#!/usr/bin/perl
#$Id: create_rig.pl,v 1.29 2023/08/23 06:17:09 sqko Exp $
use strict;
use warnings;
use RFC::Main;
my $baseuid = 600;
my $stype = `uname -r`;
if ($stype && $stype =~ /el7/)
{
    $baseuid = 1100;
}
my $str = &get_cv('main','base_userid');
if ($str && $str =~ /(\d+)/)
{
    $baseuid = $1;
}


my $u = $<;
if ($u != 0)
{
    print "must be root to run!\n";
    exit 0;
}
my $rig = shift;
if ($rig =~ /(\d+)/)
{
    $rig = $1;
}
else
{
    die "Usage: create_rig.pl rignumber, where rignumber is an integer!\n";
}
if (!$rig  || $rig > 399 || $rig < 1)
{
    die "Rig numbers only valid between 1 and 399!\n(Restriction due to NIS interfacing within DTU)\n";
}
my $apache2 = 0;
my $httpd = `locate -b httpd.conf | grep etc | grep -P '.conf\$'`;
unless ($httpd)
{
    $httpd = `locate -b apache2.conf | grep -P '.conf\$'`;
    $apache2 = 1;
}
chomp $httpd;
die "No httpd.conf or apache2.conf found!\n" unless ($httpd);
my $user;
my $group;
if ($apache2)
{
    my $string = "grep -P 'APACHE_RUN_GROUP' /etc/apache2/envvars | perl -e 'while (\$\$v = <>){chomp \$\$v; \$\$v =~ /\\=\\s\*([\\w\\-]+)\$/; print \$1};'";
    $group = `$string`;
    $string = "grep -P 'APACHE_RUN_USER' /etc/apache2/envvars | perl -e 'while (\$\$v = <>){chomp \$\$v; \$\$v =~ /\\=\\s\*([\\w\\-]+)\$/; print \$1};'";
    $user = `$string`;
}
else
{
    my $string = "grep -P '^Group' $httpd | perl -e 'while (\$\$v = <>){chomp \$\$v; \$\$v =~ /(\\w+)\$/; print \$1};'";
    $group = `$string`;
    $string = "grep -P '^User' $httpd | perl -e 'while (\$\$v = <>){chomp \$\$v; \$\$v =~ /(\\w+)\$/; print \$1};'";
    $user = `$string`;
}
my $webdir = $RFC::Header::publicdir.'rig'.$rig;

my $installfile = 'INSTALL_RIG';
open OUT, '>', $installfile or die "Cant open $installfile!!\n";
print OUT "############################\n";
print OUT "### Setting up rig $rig ####\n";
print OUT "############################\n";

my $uid = $baseuid+$rig;
### Check if rig user exists already ###
my $passwd = `/bin/cat /etc/passwd`;
if ($passwd !~ /\nrig$rig\:/)
{
    if ($apache2)
    {
	print OUT "/usr/sbin/adduser --add_extra_groups $group --uid $uid rig$rig\n";
	print OUT "/usr/sbin/usermod -a -G $group rig$rig\n";
    }
    else
    {
	print OUT "/usr/sbin/adduser -G $group -u $uid rig$rig\n";
	print OUT '/bin/echo rig',$rig,'123 | /usr/bin/passwd --stdin rig',"$rig\n";
	print OUT "/bin/echo Created celltest user rig$rig with passwd rig$rig","123\n";
	print OUT "/usr/sbin/usermod -a -G lock rig$rig\n";
    }
}
else
{
    print "Celltest user rig$rig already exists, omitting..\n";
}
### Check if rig is already added to rig list in /home/celltest/conf/celltest_global.conf ###
my @rigs = RFC::Main::get_rigs();
my $found = 0;
foreach (@rigs)
{
    next unless ($_ == $rig);
    $found = 1;
    last;
}
unless ($found)
{
    push @rigs,$rig;
    my $str = join(',',@rigs);
    my $string = "/usr/bin/perl -e 'use RFC::Main; \$c = RFC::Main::config(); \$c->change_config_value(\"celltest\",\"rigs\",\"$str\");'\n";
    print OUT $string;
    print OUT "/bin/echo \"Appended rig $rig to valid rigs. Remember to update the hostname search for valid servers as well\"\n";
    print OUT "/bin/echo \"if this is a new server (Note this may be on remote system!)\"\n";
}


