#!/usr/bin/env bash
# LabManager: systemd units & scripts installer v2.0
GIT_URL=https://gitlab.di.unipmn.it
GIT_BASE_DIR=ulisse/labmanager-systemd/raw
GIT_BRANCH=master

ESAME_DIR=/opt/esame

BIN_FILES=(
"desktop-wallpaper" "esamesync-esame.sh" "firefox-home" "get-config" "iptables-rules" "lightdm-autologin"
"kioskmode" "mk-homedir" "nfs" "usb" "virtualbox" "rabbitmq-client.py"
)

SYSTEMD_FILES=(
"esame-desktop-wallpaper.service" "esame-firefox-home.service" "esame-get-config-boot.service" "esame-get-config.service" "esame-iptables-rules.service"
"esame-dm-autologin.service" "esame-kioskmode.service" "esame-mk-homedir.service" "esame-nfs.service" "esame-usb.service" "esame-virtualbox.service"
"esamesync-esame.service" "esame-get-config.timer" "esame-configurator.target" "esame.target" "esamekiosk.target" "esameshow.target" "esame-multi-user.target"
"esame-rabbitmq-client.service"
)

USBGUARD_OVERRIDE_FILES=(
"usbguard.service.d/override.conf"
)

SYSCONFIG_FILES=(
"labmanager"
"esamesync-esame"
)

OLD_FILES=(
"/usr/libexec/labmanager"
"/etc/systemd/system/esame.target.wants"
"/etc/systemd/system/esamekiosk.target.wants"
"/etc/systemd/system/esameshow.target.wants"
"/etc/systemd/system/esame-configurator.target.wants"
"/etc/systemd/system/graphical.target.wants/esame-get-config.timer"
"/etc/systemd/system/esame-desktop-wallpaper.service"
"/etc/systemd/system/esame-firefox-home.service"
"/etc/systemd/system/esame-get-config-boot.service"
"/etc/systemd/system/esame-get-config.service"
"/etc/systemd/system/esame-iptables-rules.service"
"/etc/systemd/system/esame-dm-autologin.service"
"/etc/systemd/system/esame-kdm-autologin.service"
"/etc/systemd/system/esame-kioskmode.service"
"/etc/systemd/system/esame-mk-homedir.service"
"/etc/systemd/system/esame-nfs.service"
"/etc/systemd/system/esame-usb.service"
"/etc/systemd/system/esame-virtualbox.service"
"/etc/systemd/system/esamesync-esame.service"
"/etc/systemd/system/esame-get-config.timer"
"/etc/systemd/system/esame-configurator.target"
"/etc/systemd/system/esame.target"
"/etc/systemd/system/esamekiosk.target"
"/etc/systemd/system/esameshow.target"
"/etc/systemd/system/usbguard.service.d"
"/etc/systemd/system/esame-rabbitmq-client.service"
)

# DON'T TOUCH UNDER THIS LINE! #################################################

# Create a user
myuseradd() {
  if [ "z$1" == "z" ]; then
    echo "myuseradd: No user specified! Nothing to do."
    return
  fi
  R_USER="$1"
  R_UID=""
  if [ "z$2" != "z" ]; then
    R_UID="-u $2"
  fi
  R_GID="-U"
  if [ "z$3" != "z" ]; then
    # We need to create the group before creating the user
    R_GID="-g $3"
    groupadd ${R_GID} -r ${R_USER}
  fi
  useradd -b /local -m ${R_UID} ${R_GID} -r ${R_USER}
  if [ $? -ne 0 ]; then
    echo "Error creating user ${R_USER}"
  else
    echo "User ${R_USER} was created"
  fi
}

removeFiles() {
    local files=( "$@" )

    for f in "${files[@]}"
    do
        rm -rf $f
        echo "Removed file: $f"
    done
}

downloadFiles() {
    local base_url="$1"
    shift
    local files=( "$@" )

    i=1
    for f in "${files[@]}"
    do
        echo -e "\n$i/${#files[@]} - $base_url/$f"
        curl -# --fail -O "$base_url/$f"
        if [[ $? != 0 ]]
        then
            echo "curl exited with error code != 0, installation aborted."
            exit 1
        fi
        i=$(expr $i + 1)
    done
}

echo -e "\nLabManager: systemd units & scripts installer"

if [ -z "$1" ]; then
    echo -e "\nNo branch/tag specified, using branch 'master'."
    echo -e "Please call '$0 <branch/tag>' to use a different source.\n"
else
    GIT_BRANCH="$1"
    echo -e "\nUsing branch/tag '$GIT_BRANCH'.\n"
fi

# v1.0 has a different set of files and install procedure, print warning and abort installation
if [[ "$GIT_BRANCH" == "v1.0" ]]
then
    echo -e "\e[1mWARNING!\e[0m"
    echo "Branch 'v1.0' has a different installation procedure, please get"
    echo -e "the correct installation script here:\n"
    echo -e "$GIT_URL/$GIT_BASE_DIR/v1.0\n"
    exit 1
fi

GIT_BRANCH_PATH=${GIT_URL}/${GIT_BASE_DIR}/${GIT_BRANCH}

