#!/bin/bash
# 
# Copyright (c) 2024 Skycloud Software Corporation
#
# This script installs SkyForm AIP from tar file to a directory of a
# shared file system. It sets up SkyForm AIP configuraiton files as well
# based on a hostlist.
#
# By default, the path of the shared directory is: /opt/skyformai_shared
# By default, the path of the local SkyForm AIP top directory is: /opt/skyformai
#

usage() {
        echo "Usage: $0 [--shared=top_shared_dir] (default: /opt/skyformai_shared)"
        echo "          [--localtop=local_top_dir] (default: /opt/skyformai)"
        echo "          [--hosts=hosts_file] (default: hosts)"
        echo "          [--admin=user_name] (default: cadmin)"
        echo "          [--ncpus=threads|cores]"
        echo "          [--crv_port=port]"
        echo "          [--noint|--silent]"
        echo "          [--eda]"
        exit 1
}

i_top=/opt/skyformai_shared
i_local=/opt/skyformai
i_admin=cadmin
i_hostfile=hosts
existing=0
aiptools=0
noint=0
localcadminuid=1100
ncpus_change=0
crv_port=0
ncpus=cores
eda=0

umask 022
bindirs="bin sbin lib64 share"
non_bindirs="etc log work"

if [ $(hostname -s) == 'localhost' ]; then
    echo Please give a name to the local host by running \"hostnamectl set-hostname NAME\"
    echo "Installation failed!"
    exit 1
fi

if [ $(id -u -n) != "root" ]; then
    echo "Please run the script as root!"
    echo "Installation failed!"
    exit 1
fi

while [ $# != '0' ]; do
  case $1 in
  *=*) optarg=`expr "X$1" : '[^=]*=\(.*\)'` ;;
  *)  optarg=no ;;
  esac

  case $1 in
  --shared=*)  
	i_top=$optarg
	;;
  --localtop=*)
	i_local=$optarg
	;;
  --hostlist=*)
        i_hostfile=$optarg
        ;;
  --hosts=*)
	i_hostfile=$optarg
	;;
  --clustername=*)
        i_cname=$optarg
        ;;
  --admin=*)
        i_admin=$optarg
        ;;
  --ncpus=*)
        ncpus_change=1
        ncpus=$optarg
        ;;
  --crv_port=*)
        cpv_port=$optarg
        ;;
  --noint|--silent)
        noint=1
        ;;
  --eda)
        eda=1
        ncpus_change=1
        ncpus=threads;
        ;;
  --help | -h)
	usage ;;
  *)
	echo "ERROR: Invalid option"
        usage ;; 
  esac
  shift
done

if [ $noint == 0 ]; then
    read -p 'Shared directory for AIP install ['$i_top']: ' i_top_replace
    if [ ! -z $i_top_replace ]; then
        i_top=$i_top_replace
    fi
    read -p 'Local directory for AIP symbolic links ['$i_local']: ' i_local_replace
    if [ ! -z $i_local_replace ]; then
        i_local=$i_local_replace
    fi
    while true; do
        read -p 'Primary administrator user name ['$i_admin']: ' i_admin_replace
        if [ ! -z $i_admin_replace ]; then
            i_admin=$i_admin_replace
        fi
        if ! getent passwd $i_admin > /dev/null; then
            echo '!!! User' $i_admin does not exist '!!!'
            read -p 'Create the local user '$i_admin' [y/N]? ' yesno
            if [ _$yesno == '_y' ] || [ _$yesno == '_Y' ]; then
                useradd -u $localcadminuid $i_admin
                break
            fi
        else
            break
        fi
    done
    read -p 'Number of CPUs: threads|cores [unchange]: ' ncpus
    if [ ! -z $ncpus ]; then
        ncpus_change=1
    fi
    while true; do
        read -p 'Hosts file name ['$i_hostfile'] :' i_hostfile_replace
        if [ ! -z $i_hostfile_replace ]; then
            i_hostfile=$i_hostfile_replace
        fi
        if [ ! -f $i_top/etc/hosts ] && [ ! -f $i_hostfile ]; then
            echo "!!! Cannot find cluster hosts file $i_hostfile."
            read -p 'Just install local host [y/N] ?' yesno
            if [ _$yesno == '_y' ] || [ _$yesno == '_Y' ]; then
                echo $(hostname -I | awk '{print $1}') $(hostname -s) > hosts
                break;
            fi
        else
            break
        fi
    done
