#!/usr/bin/perl -w
# This Script (linuxmuster-client-extras-setup) was created by Rüdiger Beck
# It is released under the GPL Version 3
# For Bugs send mail to (jeffbeck-at-web.de)

use strict;
use Getopt::Long;
use File::Basename;
use English;

my $old_script_warning=0;

my $UID_name=getpwuid($UID);
my $EUID_name=getpwuid($EUID);
my $scriptname="linuxmuster-client-extras-setup";

if ($UID!=0 or $EUID!=0){
    print "\nYou need to be root to run $0\n\n";
    exit;
}

my $config_dir="";

# /etc/xdg/autostart/linuxmuster-client-extra.desktop must exist to run 
# /usr/bin/linuxmuster-client-extras-login that runs all scripts as user
my $autostart_file_source="/usr/share/linuxmuster-client-extras/linuxmuster-client-extras.desktop";
my $autostart_file_target="/etc/xdg/autostart/linuxmuster-client-extras.desktop";
system("cp $autostart_file_source $autostart_file_target");
system("chmod 0644 $autostart_file_target");


# todo
# ??? Is there something similar for logoff
#
#
# --info
#
# Scripts/Binaries run on user login:
#  S | T | Linkname                  | Script/Binary
#----+---+---------------------------+-------------------------------------
#  E | P | 020-set-default-printer   | /usr/bin/set-default-printer.sh
#  D | P | 030-setup-italc-rooms     | /usr/bin/setup-italc-rooms
#  E | C | 035-lsof                  | /usr/bin/lsof
# S = Status, E = Enabled, D = Disabled
# T = Type, P = Script from a linuxmuster.net package, C = Custom Script

my $help=0;
my $info=0;
my $type="";

my $delete_old_stuff=0;
my $off="";
my $on="";
my $order="";



# just for testing
#my @delete_old_stuff=("/usr/bin/ahjdsahdask",
#                     ); 

my @delete_old_stuff=(
#    "/usr/bin/watch-my-home", 
    "/etc/xdg/autostart/Standarddrucker-nach-Raum.desktop", 
    "/usr/bin/standarddrucker-nach-raum.sh", 
    "/usr/bin/standarddrucker-nach-raum.sh~", 
    "/etc/xdg/autostart/italcRaumanpassung.desktop", 
    "/usr/bin/italc-raumanpassung.sh", 
    "/usr/bin/italc-raumanpassung.sh~", 
    "/usr/bin/herunterfahren.sh", 
    "/usr/bin/checkshutdown.sh", 
    "/etc/xdg/autostart/DesktopIconshinzu.desktop", 
    "/etc/xdg/autostart/postlogin-xhost-root.desktop", 
    "/usr/bin/desktop-icons-hinzu.sh", 
    "/usr/bin/desktop-icons-hinzu-88591.sh", 
    "/usr/bin/desktop-icons-hinzu-Arbeitsfl.sh", 
    "/etc/xdg/autostart/VirtualBoxConfCopy.desktop", 
    "/usr/bin/virtualbox-vm-conf-kopieren.sh", 
    "/usr/bin/ausdruck-winxp-splitter", 
    "/usr/bin/ausdruck-winxp-spooler", 
    "/usr/bin/leoclient-admin", 
    "/usr/bin/serverinformationen-anzeigen.sh", 
    "/etc/cron.d/serverinformationen-anzeigen", 
    "/etc/cron.d/checkshutdown", 
   );

my @old_script_warning_lines=(
      "\nWARNING:\n The following files are replaced by the linuxmuster-client-extras",
      " and leoclient package. You should delete them BEFORE installing above packages:\n");

my %script_link_map = (
    "/usr/bin/setup-virtualbox",               "010-setup-virtualbox",
    "/usr/bin/set-default-printer",            "020-set-default-printer", 
    "/usr/bin/setup-italc-rooms",              "030-setup-italc-rooms",
    "/usr/bin/create-desktop-icons",           "040-create-desktop-icons",
    "/usr/bin/setup-show-server-information",  "050-setup-show-server-information",
    "/usr/bin/run-vm-printer-splitter",        "060-run-vm-printer-splitter",
    "/usr/bin/run-vm-printer-spooler",         "070-run-vm-printer-spooler",
    "/usr/bin/run-vm-printer2-splitter",       "060-run-vm-printer2-splitter",
    "/usr/bin/run-vm-printer2-spooler",        "070-run-vm-printer2-spooler",
    "/usr/bin/watch-my-home",                  "080-watch-my-home", 
    "/usr/bin/xhost-root",                     "090-xhost-root", 
   );




# Parsen der Optionen
my $testopt=GetOptions(
           "help|h" => \$help,
           "info|i" => \$info,
           "type=s" => \$type,
           "delete-old-stuff" => \$delete_old_stuff,
           "off=s" => \$off,
           "on=s" => \$on,
           "order=s" => \$order,
          );

