#!/bin/sh

set -x

USER_NAME="exo_admin"
USER_GROUP="exo_group"
USER_HOME=/home/${USER_NAME}
INSTALL_PATH=${USER_HOME}/ExoPrep/api
SRC_PATH="$(dirname ${0})"
printf "Installer source path: ${SRC_PATH}\n"


# Common installation (the app, user/group, etc.)
#

printf "Installing program and setting up dedicated user/group...\n"

# setup user/group (so not to run as root)
userExist=$(id -u ${USER_NAME})
groupExist=$(id -g ${USER_NAME})

reqGroups="tty,input,disk,dialout,plugdev,storage,optical,audio,video,${USER_GROUP}"

if [ -z "${userExist}" -o -z "${groupExist}" ]; then
    groupadd ${USER_GROUP}
    useradd -m ${USER_NAME}
    usermod -aG "${reqGroups}" ${USER_NAME}

    mkdir -p ${INSTALL_PATH} ${USER_HOME}/ExoPrep/logs
fi

if [ ! -e "${INSTALL_PATH}" ]; then
    printf " !!! ERROR !!! Install path: ${INSTALL_PATH} not found, aborting!\n"
    exit 1
fi

chown -R ${USER_NAME}:${USER_GROUP} ${USER_HOME}/ExoPrep/
chown -R ${USER_NAME}:${USER_GROUP} ${INSTALL_PATH}

# copy/set perm
cp ${SRC_PATH}/ExoPrepAPI ${INSTALL_PATH}

chown -R ${USER_NAME}:${USER_GROUP} ${INSTALL_PATH}


# Distro specific installations (mainly service/daemon install)
#

DISTR_ID=$(lsb_release -a | grep "Distr")

# RUNIT
RUNIT_SV_PATH=/etc/sv/exoprepapi

# Systemd
# TODO

case "${DISTR_ID}" in

    *Void*)
        printf "Installing service...\n"

        mkdir -p /etc/sv/exoprepapi
        cat > ${RUNIT_SV_PATH}/run <<EOF
#!/bin/sh
exec 2>&1
chpst -u ${USER_NAME} env HOME=${USER_HOME} ${INSTALL_PATH}/ExoPrepAPI
EOF

        chmod +x ${RUNIT_SV_PATH}/run
        ln -sf ${RUNIT_SV_PATH} /var/service/

        sv up exoprepapi && sleep 1 && sv status exoprepapi
        ;;

    *Debian*)
        printf "coming soon...\n"
        ;;
esac


