#!/bin/bash

# INSTALL SCRIPT
# The install script is required for all templates.
# It is used to install the service on the server.
# It is called with the path to the server specific env file as an argument.


check_prerequisites() {
    # prerequisites:
    # - bash
    # - curl
    # - wget
    # - docker

    PREREQUISITES=("bash" "curl" "wget" "jq" "docker")

    # check if all prerequisites are installed
    for prerequisite in "${PREREQUISITES[@]}"; do
        if ! command -v "${prerequisite}" &> /dev/null; then
            echo "Prerequisite: ${prerequisite} is not installed."
            exit 1
        fi
    done
}


install_bb64() {
    # install bb64 into EXECUTABLES
    _check_required_env_vars EXECUTABLES

    ARCH=$(uname -m)
    if [[ "$ARCH" == "x86_64" ]]; then
        BIN=bb64.amd64
    elif [[ "$ARCH" == "aarch64" || "$ARCH" == "arm64" ]]; then
        BIN=bb64.arm64
    else
        echo "Unsupported architecture: $ARCH" >&2
        exit 1
    fi

    # create the executables directory if it doesn't exist
    mkdir -p ${EXECUTABLES}

    # download bb64
    if ! curl -fsSL https://gitea.jde.nz/public/bb64/releases/download/latest/bb64.${ARCH} -o ${EXECUTABLES}/bb64; then
        echo "Failed to download bb64 for architecture: $ARCH" >&2
        exit 1
    fi
    chmod +x ${EXECUTABLES}/bb64
}


check_prerequisites

# install bb64
install_bb64

exit 0