&changeown('/home/rig'.$rig,'rig'.$rig,$group);
&changemod('/home/rig'.$rig,770);
#my $dir = $RFC::Header::homedir.$rig.'/';
my $dir = $webdir.'/';
&write_dir($dir);
&changeown($dir,$user,$group);
&changemod($dir,2770); ### Set created files in dir to be group sofs ###
for my $file ('flowvar.conf','impedance.conf')
{
    my $target = $dir.$file;
    print OUT "/bin/touch $target\n";
    &changeown($target,$user,$group);
    &changemod($target,660);
}
my $file = $dir.'configfile';
print OUT "/bin/cp /home/celltest/conf/configfile.stub $file\n" unless (-e $file);
print OUT "/bin/echo \"Remember to configure rig $rig corectly!\"\n" unless (-e $file);
&changeown($file,$user,$group);
&changemod($file,660);
$file = $dir.'test.nr';
print OUT "/bin/echo \"0\" > $file\n" unless (-e $file);
&changeown($file,$user,$group);
&changemod($file,660);
$file = $dir.'logbook.txt';
print OUT "/bin/touch $file\n";
&changeown($file,$user,$group);
&changemod($file,660);
my $imp_comp = $dir.'imp_comp/';
&write_dir($imp_comp);
&changeown($imp_comp,$user,$group);
&changemod($imp_comp,770);
$dir .= $rig.'test0/';
&write_dir($dir);
&changeown($dir,$user,$group);
&changemod($dir,770);
$file = $dir.'info.txt';
print OUT "/bin/touch $file\n";
&changeown($file,$user,$group);
&changemod($file,660);
$file = $dir.'proglog';
print OUT "/bin/touch $file\n";
&changeown($file,$user,$group);
&changemod($file,660);
my $ldir = '/home/rig'.$rig.'/'.$rig.'test0/';
&write_dir($ldir);
&changeown($ldir,$user,$group);
&changemod($ldir,770);
$str = "/bin/su - rig$rig -s /bin/sh -c '/usr/local/bin/celltest/CGI-server $rig > /dev/null 2> /dev/null &'";
print OUT "\n";
print OUT "/bin/echo \"Setting up automatic serverstart...\"\n";
print OUT "/bin/echo \"$str\" >> /usr/local/bin/celltest/start_servers\n" if (-e '/usr/local/bin/celltest/start_servers');
print OUT $str,"\n";
print OUT "/bin/echo \"Installing crontab for rig$rig...\"\n";
$str = "/bin/su rig$rig -s /bin/sh -c '/bin/sed \"s/XX/$rig/g\" home/conf/crontab_example.txt | crontab'";
print OUT $str,"\n";
unless ($apache2)
{
    print OUT "/bin/echo \"Seting SE-Linux context for rig$rig (may fail if SE-Linux is disabled or semanage/restroecon not installed)...\"\n";
    $str = 'semanage fcontext -a -t httpd_sys_content_t "/home/rig'.$rig.'(/.*)?"';
    print OUT $str,"\n";
    $str = 'restorecon -R /home/rig'.$rig;
    print OUT $str,"\n";
}
close OUT;
chmod 0700,$installfile if (-e $installfile);

exit;





sub changeown($$$)
{
    my $target = shift;
    $target =~ s/\/$//;
    my $user = shift;
    my $group = shift;
    my $command = "/bin/chown $user:$group $target";
    print OUT $command,"\n";
}

sub changemod($$)
{
    my $target = shift;
    $target =~ s/\/$//;
    my $mod = shift;
    my $command = "/bin/chmod $mod $target";
    print OUT $command,"\n";
}

sub write_dir($)
{
    my $dir = shift;
    chomp $dir;
    $dir =~ s/\/$//;
    if (-d $dir)
    {
        warn "Directory $dir exsists!  Omitting creation in $installfile\n";
    }
    else
    {
        print OUT "/bin/mkdir $dir\n";
    }
}
