#!/bin/bash

# This script is used to install the dropshell agent on a remote server.

SCRIPT_DIR=$(dirname "$0")

set -a

AGENT_PATH="$SCRIPT_DIR"

set +a


if [ -f "$SCRIPT_DIR/common.sh" ]; then
    source "$SCRIPT_DIR/common.sh"
else
    echo "Error: common.sh not found in $SCRIPT_DIR"
    exit 1
fi

_check_required_env_vars "AGENT_PATH"

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_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_PATH/bb64" -v
    if [ $? -ne 0 ]; then
        _die "bb64 did not install correctly."
    fi

    echo "bb64 installed successfully."
    return 0;
}

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

echo "Installing dropshell agent..."

install_bb64



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

echo "Running remote agent self-test..."


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

echo "Completed remote agent self-test."


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

echo "Completed dropshell agent installation."

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

exit 0