else
    if ! getent passwd $i_admin > /dev/null; then
        echo Creating local user: $i_admin
        useradd -u $localcadminuid $i_admin
    fi

    if [ ! -f $i_top/etc/hosts ] && [ ! -f $i_hostfile ]; then
        echo "Cannot find cluster hosts file. Just use local host"
        echo $(hostname -I | awk '{print $1}') $(hostname -s) > hosts
    fi
fi

echo "SkyForm AIP files will be installed in a shared file system under:"
echo "    [$i_top]"
echo "SkyForm AIP configuration files will be set so that the local"
echo "SkyForm AIP top directory is:"
echo "    [$i_local]"
echo "Existing configuration and working directories will not be overridden."
if [ $noint == '0' ]; then
   read -p "Please enter to continue..."
fi

distro=`ls [1-9]*.tar.gz`

if [ "X$distro" == "X" ]; then
    echo "No AIP distribution files are found."
    exit 1
fi   

echo Found packages:
for package in $distro; do
   echo "    " $package
done
if [ $noint == '0' ]; then
   read -p "Press enter to install..." 
fi

if [ ! -d $i_top ]; then
   mkdir -p $i_top
fi

if [ -f $i_top/etc/cb.yaml ]; then
   existing=1
fi

for package in $distro; do
   subdirname=`expr "$package" : '\(.*\).tar.gz'`
   tar xfz $package -C $i_top
   if [ ! -d $i_top/$subdirname/orig ]; then
     mkdir -p $i_top/$subdirname/orig
   fi
   for nb in $non_bindirs; do
	if [ ! -d $i_top/$nb ]; then
	     cp -rf $i_top/$subdirname/$nb $i_top
             if [ $nb == "etc" ]; then
                 rm -r $i_top/etc/skyformcrv/*
             fi
	else
            if [ $nb == "etc" ]; then
                for file in aip aip.csh aip.sh aiprestd.service aip.service aip.systemd gpu.yaml; do
                    cp -rf $i_top/$subdirname/$nb/$file $i_top/$nb
                done
                if [ ! -f $i_top/$nb/jservice.yaml ] && [ -f $i_top/$subdirname/$nb/jservice.yaml ]; then
                    cp -rf $i_top/$subdirname/$nb/jservice.yaml $i_top/$nb
                fi
                if [ ! -f $i_top/$nb/jumpserver.yaml ] && [ -f $i_top/$subdirname/$nb/jumpserver.yaml ]; then
                    cp -rf $i_top/$subdirname/$nb/jumpserver.yaml $i_top/$nb/jumpserver.yaml
                fi
            fi
        fi
        if [ -d $i_top/$subdirname/orig/$nb ]; then
          rm -rf $i_top/$subdirname/orig/$nb
        fi
	mv -f $i_top/$subdirname/$nb $i_top/$subdirname/orig
   done
   pushd . > /dev/null
   if [ $existing == "1" ] && [ -d $i_local/sbin ]; then
      cd $i_local/sbin
      cp -f ress.* cbls.remote* echkpnt.* erestart.* esub eexec \
         $i_top/$subdirname/sbin 2> /dev/null
   fi
   cd $i_top/$subdirname/orig/etc
   for file in aip* lsf.conf olmon cbcrond.yaml; do
       sed -i "s|/cubetop|$i_local|g" $file
   done
   popd > /dev/null
done

# copy the host-setup script to the shared location
cp host-setup gui-setup $i_top/

# change cb.conf shell resource files and service file
for file in $i_top/etc/aip* $i_top/etc/lsf.conf $i_top/etc/olmon \
            $i_top/etc/cbcrond.yaml; do
   sed -i "s|/cubetop|$i_local|g" $file
done

if [ -f $i_top/etc/skyformcrv/html/skyform.ico ]; then
    mv $i_top/etc/skyformcrv/html/skyform.ico $i_top/etc/skyformcrv/html/skyform.ico.bak
fi
for dir in $i_top/$subdirname/orig/etc/skyformcrv/*; do
    basename="$(basename $dir)"
    if [ "$basename" == "bin" ] || [ "$basename" == "lib64" ]; then
#        if [ -d $i_top/etc/skyformcrv/$basename ] && [ ! -L $i_top/etc/skyformcrv/$basename ]; then
#            mv $i_top/etc/skyformcrv/$basename $i_top/etc/skyformcrv/$basename.old
#        fi
        cp $dir/* $i_top/$subdirname/$basename
        if [ ! -d $i_top/etc/skyformcrv/$basename ]; then
            ln -sf $i_local/$basename $i_top/etc/skyformcrv/$basename
        fi
    else
        if [ ! -d $i_top/etc/skyformcrv/$dir ]; then
            cp -r $dir $i_top/etc/skyformcrv/
        fi
    fi
done
if [ -f $i_top/etc/skyformcrv/html/skyform.ico.bak ]; then
    mv $i_top/etc/skyformcrv/html/skyform.ico.bak $i_top/etc/skyformcrv/html/skyform.ico
fi
certsdir=$i_top/etc/skyformcrv/certs
if [ ! -d $certsdir ]; then
    mkdir -p $certsdir
    openssl req -x509 -sha256 -days 3560 \
    -nodes -newkey rsa:2048 \
    -subj "/C=CN/ST=Beijing/L=Beijing/O=Skyformaip/OU=prod" \
    -keyout $certsdir/ca.key -out $certsdir/ca.key
    ln -s $certsdir/ca.key $certsdir/ca.crt
fi
if [ $crv_port != 0 ]; then
    sed -i s/16000/$crv_port/ $i_top/etc/skyformcrv/html/rstudio.html
    sed -i s/16000/$crv_port/ $i_top/etc/skyformcrv/html/code.html
    sed -i s/16000/$crv_port/ $i_top/etc/skyformcrv/install/crv
fi

for file in aip aip.service aip.sh aip.csh limits.sh lsf.conf; do
    cp -f $i_top/$subdirname/orig/etc/$file $i_top/etc
done

# copy key.bin
keyfile=`ls -t key.bin* 2> /dev/null | head -1`
if [ x$keyfile != 'x' ]; then
    cp $keyfile $i_top/etc
else
    echo If you do not have the key file and are the first time install AIP, you will
    echo have 45 days of demo period of AIP Enterprise features.
fi

if [ $existing == "1" ]; then
   echo "SkyForm AIP binary set is updated."
   echo "!!!WARNING!!! If you have AIP custom scripts installed in <aip>/sbin directory,"
   echo "!!!WARNING!!! Please manually copy them to the new sbin directory after"
   echo "!!!WARNING!!! running host-setup on the master"
   exit 0
fi

# change AIP admin user
sed -i s/"- cadmin"/"- $i_admin"/ $i_top/etc/cb.yaml

# change define_ncpus
if [ $ncpus_change == 1 ]; then
    sed -i s/"define_ncpus: .*"/"define_ncpus: $ncpus"/ $i_top/etc/cb.yaml
fi
if [ $eda == 1 ]; then
    sed -i /"jservice_enabled"/d $i_top/etc/jservice.yaml
    sed -i /"cbcrond_enabled"/d $i_top/etc/jservice.yaml
    echo "jservice_enabled: yes" >> $i_top/etc/jservice.yaml
    echo "cbcrond_enabled: no" >> $i_top/etc/jservice.yaml
    if ! grep -q lsf_compatible $i_top/etc/cb.yaml; then
        sed -i "6i\ \ lsf_compatible: yes" $i_top/etc/cb.yaml
    fi
    master=$(awk '{print $2}' $i_hostfile | head -1)
    sed -i s/LSF_MASTER_LIST=MASTER/LSF_MASTER_LIST=$master/ $i_top/etc/lsf.conf
fi

# change owner of work directory & configuration files
# get gid of the cadmin
#id=`id $i_admin`
#gid=`expr "$id" : '.*gid=.*(\(.*\)).*'`
chown -R $i_admin: $i_top/work
chown -R $i_admin: $i_top/etc
mkdir -p $i_top/work/proxy
chmod 777 $i_top/work/proxy

if [ $i_hostfile == "no" ]; then
    echo "Please ensure the file cb.yaml is configured correctly before setting up each host"
    exit 0
fi

if [ ! -f $i_hostfile ]; then
    echo "Host list file [$i_hostfile] not found. cb.yaml is not configured"
    exit 1
fi

cp $i_hostfile $i_top/etc/hosts
lines=`wc -l < $i_hostfile`
if [ $lines -gt 500 ]; then
    echo "WARNING: for big cluster of more than 500 hosts, please manually edit cb.yaml"
    exit 0
fi
n=37
host_exist=0
for host in `awk '{print $2}' $i_hostfile`; do
   if [ $host == 'localhost' ]; then
        continue
   fi
   host_exist=1
   line="- name: $host"
   sed -i "${n}i\ \ \ \ $line" $i_top/etc/cb.yaml
   n=$(( n+1 ))
   #sed -i "${n}i\ \ \ \ \ \ maxslots: cpu" $i_top/etc/cb.yaml
   #n=$(( n+1 ))
done

if [ $host_exist == '0' ]; then
   echo "ERROR: The host file $i_hostfile does not contain valid lines"
   echo "Installation failed!"
   rm -rf $i_top/etc
   exit 1
fi
