#!/bin/bash

export PATH="${PATH}:/bin:/sbin:/usr/bin:/usr/sbin"

readonly AEMBIT_GROUP_NAME="aembit"
readonly AEMBIT_AGENT_CONTROLLER_USER_NAME="aembit_agent_controller"
INSTALLER_DIR="$(dirname ${0})"
readonly LOG_FILE="${INSTALLER_DIR}"/installer.log
readonly AEMBIT_AGENT_CONTROLLER_BIN="aembit_agent_controller"

check_for_required_env_var() {
    env_var_name=$1
    env_var_value="${!env_var_name}"

    if [ -z "${env_var_value}" ]; then
        echo "Required environment variable \"${env_var_name}\" is not defined."
        exit 1
    fi
}

check_registration_method() {
  if [[ -z "${AEMBIT_DEVICE_CODE}" && -z "${AEMBIT_AGENT_CONTROLLER_ID}" ]]; then
        echo "Either environment variable \"AEMBIT_DEVICE_CODE\" or \"AEMBIT_AGENT_CONTROLLER_ID\" is required to be present for registration."
        exit 1
    fi
}

set_default_stack_domain() {
    if [ -z "${StackDomain}" ]; then
        export StackDomain="useast2.aembit.io"
    fi
}

check_if_package_missing() {
    package=$1

    if ! which "${package}" > /dev/null 2>&1; then
        if [ -z "${missing_packages}" ]; then
            missing_packages="${package}"
        else
            missing_packages="${missing_packages}, ${package}"
        fi
    fi
}

check_required_dependencies() {
    echo "Checking for required package dependencies."

    check_if_package_missing ps
    check_if_package_missing grep
    check_if_package_missing id
    check_if_package_missing getent
    check_if_package_missing useradd
    check_if_package_missing groupadd

    if [ -n "${missing_packages}" ]; then
        echo "One or more necessary packages were missing. Please install the following package(s) and then rerun the installer: ${missing_packages}"
        exit 1
    fi
}

check_for_existing_installation() {
    # TODO - upgrade behavior should be opt-in.
    if ps axco command | grep --quiet "${AEMBIT_AGENT_CONTROLLER_BIN}"; then
        echo "An existing Aembit installation was found. Please uninstall."
        exit 1
    fi

    if [ -d "/opt/aembit/edge/aembit_agent_controller" ] && [ $(ls -1 /opt/aembit/edge/aembit_agent_controller | wc -l) -ne 0 ]; then
        echo "An existing Aembit installation was found. Please uninstall."
        exit 1
    fi

}

create_user_and_group() {
    if getent group "${AEMBIT_GROUP_NAME}" > /dev/null 2>&1; then
        echo "Group \"${AEMBIT_GROUP_NAME}\" exists"
    else
        echo "Group \"${AEMBIT_GROUP_NAME}\" does not exist. Creating."
        if groupadd "${AEMBIT_GROUP_NAME}"; then
            echo "Group created"
        else
            echo "Error creating the \"${AEMBIT_GROUP_NAME}\" user."
            exit 1
        fi
    fi

    if getent passwd "${AEMBIT_AGENT_CONTROLLER_USER_NAME}" > /dev/null 2>&1; then
        echo "User \"${AEMBIT_AGENT_CONTROLLER_USER_NAME}\" exists"
    else
        echo "User \"${AEMBIT_AGENT_CONTROLLER_USER_NAME}\" does not exist. Creating."
        if useradd --no-create-home --shell /bin/false  -g "${AEMBIT_GROUP_NAME}" "${AEMBIT_AGENT_CONTROLLER_USER_NAME}"; then
            echo "User created"
        else
            echo "There was an error creating the \"${AEMBIT_AGENT_CONTROLLER_USER_NAME}\" user."
            exit 1
        fi
    fi
}

set_up_logs() {
    if ! cp installer_components/journald@aembit_agent_controller.conf /etc/systemd/journald@aembit_agent_controller.conf; then
        echo "Unable to copy the journald configuration file to host."
        exit 1
    fi
}

copy_static_components_to_host() {
    if ! mkdir --parents /opt/aembit/edge/agent_controller/1.9.633/bin/; then
        echo "Unable to make installation directory for Agent Controller binary."
        exit 1
    fi

    if ! cp $AEMBIT_AGENT_CONTROLLER_BIN /opt/aembit/edge/agent_controller/1.9.633/bin/$AEMBIT_AGENT_CONTROLLER_BIN; then
        echo "Unable to move the Agent Controller binary to the installation directory."
        exit 1
    fi

    if ! cp appsettings.json /opt/aembit/edge/agent_controller/1.9.633/bin/appsettings.json; then
        echo "Unable to move the Agent Controller configuration to the installation directory."
        exit 1
    fi


    if ! mkdir --parents /opt/aembit/edge/agent_controller/1.9.633/scripts/; then
        echo "Unable to make installation directory for Agent Controller scripts."
        exit 1
    fi

    if ! cp uninstall /opt/aembit/edge/agent_controller/1.9.633/scripts/uninstall; then
        echo "Unable to move the Agent Controller uninstall script to the installation directory."
        exit 1
    fi
}

install_systemd_service() {
    if ! cp installer_components/aembit_agent_controller.service /etc/systemd/system/aembit_agent_controller.service; then
        echo "Unable to copy the systemd service file to the destination."
        exit 1
    fi

    if ! sed --in-place "s#{{ AEMBIT_TENANT_ID }}#${AEMBIT_TENANT_ID}#" /etc/systemd/system/aembit_agent_controller.service; then
        echo "Unable to update the Agent Controller Tenant Id in the systemd service file."
        exit 1
    fi

    if ! sed --in-place "s#{{ StackDomain }}#${StackDomain}#" /etc/systemd/system/aembit_agent_controller.service; then
        echo "Unable to update the Agent Controller Stack Domain in the systemd service file."
        exit 1
    fi

    if ! sed --in-place "s#{{ AEMBIT_DEVICE_CODE }}#${AEMBIT_DEVICE_CODE}#" /etc/systemd/system/aembit_agent_controller.service; then
        echo "Unable to update the Agent Controller Device Code in the systemd service file."
        exit 1
    fi

    if ! sed --in-place "s#{{ AEMBIT_AGENT_CONTROLLER_ID }}#${AEMBIT_AGENT_CONTROLLER_ID}#" /etc/systemd/system/aembit_agent_controller.service; then
        echo "Unable to update the Agent Controller Agent Controller Id in the systemd service file."
        exit 1
    fi

    if ! systemctl enable aembit_agent_controller.service; then
        echo "Unable to enable the Agent Controller systemd service."
        exit 1
    fi

    if ! systemctl start aembit_agent_controller.service; then
        echo "Unable to start the Agent Controller systemd service."
        exit 1
    fi
}

run_installer() {
    if [ "$(id --user)" -ne 0 ]; then
        echo "Installer must be run as root."
        exit 1
    fi

    check_for_required_env_var AEMBIT_TENANT_ID || exit 1
    check_registration_method || exit 1
    set_default_stack_domain

    check_required_dependencies || exit 1
    check_for_existing_installation || exit 1
    create_user_and_group || exit 1
    set_up_logs || exit 1
    copy_static_components_to_host || exit 1
    install_systemd_service || exit 1
}

main() {
    set -o pipefail
    run_installer 2>&1 | tee "${INSTALLER_DIR}"/installer.log
}

main || exit 1
