#!/usr/bin/env bash
# Cloudmon bootstrap installer.
# Downloads the separately hosted CLI and installs it as /usr/bin/cloudmon.

set -Eeuo pipefail

readonly SCRIPT_VERSION="5.1.0"
readonly CLOUDMON_CLI_URL="https://repo.cloudmon.ai/scripts/cloudmon-cli.sh"
readonly CLOUDMON_CLI_PATH="/usr/bin/cloudmon"
readonly LOG_DIR_DEFAULT="/var/log/cloudmon-installer"

RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'; CYAN='\033[0;36m'; BOLD='\033[1m'; NC='\033[0m'

LOG_DIR="${LOG_DIR_DEFAULT}"
LOG_FILE=""
TMP_CLI=""
RUN_COMPLETED=false
ROOT_PRIVILEGES_REQUIRED=false

# When this script is piped to bash, draining stdin before an early exit avoids
# making curl report a misleading broken-pipe error.
_drain_stdin() {
    [[ -t 0 ]] || cat >/dev/null 2>&1 || true
}

_init_log() {
    mkdir -p "${LOG_DIR}" 2>/dev/null || LOG_DIR="/tmp"
    LOG_FILE="${LOG_DIR}/cloudmon-bootstrap-$(date +%Y-%m-%d_%H-%M-%S).log"
    touch "${LOG_FILE}" 2>/dev/null || LOG_FILE="/dev/null"
}

_log() {
    local level="$1"; shift
    [[ -n "${LOG_FILE}" ]] && printf '[%s] [%s] %s\n' "$(date '+%F %T')" "${level}" "$*" >> "${LOG_FILE}"
}

log_info()  { printf "  ${CYAN}%-8s${NC} %s\n" "[INFO]" "$*"; _log INFO "$*"; }
log_ok()    { printf "  ${GREEN}%-8s${NC} %s\n" "[OK]" "$*"; _log OK "$*"; }
log_warn()  { printf "  ${YELLOW}%-8s${NC} %s\n" "[WARN]" "$*"; _log WARN "$*"; }
log_error() { printf "  ${RED}%-8s${NC} %s\n" "[ERROR]" "$*" >&2; _log ERROR "$*"; }

cleanup() {
    local exit_code=$?

    # The EXIT handler can run after an error. Disarm both traps before any
    # command here can fail, preventing Bash from recursively entering ERR
    # while unwinding its function context.
    trap - EXIT ERR

    if [[ -n "${TMP_CLI}" && -f "${TMP_CLI}" ]]; then
        rm -f "${TMP_CLI}" || true
    fi

    if [[ ${exit_code} -ne 0 && "${RUN_COMPLETED}" != true && "${ROOT_PRIVILEGES_REQUIRED}" != true ]]; then
        log_error "Installer exited with code ${exit_code}.${LOG_FILE:+ Check log: ${LOG_FILE}}" || true
    fi

    exit "${exit_code}"
}
trap cleanup EXIT
trap 'log_error "Unexpected error on line ${LINENO}."; exit 1' ERR

ensure_root() {
    [[ "${EUID}" -eq 0 ]] && return 0

    ROOT_PRIVILEGES_REQUIRED=true

    if ! command -v sudo >/dev/null 2>&1; then
        printf "This installer must be run as root, and 'sudo' is unavailable.\n" >&2
        _drain_stdin
        exit 1
    fi

    # Re-executing works for a downloaded/local script. A piped script cannot
    # safely re-execute itself because its source is stdin.
    if [[ -f "$0" && "$0" != /dev/fd/* && "$0" != /proc/self/fd/* ]]; then
        exec sudo -E bash "$0" "$@"
    fi

    printf "This installer needs root privileges. Re-run it with sudo.\n" >&2
    _drain_stdin
    exit 1
}

check_prerequisites() {
    [[ "$(uname -s)" == "Linux" ]] || { log_error "Unsupported OS: $(uname -s). Linux is required."; exit 1; }

    local dependency
    for dependency in curl install bash; do
        command -v "${dependency}" >/dev/null 2>&1 || {
            log_error "Missing required tool: ${dependency}"
            exit 1
        }
    done
}

download_cli() {
    TMP_CLI="$(mktemp /tmp/cloudmon-cli.XXXXXX)"
    log_info "Downloading Cloudmon CLI..."

    if ! curl --fail --location --silent --show-error \
        --connect-timeout 15 --retry 3 --retry-delay 2 \
        "${CLOUDMON_CLI_URL}" --output "${TMP_CLI}"; then
        log_error "Could not download the Cloudmon CLI from ${CLOUDMON_CLI_URL}."
        exit 1
    fi

    [[ -s "${TMP_CLI}" ]] || { log_error "Downloaded CLI is empty."; exit 1; }
    if ! bash -n "${TMP_CLI}"; then
        log_error "Downloaded CLI failed its syntax check; it was not installed."
        exit 1
    fi
}

install_cli() {
    mkdir -p "$(dirname "${CLOUDMON_CLI_PATH}")"
    install -m 0755 -o root -g root "${TMP_CLI}" "${CLOUDMON_CLI_PATH}"
    log_ok "Cloudmon CLI installed: ${CLOUDMON_CLI_PATH}"
}

main() {
    ensure_root "$@"
    _init_log

    printf "${BOLD}${CYAN}Cloudmon Installer ${SCRIPT_VERSION}${NC}\n\n"
    check_prerequisites
    download_cli
    install_cli
    RUN_COMPLETED=true

    printf "\n${BOLD}${GREEN}✓ cloudmon CLI is installed.${NC}\n\n"
    printf "Next step: sudo cloudmon install controller\n"
    printf "Log: %s\n" "${LOG_FILE}"
    hash -r 2>/dev/null || true
}

main "$@"

