#! /bin/sh

################################################################################
# Copyright (C) 2015-2026 NICE s.r.l.
# All Rights Reserved
#
# This software is the confidential and proprietary information
# of NICE s.r.l. ("Confidential Information").
# You shall not disclose such Confidential Information
# and shall use it only in accordance with the terms of
# the license agreement you entered into with NICE.
################################################################################

die () {
    _exit_code=${1:-0}

    if [ -z "${DCV_INSTALLER_LOG_FILE}" ]; then
        echo "Please find more information about the driver installation in '${LOG_FILE}'"
    fi

    exit ${_exit_code}
}

log() {
    echo "$1" >> "${LOG_FILE}"
}

if [ -z "${DCV_ROOT}" ]; then
    export DCV_ROOT="/usr/share/dcv"
fi

if [ -n "${DCV_INSTALLER_LOG_FILE}" ]; then
    LOG_FILE="${DCV_INSTALLER_LOG_FILE}"
else
    LOG_FILE="/var/log/dcv/usb-driver-update.log"
    echo "" 2>/dev/null > "${LOG_FILE}"
    if [ $? -ne 0 ]; then
        LOG_FILE=$(mktemp dcv-usb-driver-update-XXXXXX.log)
    fi
fi

_user_id=$(id -u)
if [ "${_user_id}" != "0" ] ; then
    log "Error: You need to be 'root' to install the Amazon DCV USB driver module."
    echo "Error: You need to be 'root' to install the Amazon DCV USB driver module."
    die 1
fi

cd "${DCV_ROOT}/eveusb" > /dev/null

log "Setting USB module prerequisites... "
printf "Setting USB module prerequisites... "
export LOG_FILE=${LOG_FILE}
./dcvusbdriverinstallprerequisites
if [ "$?" != "0" ]; then
    echo "Failed"
    die 1
fi
echo "Done"

log "Building USB module... "
printf "Building USB module... "

make 2>> "${LOG_FILE}" >> "${LOG_FILE}"
if [ "$?" != "0" ]; then
    log "USB module build failed"
    echo "Failed"
    die 1
fi
log "USB module has been successfully built."
echo "Done"

log "Installing USB module... "
printf "Installing USB module... "
make install 2>> "${LOG_FILE}" >> "${LOG_FILE}"
if [ "$?" != "0" ]; then
    log "USB module installation failed"
    echo "Failed"
    die 1
fi
log "USB module has been successfully installed."
echo "Done"

log "Updating module dependencies... "
printf "Updating module dependencies... "
depmod -a
if [ "$?" != "0" ]; then
    log "Module dependencies update failed"
    echo "Failed"
    die 1
fi
echo "Done"
echo "Restart dcvserver service to load the USB module. A machine reboot could be needed to complete the installation."

die

# ex:ts=4:et:
