#!/usr/bin/perl
#
#
############################################
#                                          #
#     YPLib 0.3 - Your Personal Library     #
#         written by Jan Schaumann         #
#                                          #
#     YPLib 0.3 is published under the      #
#     GPL and comes with no warranty       #
#                 whatsoever               #
#                                          #
#     You can obtain YPLib 0.3 (or maybe    #
#      even more recent versions) from     #
#         http://www.netmeister.org        #
#                                          #
#       Please send all Bug-Reports to     #
#          <jschauma@netmeister.org>       #
#                                          #
#     This is "yplibd" - the Personal       #
#      Library Daemon. You need to         #
#      run yplibd from your crontab         #
#                                          #
#       See crontab(5) and yplib(1) for     #
#              more information            #
#                                          #
############################################

############################################
#                                          #
#       Change the location fo sendmail    #
#               if not corrent             #
#                                          #
############################################
$sendmail = "/usr/sbin/sendmail";

use Shell qw(date touch rm mkdir cat);

my $Version = "0.3";
my $home = $ENV{HOME};
my $thepath = "$home/.yplib";
my $prefs = "$thepath/yplib.prefs";
my $libs = "$thepath/libs";
my $outbooks = "$thepath/out";
my $message = "$thepath/message";


############################################
#                                          #
#   if you are not using BASH, edit the    #
#        following line accordingly        #
#                                          #
############################################
my $shell = "$home/.bashrc";

sub getDate;

-d $thepath or mkdir $thepath;

touch $message;
my $flag = 0;
my $numofbooks = 0;
my $duebooks = 0;

open(MESSAGE, ">$message") or die "Cannot open $message! Please assure that $messag exists, and possibly run \"yplib\" again!"; 

open(MESSAGE, ">$message") or die "Cannot open $message! Please assure that $messag exists, and possibly run \"yplib\" again!"; 
-e $outbooks or print MESSAGE "I could not find $outbooks - this means you have not yet run the main-program (\"yplib\"). Please do so before you let me check if any books are due.\nHave a nice day!\n\nYour Personal Library Daemon" and $flag=1;

open(MESSAGE, ">$message") or die "Cannot open $message! Please assure that $messag exists, and possibly run \"yplib\" again!"; 
-e $prefs or print MESSAGE "I could not find $prefss - this means you have not yet run the main-program (\"yplib\"). Please do so before you let me check if any books are due.\nHave a nice day!\n\nYour Personal Library Daemon" and $flag=1; 

open(MESSAGE, ">$message") or die "Cannot open $message! Please assure that $messag exists, and possibly run \"yplib\" again!"; 
open(LIBS, "$libs") or print MESSAGE "I could not find $libs - this means you have not yet run the main-program (\"yplib\"). Please do so before you let me check if any books are due.\nHave a nice day!\n\nYour Personal Library Daemon" and $flag=1; 

# get the users preferences
my $email = $ENV{LOGNAME} . "@" . $ENV{HOSTNAME};

my $noshell = 0;
if ($ARGV[0] eq "-nl") {
	$noshell = 1;
}

if (($ARGV[0] eq "-h") || ($ARGV[0] eq "--help")) {
	print "\n\"yplibd\" is part of \"YPLib\", Your Personal Library.\n";
	print "Please see yplib(1), yplibd(1) and\/or\n";
	print "http:\/\/www.netmeister.org\/apps\/yplib\/index.html for further information.\n\n";
	print "Usage: yplibd [OPTION]\n";
	print "OPTIONS:\n";
 	print "   -h, --help      print out this screen and exit\n";
	print "   -nl             do not print warning into ~/.bashrc\n";
	print "   -v, --version   print out version number and exit\n\n";
	exit(0);
}

if (($ARGV[0] eq "-v") || ($ARGV[0] eq "--version")) {
	print "yplibd version: $Version\n";
	exit(0);
}

####################################
# first clean up the shellrc       #
####################################
	my $tmpshell = "";
	open (SHELL, "$shell");
	LINE: while ($_ = <SHELL>) {
		last LINE if m/begin warning for YPLib/;
		$tmpshell = $tmpshell . $_;
	}

	close SHELL;
	open (SHELL, ">$shell");
	chomp($tmpshell);
	print SHELL $tmpshell;
	close SHELL;