# Remove obsolete files
echo -e "\e[1mRemoving obsolete files...\e[0m"
removeFiles ${OLD_FILES[@]}
echo
echo

# Create all 'esame' users, with homes under '/local'
echo -e "\e[1mAdding users and their home directories under /local...\e[0m"

mkdir -p /local
mkdir -p ${ESAME_DIR}

#useradd -b /local -m -u 968 -U -g 968 -r    esamesync
myuseradd esamesync 451 451
myuseradd esame
myuseradd moodle
myuseradd rdesktop
chown esamesync:esamesync ${ESAME_DIR}

mkdir -p /usr/libexec/labmanager

echo
echo

# Systemd services scripts
echo -e "\e[1mDownloading systemd script files...\e[0m"
cd /usr/libexec/labmanager
echo "Creating symlink bta-no-usbpen -> /bin/sleep..."
ln -s -f /bin/sleep bta-no-usbpen
echo
downloadFiles "${GIT_BRANCH_PATH}/bin-ubuntu" ${BIN_FILES[@]}
chmod +x *
echo
echo

# default (sysconfig on RedHat)
# If the admin has created/modified the files, we will not overwrite them.
echo -e "\e[1mDownloading default files...\e[0m"
cd /etc/default
for conffile in ${SYSCONFIG_FILES[@]}; do
    if [ -e "${conffile}" ]; then
        echo "Not overwriting existing file ${conffile}, skipping it."
    else
        downloadFiles "${GIT_BRANCH_PATH}/sysconfig" "${conffile}"
   fi
done
echo
echo

# Install pika python module
pip install --user pika

# Systemd services files
echo -e "\e[1mDownloading systemd unit files...\e[0m"
cd /etc/systemd/system
downloadFiles "${GIT_BRANCH_PATH}/systemd-ubuntu" ${SYSTEMD_FILES[@]}
echo
echo

# Override USBGuard
echo -e "\e[1mOverriding USBGuard systemd service...\e[0m"
mkdir /etc/systemd/system/usbguard.service.d
cd /etc/systemd/system/usbguard.service.d
downloadFiles "${GIT_BRANCH_PATH}/systemd-ubuntu" ${USBGUARD_OVERRIDE_FILES[@]}
echo
echo

# Following links should not be needed, specifying services as "Wants" directives should suffice

# Create symlinks for target esame, esamekiosk, esameshow and esame-configurator
echo -e "\e[1mSetting up targets & services...\e[0m"
cd /etc/systemd/system
mkdir esame.target.wants
cd esame.target.wants
ln -s /usr/lib/systemd/system/accounts-daemon.service .
ln -s /usr/lib/systemd/system/rtkit-daemon.service .
ln -s /usr/lib/systemd/system/switcheroo-control.service .
ln -s /usr/lib/systemd/system/systemd-update-utmp-runlevel.service .
ln -s /usr/lib/systemd/system/udisks2.service .
ln -s /usr/lib/systemd/system/veyon.service .
ln -s /etc/systemd/system/enable-wol@.service enable-wol@eth0.service
cd ..
mkdir esamekiosk.target.wants
cd esamekiosk.target.wants
ln -s /usr/lib/systemd/system/accounts-daemon.service .
ln -s /usr/lib/systemd/system/rtkit-daemon.service .
ln -s /usr/lib/systemd/system/switcheroo-control.service .
ln -s /usr/lib/systemd/system/systemd-update-utmp-runlevel.service .
ln -s /usr/lib/systemd/system/udisks2.service .
ln -s /usr/lib/systemd/system/veyon.service .
ln -s /etc/systemd/system/enable-wol@.service enable-wol@eth0.service
cd ..
mkdir esameshow.target.wants
cd esameshow.target.wants
ln -s /usr/lib/systemd/system/accounts-daemon.service .
ln -s /usr/lib/systemd/system/rtkit-daemon.service .
ln -s /usr/lib/systemd/system/switcheroo-control.service .
ln -s /usr/lib/systemd/system/systemd-update-utmp-runlevel.service .
ln -s /usr/lib/systemd/system/udisks2.service .
ln -s /usr/lib/systemd/system/veyon.service .
ln -s /etc/systemd/system/enable-wol@.service enable-wol@eth0.service
cd ..
mkdir esame-configurator.target.wants
cd esame-configurator.target.wants
ln -s /etc/systemd/system/enable-wol@.service enable-wol@eth0.service
cd ..
echo
echo

echo -e "\e[1mReload systemd...\e[0m"
systemctl daemon-reload
echo
echo

echo -e "\e[1mEnable systemd services...\e[0m"
systemctl enable esame-*.service
systemctl enable esamesync-esame.service
# The following 2 commands are not needed anymore as get-config at boot time
# will switch and activate the timer on and off when needed
# (according to AMQP configuration)
#systemctl enable esame-get-config.timer
#systemctl start esame-get-config.timer
echo
echo

echo -e "\e[1mDisable unwanted systemd services...\e[0m"
systemctl disable esame-usb.service
echo
echo

echo -e "\e[1mChange default target to esame-configurator.target...\e[0m"
systemctl set-default esame-configurator.target
echo
echo

echo -e "\e[1mAll done!\e[0m"
