#!/bin/bash
usage() {
        echo "Usage: $0 --shared=shared_dir --upgrade"
        exit 1
}

i_share=`dirname $0`
if [ -f $i_share/aip-portal.run ]; then
  i_share=/opt/skyformai_shared
fi
upgrade=0

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

  case $1 in
  --shared=*)
        i_share=$optarg
        ;;
  --upgrade)
        upgrade=1 ;;
  --help)
        usage ;;
  *)
        echo "ERROR: Invalid option"
        usage ;;
  esac
  shift
done

if [ -f /etc/redhat-release ]; then
    osver=`tr -dc '0-9.' </etc/redhat-release  | cut -d. -f1`
    allp=`rpm -qa`
    error=0
    if [ $osver == '8' ]; then
        packages='python39 openbox mesa-libGLU'
    else
        packages='python3 openbox mesa-libGLU'
    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

i_top=`grep AIP_TOP= $i_share/etc/aip | cut -d= -f2`

crvtop=$i_top/etc/skyformcrv

if [ $upgrade == 0 ]; then
    ## set up openbox ##
    cp $crvtop/openbox/menu.xml /etc/xdg/openbox
    # sed -i s/'<titleLayout>NLIMC'/'<titleLayout>NLMC'/ /etc/xdg/openbox/rc.xml
    if [ -f /usr/libexec/gnome-initial-setup ]; then
        mv /usr/libexec/gnome-initial-setup /usr/libexec/gnome-initial-setup.bak
    fi
    cat << EOF > /etc/dconf/db/local.d/00-screensaver
[org/gnome/desktop/session]
idle-delay=uint32 0

[org/gnome/desktop/screensaver]
lock-enabled=false
EOF
    dconf update
fi

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

# install VGL ###
if [ -f /usr/bin/vglrun ]; then
   exit 0
fi
if [ -f /etc/lsb-release ]; then
    if ! dpkg -l xfce4 >/dev/null 2>&1; then
        echo "Error!!! The package xfce4 needs to be installed."
        exit 1
    fi
    cp $crvtop/lib64/*.so /lib/$(uname -i)-linux-gnu/
else
    cp $crvtop/lib64/*.so /lib64
fi
cp $crvtop/bin/vgl* /usr/bin

if [ $upgrade == '1' ]; then
    exit 0
fi 
a=`which nvidia-smi 2>&1`
if [ $? == 0 ]; then
    init 3
    rmmod nvidia_drm nvidia_modeset nvidia_uvm nvidia
    vglserver_config +glx +s +f +t
    init 5
    exit 0
    ## enable vglrun in vncsub.yaml
    if [ -z $CB_ENVDIR ]; then
        source /etc/profile.d/aip.sh
    fi
    if [ ! -f /etc/lsb-release ]; then
        if ! grep -q ^vglrun $CB_ENVDIR/vncsub.yaml; then
            echo "vglrun: y" >> $CB_ENVDIR/vncsub.yaml
        fi
    fi
fi