####################################
# begin main procedure             #
####################################

unless ($flag==1) {
  my $thedate = `date +%D`;
  my $absolutedate = 0;
  my $absoluteduedate = 0;
  
  $absolutedate = getDate($thedate);
  
  # get the users preferences
  open(PREFS, "$prefs") or print MESSAGE "I could not open $prefs! Please checkthe permissions on this file, and run \"yplib\" again.\nHave a nice day!\n\nYour Personal Library Daemon";
  my @prefs = split /:/, <PREFS>;
  my $email = $prefs[5];
  
  my $remind = $prefs[1];
  $numofbooks = $prefs[7]; 
  # if no books are rented, we don't need to do anything
  unless ($numofbooks==0) {
    @fine;
    @owelibs;
    $i = 0;
    $numoverduebooks = 0;
    $duetoday = 0;
    $firstduetoday = 0;
    $firstduesoon = 0;
    $firstoverdue = 0;
    
    open(MESSAGE, ">>$message") or die;
    print MESSAGE "Subject: Return the book(s) soon!\n";
    print MESSAGE "Hello!\nThis is YPLibd, your Personal Library Daemon.\n";
    print MESSAGE "A while ago you rented a few books, and it is my job to make sure you won't forget to return them.\n";
    open(OUT, "$outbooks") or die;
    while ($line = <OUT>) {
      $absoluteduedate = 0;
      $thedate = `date +%D`;
      @current = split /:/, $line;
      $owelibs[$i] = $current[5];
      $i++;
      $absoluteduedate = getDate($current[3]);
      @duedate = split /\//, $current[3];	
      
      # a book is due today
      if ($absoluteduedate==$absolutedate) {
		unless ($noshell) {
			$editshell = 1;
			open(SHELL, ">>$shell");
		}
		if ($firstduetoday == 0) {
	  		print MESSAGE "\nThe following book(s) is/are due TODAY:\n";
			unless ($noshell) {
				print SHELL "\n\# begin warning for YPLib";
	  			print SHELL "\necho \"The following book(s) is/are due TODAY:\"\n";
		  	}
		}
		chomp($current[7]);
	   	print MESSAGE "\n\"$current[1]\" by $current[7]\n";
		unless ($noshell) {
	   		print SHELL "\necho \"$current[1] by $current[7]\"";
		}
	  	# from which library is the book?
	  	print MESSAGE "Library:"; 
	  	open(LIBS, "$libs") or die;
	  	while ($libline = <LIBS>) {
	  		@tmp = split /:/, $libline;
	  		$thelib = $tmp[0];
	  		if ($thelib==$current[5]) {
	    		print MESSAGE "$tmp[1]\n\t\t$tmp[2]\n\t\t$tmp[3]\n";
	  		}	
	  	}
	  	$firstduetoday = 1;
      }
      
      # books are due soon
      if (($absoluteduedate-$remind)==$absolutedate) {
		if ($firstduesoon==0) {
	  		print MESSAGE "\nThe following book are due on $duedate[0]\/$duedate[1]\/$duedate[2]:\n";
		}
		chomp($current[7]);
	  	print MESSAGE "\n\"$current[1]\" by $current[7]\n";
		# from which library is the book?
		print MESSAGE "Library:";
		open(LIBS, "$libs") or die;
		while ($libline = <LIBS>) {
	  		@tmp = split /:/, $libline;
	  		$thelib = $tmp[0];
	  		if ($thelib==$current[5]) {
	    		print MESSAGE "$tmp[1]\n\t\t$tmp[2]\n\t\t$tmp[3]\n";
	  		}
		}
		$firstduesoon = 1;
      }
      
      # books are overdue
      if ($absoluteduedate<$absolutedate) {
		unless ($noshell) {
			open(SHELL, ">>$shell");
			$editshell = 1;
		}
		if ($prevdate!=$absoluteduedate) {
	 	 	print MESSAGE "\nThe following books are overdue since $duedate[0]\/$duedate[1]\/$duedate[2]:\n";
			unless ($noshell) {
				print SHELL "\n\# begin warning for YPLib";
	  			print SHELL "\necho \"The following book(s) is/are overdue since $duedate[0]\/$duedate[1]\/$duedate[2]:\"\n";
			}
		}
		chomp($current[7]);
		print MESSAGE "\n\"$current[1]\" by $current[7]\n";
		unless ($noshell) {
			print SHELL "\necho \"$current[1] by $current[7]\"";
		}
		# from which library is the book?
		print MESSAGE "Library:";
		open(LIBS, "$libs") or die;
		while ($libline = <LIBS>) {
	  		@tmp = split /:/, $libline;
	  		$thelib = $tmp[0];
	  		if ($thelib==$current[5]) {
	    		print MESSAGE "$tmp[1]\n\t\t$tmp[2]\n\t\t$tmp[3]\n";
	    		$numoverduebooks++;
	  		}
		}
	
		# books are overdue, we owe money
	
		open(LIBS, "$libs") or die;
		while ($libline = <LIBS>) {
	  		@tmp = split /:/, $libline;
	  		$thelib = $tmp[0];
	  		if ($thelib==$current[5]) {
	    		$fine[$tmp[0]] += $tmp[4]*($absolutedate-$absoluteduedate);
	  		}
		}
	
		$prevdate = $absoluteduedate;
		$firstoverdue = 1;
      }
    }

	if ($editshell && (!$noshell)) {
		print SHELL "\necho \"Please return the books and remove them from the record by running bday.\"\n";
		print SHELL "\# end warning for YPLib\n";
	}

    # print how much we owe
    open(LIBS, "$libs") or die;
    @printowe;
    while ($libline = <LIBS>) {
      @tmp = split /:/, $libline;
      for ($j=0; $j<$i; $j++) {
		if($tmp[0]==$owelibs[$j]) {
	  		if (($fine[$tmp[0]]>0)&&($printowe[$owelibs[$j]]!=1)) {
	    		print MESSAGE "\nYou owe $fine[$tmp[0]] cents to the Library \"$tmp[1]\".\n";
	    		$printowe[$owelibs[$j]] = 1;
	  		}
		}
      }
    }
    
    if (($firstoverdue==1)||($firstduetoday==1)||($firstduesoon==1)) {
      $duebooks = 1;
    }
  }
  
  
  print MESSAGE "\nThis is an automated message, please do not respond.\nHave a nice day!\n\nYour Personal Library Daemon";
}

