#!/usr/bin/perl
# ddg -- duckduckgo reader
# IDEAS:
#   - could deal with pdf's, download them, and also have pdf reader
#   display them.
#   - could add image viewing support, that the image will pop up,
#   not sure if it should get downloaded or not.
# TODO: 
#   - make the video player be a variable, maybe have to try some
#   examples.
# OTHER:
#   - if using urxvt, can put this in .Xdefaults:
#   URxvt.url-launcher:     /path/to/ddg

use File::Fetch;

### config options ###
# one other options for webbrowser may be "links -g"

$webbrowser = "google-chrome";
$soundplayer = "aplay -q";
$pdfreader = "zathura";
$imageviewer = "qiv --scale_down";

$num_args = $#ARGV + 1;
if ($num_args != 1) {
    system("$soundplayer ~/.local/sounds/kde-error1.wav &");
    system("xmessage -timeout 5 \"Error: ARG Count Wrong..\" &");
    print "\nUsage: ddg <search>\n";
    exit;
}

# limit input to 1000 chars.
$search_term = substr($ARGV[0], 0, 1000);

if($search_term =~ m!^\s*https?://(www\.)?youtube!) {
    system("$soundplayer ~/.local/sounds/kde-medium.wav &");
    system("xclip -i <<< \"$search_term\" &");
    system("xmessage -timeout 15 \"$search_term\" &");
    system("/home/kreator/.local/bin/mplayer-youtube.sh \"$search_term\" &");
} elsif($search_term =~ m!^\s*https?://\S+\.pdf($|\?)!) {
    # Handle PDFs, downloads to /tmp then displays with zathura.
    system("$soundplayer ~/.local/sounds/kde-medium.wav &");
    my $ff = File::Fetch->new(uri => $search_term);
    my $where = $ff->fetch(to => '/tmp');
    my $file = $ff->output_file;
    system("xmessage \"/tmp/$file\" &");
    system("$pdfreader \"/tmp/$file\" &");
} elsif($search_term =~ m!^\s*https?://\S+\.(jpg|png|jpeg|gif)($|\?)!) {
    system("$soundplayer ~/.local/sounds/kde-medium.wav &");
    my $ff = File::Fetch->new(uri => $search_term);
    my $where = $ff->fetch(to => '/tmp');
    my $file = $ff->output_file;
    system("xmessage \"/tmp/$file\" &");
    system("$imageviewer \"/tmp/$file\" &");
} elsif($search_term =~ m!^\s*https?://!) {
    system("$soundplayer ~/.local/sounds/kde-special.wav &");
    system("$webbrowser \"$search_term\" &");
} else {
    system("$soundplayer ~/.local/sounds/kde-special.wav &");
    system("$webbrowser \"https://duckduckgo.com/lite?q=$search_term\" &");
}


