#!/usr/bin/perl

## nappit cs installer - setup as root via: wget www.napp-it.org/nappitcs | perl
## 2024 (c) Günther Alka

use strict;

# public vars
use vars qw($dest $smartold $smart $special $be $dl $t $user $os $osver $ver $rel $osrel $ant $cgi $www $zip @w @l $l $sh $min $hour $mday $sec $mon $year $wday $ydat $isdst $log $info $conf $uconf $ustr $ustr2);


#.zip file
#######################################################################
$dl="www.napp-it.org/doc/downloads/cs_server.zip";            # with cs_server_newest

# log output
############
$log="| tee -a /tmp/setup.log\necho \" \"\n\necho \" \"\n";                                 # two lines space after log


#print/ log info beginning with echo "cc" $info
################
$info="| tee -a \tmp/setup.log\necho \"---------------------------------\"\n";              # no lines space after log


####################################################################################
## setup-script to install napp-it cs first time or to update
## napp-it cs to newest version

# script has two parts:
# part 1 perl with basics
# part 2 shellscript (autogenerated by this script to install services and tools)
#####################################################################################


#run from /tmp
###############
print "\ndownload cs_server  to /tmp\n";

     `cd /tmp`;
     $t=`pwd`;
     chomp($t);
     if ($t ne "/tmp")  {
        print "\n\n#####################\n$t\n\n";
       # exit;
     }

     ##date
     #######
     ($sec,$min,$hour,$mday,$mon,$year,$wday,$ydat,$isdst) = localtime(time);
     $mon++;
     if ($min < 10)  { $min = "0$min";   }
     if ($hour < 10) { $hour = "0$hour"; }
     if ($mday < 10) { $mday = "0$mday"; }
     if ($mon < 10)  { $mon = "0$mon";   }
     $year=1900+$year;


# Startmessage
##############
      print "\n" x20;
      print "***************************************************************************\n\n";
      print "**  Base-Setup of cs_server ZFS Server backend  Ver. 1.2                 **\n";
      print "**  for ZFS server and mixed servergroups                                **\n\n";
      print "***************************************************************************\n\n";
      print "** Actions:                                                              **\n";
      print "**  1. Basic Actions                                                     **\n";
      print "**    -  download newest cs_server                                       **\n";
      print "**    -  copy to /var/web-gui                                            **\n";
      print "**    -  opt. renme old cs_server to cs_server.last                       *\n";
      print "**   2. You need to edit server.auth (same auth as on frontend)          **\n";
      print "**    - run (root): perl /path_to_cs_server/start_cs_server_as_admin.pl  **\n\n";
      print "***************************************************************************\n\n\n";
      print "*  \n";
      print "** !! cs_server is free for noncommercial home use only !!               **\n";
      print "** !! Outside noncommercial home use  you need a Pro license!!           **\n\n";
      sleep(3);

######################################
# 1a. verify if OS has Perl or exit
######################################

      print "\n"x40;
      print "step 1a: check OS, download cs_server or updating to the most current version now\nplease wait ";
      &check_os;

      print "\n 3 \n"; sleep(2);
      print " 2 \n"; sleep(2);
      print " 1 \n"; sleep(2);


######################################
# 1b. get napp-it
######################################
        # download newest cs_server.zip via wget
        # unzip it
       ##############################

        print "step 1b:  download the most current version of cs_server now via wget\nplease wait.... ";
        &get_cs;                                                # load newest cs_server.zip


        ## prepare logfile
        `touch /tmp/setup-napp-it.log`;               # to avoid errors when missing
        $t=`rm /tmp/setup-napp-it.log`;               # opt second run