close MESSAGE;

if (($numofbooks>0) && ($flag==0) && ($duebooks>0)) {
  `cat $message | $sendmail -F "Your Personal Library Daemon" $email`;
}


sub getDate {
  $returndate = 0;
  @adate = split /\//, @_[0];
  if ($adate[0]==1) {
    $returndate == $adate[1];
  }
  elsif ($adate[0] == 2) {
    $returndate += (31+$adate[1]);
  }
  elsif ($adate[0] == 3) {
    $returndate += (59+$adate[1]);
  }
  elsif ($adate[0] == 4) {
    $returndate += (90+$adate[1]);
  }
  elsif ($adate[0] == 5) {
    $returndate += (120+$adate[1]);
  }
  elsif ($adate[0] == 6) {
    $returndate += (151+$adate[1]);
  }
  elsif ($adate[0] == 7) {
    $returndate += (181+$adate[1]);
  }
  elsif ($adate[0] == 8) {
    $returndate += (212+$adate[1]);
  }
  elsif ($adate[0] == 9) {
    $returndate += (243+$adate[1]);
  }
  elsif ($adate[0] == 10) {
    $returndate += (273+$adate[1]);
  }
  elsif ($adate[0] == 11) {
    $returndate += (304+$adate[1]);
  }
  elsif ($adate[0] == 12) {
    $returndate += (334+$adate[1]);
  }
  
  # add the first 2000 years
  $returndate += (2000*365);
  $returndate += ($adate[2]*365);
}






