#!/bin/bash -e
if [ _$CB_ENVDIR == '_' ]; then
   echo Please ensure SkyForm AI is configured properly in the current environment
   exit 1
fi

if [ -f /var/www/html/jobs.php ]; then
   echo AIP Web portal seems installed already. Please choose another machine to
   echo install the VNC Portal. Or delete all files and directories in /var/www/html
   echo and try again.
   exit 1
fi

if ! (systemctl -a | grep -q nginx); then
   echo ERROR: Please ensure "nginx" is installed and ENABLED.
   exit 1
fi

if ! (systemctl -a | grep -q httpd) && ! (systemctl -a | grep -q apache2) ; then
   echo ERROR: Please ensure "httpd" or "apache2" is installed and ENABLED.
   exit 1
fi

if ! (systemctl -a | grep -q aiprestd); then
   echo Installing AIPRESTD...
   rest/installaiprestd
fi

certsdir=/etc/nginx/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/server.key -out $certsdir/server.crt
fi

cp -f nginx.conf /etc/nginx/nginx.conf

# Ubuntu
if [ -f /etc/lsb-release ]; then
    sed -i s/apache/www-data/ /etc/nginx/nginx.conf
    systemctl disable --now apache2
    rm /var/www/html/*.html
    systemctl enable nginx
    systemctl restart nginx
    cp /bin/bash /bin/sh
else
    systemctl disable --now httpd
    systemctl enable nginx
    systemctl restart nginx
fi

tar xfz aip-vncportal.tar.gz -C /var/www/html

sed -i s/"^#pp:"/"pp:"/ $CB_ENVDIR/vncsub.yaml
