#!/bin/bash

set -e

VERSION=""
if [ -n "$RV_VERSION" ]; then
    VERSION="$RV_VERSION"
fi

PROD_REPO_ADDRESS=https://repo.iz-cloud.com
if [ -z "$REPO_ADDRESS" ]; then
    REPO_ADDRESS="$PROD_REPO_ADDRESS"
fi

#################################################
# for logging to file

exec 3>&1 4>&2
trap 'exec 2>&4 1>&3' 0 1 2 3
exec 1> >(tee -a "/home/izuser/install-${VERSION}.log") 2>&1

log() {
    echo `date --rfc-3339=ns`" | $1"
}

catch() {
    log "Error $1 occurred on line: $2"
    exit 1
}

trap 'catch $? $LINENO' ERR

################################################


get_jetpack_version() {
    echo $(apt-cache show nvidia-jetpack 2>/dev/null | grep -E "Version:" | awk '{print $2}' | cut -d'-' -f1)  
}

get_dependencies() {
    # $1: package name
    # $2: filter
    echo $(apt-cache show $1 | grep -E "Depends|Recommends|Suggests|Pre\-Depends" | tr ":" "\n" | tr "," "\n" | grep -Ev "Depends|Recommends|Suggests|Pre\-Depends" | sed 's/^ *//' | sort -u | grep -E $2 | sed -z "s/ (>= [^)]*)//g; s/ (= /=/g; s/)//g")
}

get_dependencies_recursive() {
    # $1: package name
    # $2: filter
    local DEPS="$(get_dependencies "$1" "$2")"
    local DEEPER=""
    if [ -n "$DEPS" ]; then
        local DEEPER="$(for deb in $DEPS ; do get_dependencies_recursive "$deb" "$2"; done | sed 's/[[:space:]]*$//')"
    fi
    echo "$DEPS $DEEPER"
}

check_package_version_in_repos() {
    local package_name="$1"
    local version="$2"
    # log "Checking if $package_name version $version exists in the repositories"
    # Use apt-cache madison to list versions and check if the specified version exists in the version column
    apt-cache madison "$package_name" | awk '{print $3}' | grep -q "^${version}$"
}


PKG_NAMES="roadview rv-web rv-core activation hostcontrol-rv1 dgpu-adam private-info-protector rv-common rv-runtime plate-catalog rv1-models"
PKG_FILTER=$(echo $PKG_NAMES | sed 's/ /|/g')

main() {

    # Step 1: work out if we can run privileged commands, and if so,
	# how.
    CAN_ROOT=
	SUDO=
	if [ "$(id -u)" = 0 ]; then
		CAN_ROOT=1
		SUDO=""
	elif type sudo >/dev/null; then
		CAN_ROOT=1
		SUDO="sudo"
	elif type doas >/dev/null; then
		CAN_ROOT=1
		SUDO="doas"
	fi
	if [ "$CAN_ROOT" != "1" ]; then
		log "This installer needs to run commands as root."
		log "We tried looking for 'sudo' and 'doas', but couldn't find them."
		log "Either re-run this script as root, or set up sudo/doas."
		exit 1
	fi

    # Check for wget or curl and define download command
    DOWNLOAD_CMD=""
    if command -v wget >/dev/null 2>&1; then
        DOWNLOAD_CMD="wget -q --tries=3 --timeout=10 -O"
    elif command -v curl >/dev/null 2>&1; then
        DOWNLOAD_CMD="curl -s --retry 3 --max-time 10 -o"
    else
        log "Error: Neither wget nor curl is installed. Please install one of these utilities."
        exit 1
    fi

    log "Setting up sources"
    $DOWNLOAD_CMD - $REPO_ADDRESS/installer/setup_repo.sh | REPO_ADDRESS=${REPO_ADDRESS} bash

    pkg_version=""
    DEPENDENCIES=""

    if [ -n "$VERSION" ]; then
        pkg_version="=$VERSION"
    else
        pkg_version="=$(apt-cache madison roadview | head -1 | awk '{$1=$1};1' | cut -d' ' -f 3)"
    fi

    log "Checking version $pkg_version"

    if ! check_package_version_in_repos "roadview" "${pkg_version#=}"; then
        log "Error: Version $pkg_version of package roadview does not exist in the repositories."
        exit 1
    fi

    PKG_LIST="roadview${pkg_version%=}"

    log "Installing $PKG_LIST"

    log "Simulate install"

    if ! $SUDO apt-get install -y --simulate --allow-downgrades $PKG_LIST; then
        log "Some dependencies prevent to install: $PKG_LIST"
        log "WARNING: DEPENDENCIES WILL BE INSTALLED SEPARATELY"
        log "Calculating dependencies"
        DEPENDENCIES=$(echo "$(get_dependencies_recursive $PKG_LIST $PKG_FILTER)" | tr " " "\n" | sort -u | tr "\n" " ")

        PKG_LIST="$PKG_LIST $DEPENDENCIES"
    fi

    log "Package list: $PKG_LIST"

    set +x
    (
        $SUDO apt-get install -y --allow-downgrades --allow-remove-essential libcurl3-gnutls $PKG_LIST
    )

    # check MAX perfomance is setup
    mode=0
    current_mode="$($SUDO nvpmodel -q | tail -n 1 | tr -d '\r\n')" || {
        log "Error: failed to execute nvpmodel -q" >&2
        exit 1
    }

    if [[ -z "$current_mode" ]]; then
        log "Error: empty result from nvpmodel -q" >&2
        exit 1
    fi

    # Finish up
    log "Installation completed"

    # set MAX perfomance
    if [[ "$current_mode" != "$mode" ]]; then
        log "change power mode"
        # wait 10 seconds for the hostcontrol service to configure the DPU
        nohup bash -c "sleep 10; echo YES | sudo nvpmodel -m '$mode'" >/dev/null 2>&1 &
        log "ATTENTION!!! The device will be rebooted"
    fi
}

main
