#!/usr/bin/perl -w
# $Id$
# This Script (run-vm-printer2-splitter) was created by Rüdiger Beck
# It is released under the GPL Version 3
# For Bugs send mail to: jeffbeck-at-web.de

# Bibliotheken
use strict;
use Linux::Inotify2;
use File::Basename;
use File::Copy;
use File::Path;
# use log names of perl variables, i.e. $UID
use English;
use Log::Log4perl qw(:easy);

my $config_file = "/etc/leoclient2/leoclient-vm-printer2.conf";
{package Conf ; do $config_file || die "ERROR: $config_file not found or readable\n"} 

my $home=$ENV{'HOME'};
my $UID_name=getpwuid($UID);
my $EUID_name=getpwuid($EUID);
my ($GID_name)=getgrgid($GID);
my ($EGID_name)=getgrgid($EGID);

# configure logging
my $log="/tmp/run-vm-printer2-splitter.log-".$UID_name;
my $script="run-vm-printer2-splitter";
# allow everybody to log int the logfile
umask 000;
Log::Log4perl->easy_init({ 
                level   => $DEBUG,
                file    => ">>$log" } );    

INFO "##################################################";

&kill_other_scripts();
INFO "\$HOME: $home";
INFO "UID:  $UID_name ($UID)\n";
INFO "EUID: $EUID_name ($EUID)\n";
INFO "GID:  $GID_name ($GID)\n";
INFO "EGID: $EGID_name ($EGID)\n";

############################################################
# Configuration
############################################################
# where collect the print files
#OLD: my $spool_dir=$home."/".".ausdruck-winxp-spool";
my $spool_dir=$home."/Home_auf_Server/".$Conf::spool_dir_user;


#if (-e "${spool_dir}/*"){
    INFO "Removing files in ${spool_dir}";
    system("rm ${spool_dir}/* > /dev/null 2>&1");
#}

system("mkdir -p $spool_dir");
my $count=1;

# dir to watch (must be directory)
#OLD: my $dir=$home;
my $dir=$home."/Home_auf_Server".$Conf::print_dir_user;


# file to watch in dir
#OLD: my $filename="ausdruck-winxp.pdf";
#NEW:    $Conf::print_file_user


# first target name
my $target=$spool_dir."/ausdruck-1.pdf";

my $new_home_file="/tmp/heimatverzeichnis";

INFO "$script started (pid=$PROCESS_ID)";
INFO "   Watching:           $dir";
INFO "   \$print_dir_user:  $Conf::print_dir_user\n";
INFO "   \$print_file_user: $Conf::print_file_user\n";
INFO "   \$spool_dir_user:  $Conf::spool_dir_user\n";
INFO "   First Target:      $target\n";



############################################################
# Script
############################################################
### Define an Inotify2 instance
INFO "Watching $dir for incoming files";
if (not -e $dir){
    INFO "Watching $dir does not exist";
    exit;
}
my $inotify = new Linux::Inotify2
or die "Unable to create new inotify object: $!";
$inotify->watch ( $dir, IN_CLOSE_WRITE )
or die "watch creation failed";



my $kidpid = fork();
my $dead_kid=0;
if (not defined $kidpid) {
    print "No resources\n";
} elsif ($kidpid == 0) {
    INFO "Child process started with pid $PROCESS_ID";
    &splitter();
} else {
    INFO "Parent process started with pid $PROCESS_ID";
    &user_change();
    # do not wait for child, kill it
    &kill_other_scripts();
    # wait for child
    #my $dead_kid = waitpid($kidpid,0);
    INFO "Parent process will end now";
}



sub splitter{
    while () {
        my @events = $inotify->read;
        unless ( @events > 0 ) {
            print "read error: $!";
            last;
        }
        foreach( @events ) {
            my $abs_path=$_->fullname;
            my $basename=fileparse($abs_path, ".pdf");
            my $closed_file=$basename.".pdf";
            if ($closed_file eq $Conf::print_file_user){
                move("$abs_path", "$target");
                INFO "Closed file moved:   $abs_path\n           --> $target";
                # prepare target name for next file (save time)
                $count++;
                $target=$spool_dir."/ausdruck-".$count.".pdf";
            }
        }
    }
}



sub user_change{
    while (){
        if (-e "$new_home_file"){
            my $new_home=&get_new_home();
            #INFO "Userchange($PROCESS_ID): $new_home ($home)";
            if ($new_home ne $home){
                INFO "Userchange($PROCESS_ID, $new_home, $home): user has changed -> terminate";
                return;
            } else {
                # INFO "Userchange($PROCESS_ID): user unchanged -> waiting";
            }
        } else {
            INFO "Userchange($PROCESS_ID): cannot read $new_home_file";
        }
        sleep 5;
    }
}



sub kill_other_scripts {
    INFO "Killing all other scripts:";
    my $pid_string=`pgrep -f $script`;
    my (@pids) = split("\n",$pid_string);
    foreach my $pid (@pids){
        if (not $pid==$PROCESS_ID){
            my $string=`ps -o cmd= -p $pid`;
            if ($string=~/perl/){
                # make sure its the script
                INFO "   Killing $script with pid $pid";
                system("kill $pid && echo '   ---> Killed succesfully' >> $log || echo '   ---> ERROR killing $pid' >> $log");
            } else {
                INFO "   NOT Killing $string";
            }
        }
    }
}




sub get_new_home{
    my $new_home=`cat $new_home_file`;
    chomp($new_home);
    return $new_home;
}