##############################
# opt delete files from last setup
##############################

        #del opt old napp-it folder
        if (-d "/tmp/cs_server_newest") {
                $t=`rm -r /tmp/cs_server_newest`;
        }

        # unzip
        print __LINE__." unzip -a /tmp/$zip\n";
        `cd /tmp && unzip -ao /tmp/$zip`;

        ##################################
        ## Solaris/Illumos:  setup smb pam
        ##################################


        #######################
        # smb.pam ok for smb? #
        #######################

       if ($osrel=~/Solaris/i) {               # 11.2 and up
                  print "\n step 1e check pam\n";
                  # verify if
                  # password required   pam_smb_passwd.so.1 nowarn                is in /etc/pam.d/other to allow smb
                  $ant=`cat /etc/pam.d/other`;
                  $t="1";
                  @l=();
                  @l=split(/\n/,$ant);
                  foreach $l (@l) {
                      if ($l=~/^password required\s+pam_smb_passwd.so.1\s+nowarn/) { $t="0"; }
                  }
                  if ($t) {
                     $ant=`echo '# smb settings set by napp-it installer' >> /etc/pam.d/other`;
                     $ant=`echo 'password required   pam_smb_passwd.so.1 nowarn' >> /etc/pam.d/other`;
                  }

        }

        if ($osrel=~/Illumos/i) {   # Illumos
                   print "\n step 1e check pam\n";
                   # verify if
                   # other   password required   pam_smb_passwd.so.1 nowarn                is in /etc/pam.conf to allow smb

                   $ant=`cat /etc/pam.conf`;
                   $t="1";
                   @l=();
                   @l=split(/\n/,$ant);
                   foreach $l (@l) {
                        if ($l=~/^\s*other\s+password required\s+pam_smb_passwd.so.1\s+nowarn/) { $t="0"; }
                   }
                   if ($t) {
                        $ant=`echo '# smb settings set by napp-it installer' >> /etc/pam.conf`;
                        $ant=`echo 'other   password required   pam_smb_passwd.so.1 nowarn' >> /etc/pam.conf`;
                   }

        }

        if ($osrel=~/Solaris|Illumos/i) {   # both

            # add user guest and enable guest?
            if (-f "/var/smb/smbpasswd") {
                print "\n step 1f, check guest\n";
                $ant=`cat /etc/passwd`;
                if (!($ant=~/\bguest:/s)) {
                    $ant=`useradd -c 'smb guest account' -s /bin/false guest 2>&1`;
                }
                $t="65929";
                $ant=`cat /etc/passwd | grep guest:`;
                chomp($ant);
                @w=split(/::/,$ant);
                if ($w[2]=~/\d/) { $t=$w[2]; }      # uid

                `smbadm enable-user guest`;         # add guest to smbpasswd

                $ant=`cat /var/smb/smbpasswd`;
                `chmod 600 /var/smb/smbpasswd`;

                @w=();
                @w=split(/\n/,$ant);
                $t="1";
                foreach my $w (@w) {
                       if ($w=~/^guest:\d+::$/)   {
                           #  $w.="2AB6A832F1FEE5F3B0A378E0465E7FA8";  # opt preset pw?
                       }
                       if ($t) {
                         `echo $w > /var/smb/smbpasswd`; # add user
                         $t="0";
                       } else {
                         `echo $w >> /var/smb/smbpasswd`; # add user
                       }
                       # print "echo $w\n";
                }
                `chmod 400 /var/smb/smbpasswd`;

            }  # /smbpw

        }   #/sol/ill

        ##########################
        # opt kill cs_server
        ##########################

        print "stop running cs_server agents\n";
        my $update=0; #                                new setup
        $t=`ps axw | grep cs_server`;
        @w=split(/\n/,$t);

        foreach my $t (@w) {
           #
           if (!($t=~/\.pl/)) { next; }                # kill socketserver, taskserver and agents and stat
           $t=~s/^ +//;
           $t=~s/ .*//;
           $update=1;                                  # update restart later

            print "kill -9 $t\n";
           `kill -9 $t`;
          }

          my $update="0";
          # cp to dest
                if (!(-d "/var/web-gui"))             { `mkdir /var/web-gui`;  }  else { $update="1";  }
                if (-d "/var/web-gui/cs_server.last") { `rm -r /var/web-gui/cs_server.last`; }
                if (-d "/var/web-gui/cs_server")      { `mv /var/web-gui/cs_server /var/web-gui/cs_server.last`; }
                `cp -R /tmp/cs_server_newest /var/web-gui/cs_server`;

                # preserve server.auth
               # if (-d "/var/web-gui/cs_server.last") {
                #   `cp /var/web-gui/cs_server.last/server.auth /var/web-gui/cs_server`;
               # }

                `rm -r /tmp/cs_server_newest`;
                `rm -r /tmp/cs_server.zip`;

          if ($update) {
             print "restart cs_server\n";
             system("perl $dest/cs_server/start_server_as_admin.pl");                # restart
          } else {
             print "\nInitial Setup:\n\nSync $dest/cs_server/server.auth with web-gui group member\nThen start cs_server from console via\n\n##########\n";
             print "perl $dest/cs_server/start_server_as_admin.pl\n##########\n\n";
             print "Up from second download, cs_server ist (re)started by this script.\n\n";
          }
          exit;

############################################## sub #####################################################################

############## 1.a
sub check_os {
############## set cgi-Folder !!
my $ok="0";
my ($ant);


  $ant=`uname -a`;
  chomp($ant);

  $dest="/var/web-gui";                 # default dest
  # if (!(-d /opt)) {  `mkdir /opt`; }

  if (-f "/etc/release") {
      #
      $osrel=`cat /etc/release`;
      $osrel=~s/\n*.*/ /s;              # first line
      if (!($osrel=~/Solaris/)) {
         $osrel.=", Illumos";
      }

      $ant.=" $osrel";
  }
  print "Your OS: $ant\n";

  #check Perl
  $t=`perl -v`;
  if ($t=~/perl/is) {
    #print "perl: $t";
  }  else {
    print "You need Perl to run cs_server.\nOn Windows download xampp.zip and start cs_server (web client or cs_server only)\n";
    exit;
  }

  $t=`wget 2>&1`;
  if ($t=~/not found/) {
     print "You need wget to download cs_server, download manually and copy cs_server to $dest (or any other any other location) and start from console.\nOn Windows download xampp.zip and start cs_server (web client or cs_server only)\n";
     exit;
  }

  $t=`unzip 2>&1`;
  if ($t=~/not found/) {
     print "You need unzip to download cs_server, download manually and copy cs_server to $dest (or any other any other location) and start from console.\nOn Windows download xampp.zip and start cs_server (web client or cs_server only)\n";
     exit;
  }

  print "Download cs_server to: $dest\n";

# end
}


#################
sub get_cs {
#################
       #load download $zip
       my ($ant,$t,$h);                                                               # dl=http://..napp-i-xx.zip

       print "start download now... ";
       $zip=$dl; $zip=~s/.*\///;

        if (-f "/tmp/$zip") {
                print "\ndeleting old zip-file\n";
                $t=`rm /tmp/$zip`;                                                       # delete opt old version
        }


        # load newest cs_server.zip
        $ant=`cd /tmp && wget $dl 2>&1`;
        if (!(-f "/tmp/$zip"))  {
                print "Download newest cs_server Version via wget ($zip): \nfailed, please try later.\n ";
                exit;
        }

        print "\nok, downloaded $zip, unzip it now..\n";
        sleep(1);

        #ok n.zip is downloaded
        print "$ant";

}


#########
sub log {
       #
       open (M, '>>/tmp/setup-napp-it.log');
            print M "$_[0]\n";
       close (M);
}


##
1;
