#!/bin/bash
if !(echo $LSF_ENVDIR | grep -q lsf); then
    echo LSF environment is not detected.
    echo Please make sure the env variable LSF_ENVDIR
    echo contains the word '"lsf"', e.g. /share/lsf/conf.
    exit 1
fi

if [ -f /etc/redhat-release ]; then
    osver=`tr -dc '0-9.' </etc/redhat-release  | cut -d. -f1`
    allp=`rpm -qa`
    error=0
    packages='python3 openbox mesa-libGLU'
    if [ $osver == '9' ]; then
        packages="dbus-x11 "$packages
        echo "******* On Rocky Linux 9, recommend to install XFCE4 desktop"
    fi
    for p in $packages; do
        echo $allp | grep -q -w $p
        if [ $? != 0 ]; then
            echo "Error: the software package $p is required but not installed."
            error=1
        fi
    done
    if [ $error == 1 ]; then
        exit 1
    fi
fi

crvtop=/opt/skyformaip-tools/skyformcrv

if [ -f /usr/libexec/gnome-initial-setup ]; then
    mv /usr/libexec/gnome-initial-setup /usr/libexec/gnome-initial-setup.bak
fi

gsettings set org.gnome.desktop.screensaver lock-enabled false
gsettings set org.gnome.desktop.session idle-delay 0

sed -i 's|/opt/skyformai/etc|/opt/skyformaip-tools|g' $crvtop/install/crv.service
sed -i '7s|.*|CB_ENVDIR=/opt/skyformaip-tools|' $crvtop/install/crv

cp $crvtop/install/crv.service /lib/systemd/system
setenforce 0
sed -i s/SELINUX=enforcing/SELINUX=permissive/ /etc/selinux/config

certsdir=$crvtop/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

setenforce 0
sed -i s/SELINUX=enforcing/SELINUX=disabled/ /etc/selinux/config

systemctl enable crv
systemctl restart crv

if [ ! -f /etc/xdg/openbox/menu.xml.orig ]; then
    mv /etc/xdg/openbox/menu.xml /etc/xdg/openbox/menu.xml.orig
fi
cp $crvtop/openbox/menu-eda.xml /etc/xdg/openbox/menu.xml

echo SkyForm CRV installation is done. Please run
echo ./disable_gnome_lock_screen_all.sh
echo to disable desktop screen lock.
