#!/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.


attempt_install_prerequisite() {
    local prerequisite="${1}"
    echo "Attempting to install prerequisite: ${prerequisite}"

    # test if root, and test sudo otherwise.
    SUDO_CMD=""
    if [ "$EUID" -ne 0 ]; then
        if ! sudo -v; then
            echo "--------------------------------"
            echo "Prerequisite: ${prerequisite} is not installed."
            echo "Please run the script with sudo privileges or as root to automatically install the prerequisite."
            echo "--------------------------------"
            exit 1
        fi
        SUDO_CMD="sudo "
    fi


    # separate install for each prerequisite
    case "${prerequisite}" in
        "bash")
            $SUDO_CMD apt-get install -y bash
            ;;
        "curl")
            $SUDO_CMD apt-get install -y curl
            ;;
        "wget")
            $SUDO_CMD apt-get install -y wget
            ;;
        "docker")
            # install docker using the official script.
            curl -fsSL https://get.docker.com -o get-docker.sh
            $SUDO_CMD sh get-docker.sh
            rm get-docker.sh
            ;;
        *)
            echo "--------------------------------"
            echo "Prerequisite: ${prerequisite} is not installed."
            echo "Please install it manually and try again."
            echo "--------------------------------"
            exit 1
    }
install_prerequisites() {]
    # this script works on debian, ubuntu and Raspberry Pi OS
    # it checks the following prerequisites, and installs them if missing. 
    # if the user is root it proceeds, otherwise it checks for sudo privileges.
    # if neither exists, and a prerequisite is missing, the script exits with failure.

    # prerequisites:
    # - bash
    # - curl
    # - wget
    # - docker

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

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

install_prerequisites
exit 0