#!/bin/bash

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
}

# Checks if Docker is installed, running, and user has permission. Returns 1 on failure.
_check_docker_installed() {
    if ! command -v docker &> /dev/null; then
        echo "Docker is not installed"
        return 1
    fi

    # check if docker daemon is running
    if ! docker info &> /dev/null; then
        echo "Docker daemon is not running"
        return 1
    fi

    # check if user has permission to run docker
    if ! docker run --rm hello-world &> /dev/null; then
        echo "User does not have permission to run docker"
        return 1
    fi

    return 0
}

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"

_check_docker_installed || _die "Docker is required."

install_bb64