#!/bin/bash

# install the dropshell host agent on this computer.
# (not for remote servers)

SCRIPT_DIR=$(dirname "$0")

echo "Installing dropshell host agent on this computer..."


# Prints an error message in red and exits with status code 1.
_die() {
    echo -e "Error: $1"
    exit 1
}


# Checks if listed environment variables are set; calls _die() if any are missing.
_check_required_env_vars() {
    local required_vars=("$@")
    for var in "${required_vars[@]}"; do
        if [ -z "${!var}" ]; then
            _die "Required environment variable $var is not set"
        fi
    done
}


function install_bb64() {    
    # check curl installed
    if ! command -v curl &> /dev/null; then
        _die "Curl is not installed. Curl is required for agent installation."
    fi

    curl -fsSL "https://gitea.jde.nz/public/bb64/releases/download/latest/install.sh" | bash -s -- "$AGENT_LOCAL_PATH" "$(id -u $USER):$(id -g $USER)"

    # test result code from curl
    if [ $? -ne 0 ]; then
        _die "Failed to install bb64. Curl returned non-zero exit code."
    fi

    # test if bb64 is installed
    "$AGENT_LOCAL_PATH/bb64" -v
    if [ $? -ne 0 ]; then
        _die "bb64 did not install correctly."
    fi

    echo "bb64 installed successfully."
    return 0;
}


#-------------------------------------------------------------------------

set -a
AGENT_LOCAL_PATH="$SCRIPT_DIR"
set +a

_check_required_env_vars "AGENT_LOCAL_PATH"
echo "Installing host agent into $AGENT_LOCAL_PATH"

install_bb64