DOWNOLOAD_BASE="https://builds.3dprinteros.com/cl/"
ZIP_NAME="clisma_armv6.zip"
DOWNOLOAD_URL=${DOWNOLOAD_BASE}${ZIP_NAME}
BINARY="cl"
SERVICE="clisma"
SERVICE_FILENAME="clisma.service"
INSTALL_DIR="/opt/3dprinteros/clisma"
SERVICE_FILE_PATH=${INSTALL_DIR}/${SERVICE_FILENAME}

set -e

# check if root
if [ "$(id -u)" -ne 0 ]; then
  SUDO=sudo
else
  SUDO=''
fi

install_cl() {
    echo "Installing 3DPrinterOS remote support terminal"
    echo Downloading... $DOWNOLOAD_URL
    curl -OL $DOWNOLOAD_URL 
    echo "Checking/Creating opt dir:" $INSTALL_DIR
    $SUDO mkdir -p $INSTALL_DIR || true
    echo Unpacking $ZIP_NAME to $INSTALL_DIR
    $SUDO python3 -m zipfile -e $ZIP_NAME $INSTALL_DIR
    echo Cleaning download zip
    rm $ZIP_NAME
    echo Setting execution rights
    $SUDO chmod +x ${INSTALL_DIR}/${BINARY}
    echo Linking the service
    $SUDO systemctl link "${SERVICE_FILE_PATH}"
    echo Enabling the service
    $SUDO systemctl enable $SERVICE
    echo Starting cl
    $SUDO systemctl start $SERVICE
}

install_cl && echo "Success!" && echo "Installation complete"
