#!/opt/bin/perl

use strict;
use warnings;

use CGI;
use File::Basename;
use File::Spec;
use Path::Trim;

my $cgi = CGI->new();

if ( my $file = $cgi->param('file') ) {
    if ( $cgi->param('subs') ) {
		print $cgi->header(), $cgi->start_html('Subtitles');
		print $cgi->h1("Downloading subs for $file");
		$ENV{"PATH"} = "/volume1/web/cgi-bin/:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";
		print $cgi->pre(qx(/volume1/web/cgi-bin/filebot_sub.sh \"$file\" 2>&1));
		print $cgi->end_html();
    } elsif ( $cgi->param('mediainfo') ) {
		print $cgi->header(), $cgi->start_html('MediaInfo');
		print $cgi->h1("MediaInfo for $file");
		$ENV{"PATH"} = "/volume1/web/cgi-bin/:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";
		print $cgi->pre(qx(mediainfo \"$file\" 2>&1));
		print $cgi->end_html();
    } elsif ( $cgi->param('rename') ) {
		print $cgi->header(), $cgi->start_html('Rename');
		print $cgi->h1("Rename for $file");
		$ENV{"PATH"} = "/volume1/web/cgi-bin/:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";
		print $cgi->pre(qx(/volume1/web/cgi-bin/filebot_rename.sh \"$file\" 2>&1));
		print $cgi->end_html();
    } else {
        open my $fh, '<', $file or die $!;

        print $cgi->header(
            '-type'           => 'application/octet-stream',
            '-attachment'     => basename($file),
            '-Content_Length' => -s $file,
        );

        binmode $fh;
        print while <$fh>;
    }
}
else {
	my $path = $cgi->param('path');
	print $cgi->header(), $cgi->start_html('Subtitles');
	# remove redundant current directory and parent directory entries
	my $pt = Path::Trim->new();
	$pt->set_directory_separator('/');
	$path = $pt->trim_path($path);

  # remove all ../ and ./ that have accumulated at the beginning of the path and
  # make the path absolute by prepending a /
	$path =~ s{^ (\.\.? /)+ }{}x;
	$path = "/$path" unless $path =~ m{^ / }x;

	if ( $cgi->param('subs') ) {
		print $cgi->h1("Downloading subs for $path");
		$ENV{"PATH"} = "/volume1/web/cgi-bin/:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";
		print $cgi->pre(qx(/volume1/web/cgi-bin/filebot_sub.sh \"$path\" 2>&1));
		print $cgi->end_html();
	} elsif ( $cgi->param('rename') ) {
		print $cgi->h1("Renaming $path");
		$ENV{"PATH"} = "/volume1/web/cgi-bin/:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";
		print $cgi->pre(qx(/volume1/web/cgi-bin/filebot_rename.sh \"$path\" 2>&1));
		print $cgi->end_html();
	}
	else {

		print $cgi->h1($path);

		opendir my $dh, $path or die $!;
		#my @entries = grep { $_ !~ /^ \. $/x } readdir $dh;
		my @entries = readdir $dh;
		closedir $dh;
		
		my $showall = $cgi->param('showall');
		my $sortmode = $cgi->param('sortmode');
		if ( $showall ) {
			print $cgi->a( { 'href' => "?path=$path&showall=0&sortmode=$sortmode" }, "Hide films with subs" );
		} else {
			print $cgi->a( { 'href' => "?path=$path&showall=1&sortmode=$sortmode" }, "Show all" );
			$showall = 0
		}
		print $cgi->p();
		if ( $sortmode ) {
			print $cgi->a( { 'href' => "?path=$path&showall=$showall&sortmode=0" }, "Sort by date" );
		} else {
			print $cgi->a( { 'href' => "?path=$path&showall=$showall&sortmode=1" }, "Sort alphabetically" );
			$sortmode = 0
		}
		print $cgi->start_ul();
		my @sorted_list = sort { -M "$path/$a" <=> -M "$path/$b" } @entries;
		if ( $sortmode ) {
			@sorted_list = sort { $a cmp $b } @entries;
		}
#		for my $entry ( sort { $a cmp $b } @entries ) {
		for my $entry ( @sorted_list ) {
			if ( -d File::Spec->catfile( $path, $entry ) ) {
				my $abs_entry = File::Spec->catfile( $path, $entry );
				my $anchor = $cgi->a( { 'href' => "?path=$abs_entry&showall=$showall&sortmode=$sortmode" }, $entry );
				my $subs = $cgi->a( { 'href' => "?subs=1&path=$abs_entry&showall=$showall&sortmode=$sortmode" }, "[ subs ]" );
				my $rename = $cgi->a( { 'href' => "?rename=1&path=$abs_entry&showall=$showall&sortmode=$sortmode" }, "[ rename ]" );
				print $cgi->li($anchor, $subs, $rename);
			}
			else {
				my $abs_entry = File::Spec->catfile( $path, $entry );
				my $anchor = $cgi->a( { 'href' => "?file=$abs_entry" }, $entry );
				my($basename, undef, $ftype) = fileparse($entry,qr'\.[^\.]*');
				my $subfile = File::Spec->catfile( $path, $basename . ".srt" );
				my $nldsubfile = File::Spec->catfile( $path, $basename . ".nld.srt" );
				my $engsubfile = File::Spec->catfile( $path, $basename . ".eng.srt" );
				my $nldsubfile2 = File::Spec->catfile( $path, $basename . ".nl.srt" );
				my $engsubfile2 = File::Spec->catfile( $path, $basename . ".en.srt" );
				my $mediainfo = $cgi->a( { 'href' => "?mediainfo=1&file=$abs_entry" }, "[ mediainfo ]" );
				if ( ( "$ftype" ne ".srt" ) && !( -e $subfile ) && !( -e $nldsubfile ) && !( -e $engsubfile ) && !( -e $nldsubfile2 ) && !( -e $engsubfile2 ) ) {
					my $subs = $cgi->a( { 'href' => "?subs=1&file=$abs_entry" }, "[ subs ]" );
					my $rename = $cgi->a( { 'href' => "?rename=1&file=$abs_entry" }, "[ rename ]" );
					print $cgi->li($anchor, $subs, $mediainfo, $rename);
				} else {
					if ( $showall ) {
						my $subs = $cgi->a( { 'href' => "?subs=1&file=$abs_entry" }, "[ subs ]" );
						my $rename = $cgi->a( { 'href' => "?rename=1&file=$abs_entry" }, "[ rename ]" );
						print $cgi->li($anchor, $subs, $mediainfo, $rename);
					}
				}
			}
		}
		print $cgi->end_ul(), $cgi->end_html();
	}
}

