use strict;
use vars qw($VERSION %IRSSI);

use File::stat;
use Time::localtime;

use Irssi qw(
    command_bind settings_get_str settings_add_str timeout_add server_find_chatnet
);

$VERSION = '1.00';
%IRSSI = (
    authors     => 'Tuomas Kulve',
    contact     => 'tuomas@kulve.fi',
    name        => 'Print URLs for new photos',
    description => 'This script polls for new images' .
                   'and prints their URLs and meta information' .
                   'to IRC',
    license     => 'Public Domain',
);


sub handle_photo {
    my ($dir_in, $dir_public, $file) = @_;

    if (!rename("$dir_in/$file", "$dir_public/$file")) {
           print "Failed to rename $dir_in/$file to $dir_public/$file: $!";
           return;
    }

    my $filename = "$dir_public/$file";

    if (! -f "/usr/bin/exiftool") {
        print "No exiftool, cannot get image details";
        return;
    }

    my $cmd = "exiftool -f -s -s -s -t -c %.6f -ObjectName -Description -GPSPosition -Subject $filename";

    my $msg ="";
    my $exifmsg ="";
	
	# Add EXIF info to IRC message
    if (!open(EXIF, "$cmd |")) {
        print "Failed to run exiftool: $!";
    } else {

      my $exifout = <EXIF>;
      chomp $exifout;

      close(EXIF);

      my @data = split("\t", $exifout);


      # Title
      if ($data[0] ne "-") {
          $exifmsg .= "$data[0]: "
      }

      # Description
      if ($data[1] ne "-") {
          $exifmsg .= "$data[1]. "
      }

      #  Tags
      if ($data[3] ne "-") {
          $exifmsg .= "\[$data[3]\] "
      }

      #  GPS Location
      if ($data[2] ne "-") {
          $exifmsg .= "($data[2]) "
      }
	}

	$msg = $exifmsg;

	# Append public http URL
    my $url_prefix = settings_get_str('photos_url_prefix');
    $msg .= "$url_prefix/$file";

	# Send IRC message to appropriate channel
    my $networkname = settings_get_str('photos_notify_server_name');
    my $ircserver = server_find_chatnet($networkname);
    if (defined $ircserver) {
        my $channel  = settings_get_str('photos_notify_channel');
        $ircserver->command("/msg -channel $channel $msg");
    } else {
	  print "Failed to find server '$ircserver' in network '$network'";
	  return
	}
}

sub timeouttest {
    my ($data) = @_;

    my $dir_in     = settings_get_str('photos_dir_incoming');
    my $dir_public = settings_get_str('photos_dir_public');

    if (! -d $dir_in) {
        print "Invalid incoming photos dir: $dir_in";
        return;
    }

    if (! -d $dir_public) {
        print "Invalid public photos dir: $dir_public";
        return;
    }

    if (!opendir(DIR, $dir_in)) {
        print "Can't opendir $dir_in: $!";
        return;
    }

    my $file;
    while (defined ($file = readdir(DIR))) {
        my $filename = "$dir_in/$file";

        # TODO: what about videos? Or other non-image files.
        if (-f "$filename") {
            my $now = time();
            my $date_string = stat($filename)->mtime;
            my $diff = $now - $date_string;

            # Try to ensure that the whole image is there instead of moving 
            # a file that's still being copied.
            if ($diff > 60) {
                handle_photo($dir_in, $dir_public, $file);
            }
        }
    }

    closedir(DIR);
}


# Edit this to match your command line in the sharing-cli plugin
settings_add_str('photos', 'photos_dir_incoming',
                 "$ENV{HOME}/photos_incoming");
# Edit this to be your public www-directory name
settings_add_str('photos', 'photos_dir_public', 
                 '$ENV{HOME}/~public_html/');
# Edit this to match your IRC network name
settings_add_str('photos', 'photos_notify_server_name',
				 'NAME_OF_YOUR_IRC_NETWORK');
# Edit this to match your IRC channel
settings_add_str('photos', 'photos_notify_channel',
				 '#CHANNEL_NAME_HERE');
# Edit this to match your www address
settings_add_str('photos', 'photos_url_prefix', 
				 "http://WWW.DOMAIN.COM/~$ENV{USER}/");

# Let's poll for new images every 30 secs
timeout_add(30 * 1000, "timeouttest", "");