# Prüfen, ob Optionen erkannt wurden, sonst Abbruch
&check_options($testopt);

# set config dir
if ($type eq "" and $help==0){
    print "\n   Option --type must be set\n\n";
    exit;
} elsif ($type eq "login"){
    $config_dir="/etc/linuxmuster-client/extras/login-enabled";
} elsif ($type eq "" and $help==1){
    $config_dir="/etc/linuxmuster-client/extras/login-enabled";
} else {
    print "\n   Unknown Type:  $type\n\n";
    exit;
}


if ($help==1){
   print("With $scriptname you can setup scripts to be run on user login|... on the linuxmuster Linux client.\n",
'All linked scripts/programs are run in the order given by the 3-digit string at the beginning of the linkname.

For scripts known to ',"$scriptname",' the 3-digit string is looked up automatically. 
For your own custom scripts, you must use the option --order to submit the 3-digit string.

On user login the script /usr/bin/linuxmuster-client-extras-login is executed to run all the linked scripts.
See the help there for debugging info.

Options:
  -h  / --help

  -i  / --info
    List all links in the configuration directory

  --type login|...
    Where to create the links:
    ',$type,':   ',$config_dir,'
    ...

  --off ',"$config_dir",'/123-link
    Remove the link = Do not start this script on login.

  --on /absolute/path/to/executable/script
    Adds a link in ',"$config_dir",' to start this script on login.

  --order numberstring
    When creating links to own scripts, you have to state, WHEN they will be executed.
    The numberstring given as option must have 3 digits and is prefixed to the scriptname
    to result in the linkname.

  --delete-old-stuff
    Delete all old files from a manual install. Will be deprecated.

Examples: 
 Switching a servive on/off on login:
   linuxmuster-client-extras-setup --type login --on /usr/bin/watch-my-home
   linuxmuster-client-extras-setup --type login --off /etc/linuxmuster-client/extras/login-enabled/080-watch-my-home

');
   print "\n";
   exit;
}


# make sure config directory exists
if ($config_dir ne "" and not -d $config_dir){
    system("mkdir -p $config_dir");
    # ????? set permissions
}


# Checking for old scripts
foreach my $file (@delete_old_stuff) {
    if (-e $file){
        $old_script_warning=1;
        push  @old_script_warning_lines , "    $file\n";
    }
}


if ($old_script_warning==1){
    foreach my $line (@old_script_warning_lines) {
        print $line;
    }
    print "\n";
}


if ($delete_old_stuff==1){
    foreach my $file (@delete_old_stuff) {
        if (-e $file){ 
            print "Deleting $file\n";
            system("rm $file");
        }
    }
    print "\nDeleting old stuff finished\n\n";
    exit;
}







# --info
if ($info==1){
    system("ls -lGg --color $config_dir");
    exit;
}


# --off
if ($off ne ""){
    &check_abs_path($off);
    # removing links
    if (-l $off and $off=~m/^$config_dir/){
        unlink $off;
    } else {
        print "\nDoing nothing!\n",
              "   $off\n",
              " is not a link in  \n",
              "   $config_dir\n\n";
    }
}



# --on
if ($on ne ""){
    # a link is correct -> bug ???
    if (not -x $on){
        print "\n$on is nonexisting/not executable\n\n";
        exit;
    }
    if (exists $script_link_map{$on}){
        my $linkname=$config_dir."/".$script_link_map{$on};
        &create_symlink($on,$linkname);
    } else {
        if ($order eq ""){
	    print "\nPlease use option --order to confige WHEN your custom script will be run.\n\n";
	} elsif ($order=~m/[0-9]/){
            my $basename = basename($on);
            my $linkname=$config_dir."/".$order."-".$basename;
            &create_symlink($on,$linkname);
        } else {
            print "\nThe value of option --order has to consist of digits from 0 to 9.\n\n";
        }
    }
}




############################################################
# subs
############################################################

sub check_abs_path {
    # check if argument is an absolute path
    my ($path) = @_;
    if ($path=~m/^\//){
        # path is absolute, continue
    } else {
        print "\nPlease use the absolute path to $path\n\n";
        exit;
    }

}

sub create_symlink {
    my ($script,$linkname) = @_;
    &check_abs_path($script);
    print "Creating Link:\n",
          "   $linkname\n",
          "to script:\n",
          "   $script\n";
    if (-l $linkname){
        system("rm $linkname");
    }
    symlink $script, $linkname;
}




sub  check_options{
   my ($parse_ergebnis) = @_;
   if (not $parse_ergebnis==1){
      my @list = split(/\//,$0);
      my $scriptname = pop @list;
      print "\nYou have made a mistake, when specifying options.\n"; 
      print "See error message above. \n\n";
      print "... $scriptname is terminating.\n\n";
      exit;
   } else {
      #print "All options  were recognized.\n";
   }

}

