#!/bin/sh

set -e

. /usr/share/debconf/confmodule

MY_NAME="unknown"
MY_SWBUILD_VERSION="unknown"
MY_COMMIT_ID="unknown"

# Get name, version, and commit from release file
if [ -f /etc/dgx-release ]; then
    . /etc/dgx-release
    MY_NAME="DGX OS"
    MY_SWBUILD_VERSION="${DGX_SWBUILD_VERSION}"
    MY_COMMIT_ID="${DGX_COMMIT_ID}"
elif [ -f /etc/dcs-release ]; then
    . /etc/dcs-release
    MY_NAME="DCS OS"
    MY_SWBUILD_VERSION="${DCS_SWBUILD_VERSION}"
    MY_COMMIT_ID="${DCS_COMMIT_ID}"
elif [ -f /etc/egx-release ]; then
    . /etc/egx-release
    MY_NAME="EGX OS"
    MY_SWBUILD_VERSION="${EGX_SWBUILD_VERSION}"
    MY_COMMIT_ID="${EGX_COMMIT_ID}"
fi

# Dynamically add a required leading space character from enterprise_eula.txt for debconf
LICENSE="$(cat /usr/share/nvidia/enterprise_eula.txt | sed 's/^/ /')"

# Create the template file
cat > /tmp/nvidia.template << EOF
Template: nvidia/title
Type: text
Description: NVIDIA EULA confirmation

Template: nvidia/present-eula
Type: note
Description: [$MY_SWBUILD_VERSION]
$LICENSE

Template: nvidia/accepted-eula
Type: boolean
Default: false
Description: Do you accept the EULA license terms?
 In order to install $MY_NAME,
 you must accept the license terms, the
 "NVIDIA EULA". Not accepting will cancel the
 installation.

Template: nvidia/error-eula
Type: error
Description: Declined "NVIDIA EULA"
 If you do not agree to the "NVIDIA EULA" license
 terms you cannot install this image.
 .
 The installation of this image will be canceled.
EOF

# Load your template
db_x_loadtemplatefile /tmp/nvidia.template nvidia

# Set title for your custom dialog box
db_settitle nvidia/title

# facilitate backup capability per debconf-devel(7)
STATE=1
while true; do
    case "$STATE" in
    0)  # ensure going back from license presentment is harmless
        STATE=1
        continue
        ;;
    1)  # present license
        db_fset nvidia/present-eula seen false
        if ! db_input critical nvidia/present-eula ; then
            exit 0
        fi
        db_fset nvidia/accepted-eula seen false
        if ! db_input critical nvidia/accepted-eula ; then
            exit 0
        fi
        ;;
    2)  # determine users' choice
        db_get nvidia/accepted-eula
        if [ "$RET" = "true" ]; then
            exit 0
        fi
        # error on decline license (give user chance to back up)
        db_input critical nvidia/error-eula
        ;;
    3)  # user has confirmed declining license
        echo "user did not accept the eula license" >&2
        shutdown -r now
        ;;
    *)  # unknown state
        echo "eula license state unknown: $STATE" >&2
        exit 2
        ;;
    esac
    if db_go; then
        STATE=$(($STATE + 1))
    else
        STATE=$(($STATE - 1))
    fi
done

