#!/bin/bash
# #/**
#         launchOgagentInstaller ndisk npart [windowsadmin]
#@brief   Scheduling OpenGnsys Agent installation at next boot or administrator session.
#@param   integer ndsik         disk number
#@param   integer npart         partition number
#@param   string  windowsadmin  administrator user (only for Windows)
#@author  Ramón M. Gómez, ETSII Univ. Sevilla
#@version 1.1.0 - Initial version.
#@date    2018-02-16
#*/ ##

# Global variables.
PROG="$(basename "$0")"
if which curl &>/dev/null; then
    DOWNLOAD="curl -k -f --connect-timeout 1 -o"
else
    DOWNLOAD="wget --no-check-certificate -T 1 -O"
fi

# Show help.
if [ "$*" == "help" ]; then
    echo "$PROG: scheduling OpenGnsys Agent installation."
    echo "Format: $PROG ndisk npart [windowsadmin]"
    exit 0
fi
# Error control.
if ! typeset -Fp ogRaiseError &>/dev/null; then
    echo "$PROG: it can only be executed by an ogLive client." >&2
    exit 1
fi
[ $# == 2 -o $# == 3 ] || ogRaiseError $OG_ERR_FORMAT "$PROG ndisk npart [adminuser]" || exit $OG_ERR_FORMAT
MNTDIR=$(ogMount "$1" "$2") || exit $?
OGVERSION=$($DOWNLOAD - https://$(ogGetServerIp)/opengnsys/rest/info 2>/dev/null | jq -r .version)
[ -n "$OGVERSION" ] || ogRaiseError $OG_ERR_NOTFOUND "GET /rest/info" || exit $OG_ERR_NOTFOUND

case "$(ogGetOsType $1 $2)" in
    Windows)  # OGAgent for Windows.
        HIVE="$(ogGetHivePath "$MNTDIR" "$3")"
        [ -n "$HIVE" ] || ogRaiseError $OG_ERR_NOTFOUND "$1 $2 $3/NTUSER.DAT" || exit $OG_ERR_NOTFOUND
        # Downloading OGAgent installer for Windows.
        OGAGENTFILE="OGAgentSetup-${OGVERSION/pre/}.exe"
        TMPDIR="$(ogGetPath "$MNTDIR/Windows/Temp")"
        if ogListSoftware $1 $2 | grep -qi "opengnsys agent"; then
            echo "OGAgent for Windows is already installed, you need to uninstall it before re-install."
        else
            if eval $DOWNLOAD "$TMPDIR/$OGAGENTFILE" "https://$(ogGetServerIp)/opengnsys/descargas/$OGAGENTFILE" 2>/dev/null; then
                # Run once OGAgent Installer.
                if hivexsh -w << EOT 2>/dev/null; then
load $HIVE
cd \\Software\\Microsoft\\Windows\\CurrentVersion\\RunOnce
setval 1
Install OGAgent
string:C:\\Windows\\Temp\\$OGAGENTFILE"
commit
close
exit
EOT
                    echo "Scheduled OGAgent installation after \"$3\" logon"
                    echo "  (edit config file after finish)."
                else
                    ogRaiseError $OG_ERR_NOTWRITE "$1 $2 .../$3/NTUSER.DAT"
                    exit $OG_ERR_NOTWRITE
                fi 
            else
                ogRaiseError $OG_ERR_NOTFOUND "$1 $2 /Windows/Temp/$OGAGENTFILE"
                exit $OG_ERR_NOTFOUND
            fi
        fi
        ;;
    Linux)    # OGAgent for Linux (only deb and redhat-based backages; TODO suse-based package).
        if ogListSoftware $1 $2 | grep -qi "ogagent"; then
            echo "OGAgent for Linux is already installed, you need to uninstall it before re-install."
        else
            SYSTEMDDIR="$MNTDIR/lib/systemd"
            [ -d "$SYSTEMDDIR" -a -d "${SYSTEMDDIR/lib/etc}" ] || ogRaiseError $OG_ERR_NOTFOUND "$1 $2 systemd" || exit $OG_ERR_NOTFOUND
            # Downloading OGAgent installer for Linux.
            if [ -e $MNTDIR/etc/debian_version ]; then    # Debian-based
                OGAGENTFILE="ogagent_${OGVERSION/pre/}_all.deb"
                CODE="if ! dpkg -l ogagent &>/dev/null && [ -f /var/tmp/$OGAGENTFILE ]; then apt-get update; apt-get install -y /var/tmp/$OGAGENTFILE; fi"
            fi
            if [ -e $MNTDIR/etc/redhat-release ]; then    # RedHat-based
                OGAGENTFILE="ogagent-${OGVERSION/pre/}-1.noarch.rpm"
                CODE="if ! rpm -q ogagent &>/dev/null && [ -f /var/tmp/$OGAGENTFILE ]; then yum install -y /var/tmp/$OGAGENTFILE; fi"
            fi
            [ -n "$OGAGENTFILE" ] || ogRaiseError $OG_ERR_NOTFOUND "$1 $2 ogagent" || exit $OG_ERR_NOTFOUND
            TMPDIR="$MNTDIR/var/tmp"
            if eval $DOWNLOAD "$TMPDIR/$OGAGENTFILE" "https://$(ogGetServerIp)/opengnsys/descargas/$OGAGENTFILE" 2>/dev/null; then
                # Creating systemd script.
                cat << EOT > $SYSTEMDDIR/systemd-launchogagent
#!/bin/bash
[ $EUID = 0 ] || exit 4
start() {
    $CODE
    sed -i "0,/remote=/ s,remote=.*,remote=https://$(ogGetServerIp)/opengnsys/rest/," /usr/share/OGAgent/cfg/ogagent.cfg
    service ogagent start
}
restart() {
    service ogagent stop
    if [ -f /var/tmp/$OGAGENTFILE ]; then
        apt-get update
        apt-get install -y --reinstall /var/tmp/$OGAGENTFILE
    fi
    sed -i "0,/remote=/ s,remote=.*,remote=https://$(ogGetServerIp)/opengnsys/rest/," /usr/share/OGAgent/cfg/ogagent.cfg
    service ogagent start
}

case "\$1" in
    start|restart)  "\$1" ;;
esac
EOT
                chmod +x $SYSTEMDDIR/systemd-launchogagent
                # Creating systemd service.
                cat << EOT > $SYSTEMDDIR/system/launchogagent.service
[Unit]
Description=Installing and configuring OGAgent

[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/lib/systemd/systemd-launchogagent start
TimeoutStartSec=5min

[Install]
WantedBy=multi-user.target
EOT
                ln -fs /lib/systemd/system/launchogagent.service \
                       ${SYSTEMDDIR/lib/etc}/system/multi-user.target.wants
                echo "Scheduled OGAgent installation at next boot"
                echo "  (process will be executed in the background, do not shutdown until finish)."
            else
                ogRaiseError $OG_ERR_NOTFOUND "$1 $2 /var/tmp/$OGAGENTFILE"
                exit $OG_ERR_NOTFOUND
            fi
        fi
        ;;
    MacOS)    # OGAgent for macOS (TODO).
        echo "OGAgent installer for macOS is not implemented yet."
        ;;
    *)        # OS not detected or OGAgent not implemented.
        ogRaiseError $OG_ERR_NOTOS "$1 $2"
        exit $OG_ERR_NOTOS
        ;;
esac

