#!/bin/sh
# Treeward Shirudo host installer (https://get.treeward.ai)
# Supports Ubuntu 24.04 LTS (noble) and Debian 12 (bookworm) on amd64.
set -eu

TREEWARD_APT_URL="${TREEWARD_APT_URL:-https://get.treeward.ai/apt}"
TREEWARD_GPG_URL="${TREEWARD_GPG_URL:-https://get.treeward.ai/gpg.key}"
TREEWARD_DRY_RUN="${TREEWARD_DRY_RUN:-0}"

# Path overrides (primarily for automated testing).
OS_RELEASE_PATH="${TREEWARD_OS_RELEASE:-/etc/os-release}"
TPM_DEVICE_PATH="${TREEWARD_TPM_DEVICE:-/dev/tpmrm0}"
EFIVARS_DIR="${TREEWARD_EFIVARS_DIR:-/sys/firmware/efi/efivars}"
SYSTEMD_RUN_DIR="${TREEWARD_SYSTEMD_RUN_DIR:-/run/systemd/system}"
GRUB_DIR="${TREEWARD_GRUB_DIR:-/boot/grub}"
GRUB_DEFAULT_FILE="${TREEWARD_GRUB_DEFAULT:-/etc/default/grub}"
APT_KEYRING_PATH="${TREEWARD_APT_KEYRING:-/etc/apt/keyrings/treeward.gpg}"
APT_LIST_PATH="${TREEWARD_APT_LIST:-/etc/apt/sources.list.d/treeward.list}"

log() {
    printf '[treeward-install] %s\n' "$*"
}

fail() {
    printf '[treeward-install] ERROR: %s\n' "$*" >&2
    exit 1
}

check_root() {
    uid="$(id -u)"
    if [ "$uid" -ne 0 ]; then
        fail "This installer must be run as root (e.g. curl -fsSL https://get.treeward.ai | sudo sh)."
    fi
}

OS_ID=""
OS_VERSION_ID=""
OS_CODENAME=""

check_os() {
    if [ ! -r "$OS_RELEASE_PATH" ]; then
        fail "Cannot read $OS_RELEASE_PATH; unable to detect operating system."
    fi

    while IFS='=' read -r key val; do
        # Strip surrounding double or single quotes.
        val="${val#\"}"
        val="${val%\"}"
        val="${val#\'}"
        val="${val%\'}"
        case "$key" in
            ID) OS_ID="$val" ;;
            VERSION_ID) OS_VERSION_ID="$val" ;;
            VERSION_CODENAME) OS_CODENAME="$val" ;;
        esac
    done < "$OS_RELEASE_PATH"

    case "$OS_ID" in
        ubuntu)
            if [ "$OS_CODENAME" = "noble" ] || [ "$OS_VERSION_ID" = "24.04" ]; then
                OS_CODENAME="noble"
                return 0
            fi
            ;;
        debian)
            if [ "$OS_CODENAME" = "bookworm" ] || [ "$OS_VERSION_ID" = "12" ]; then
                OS_CODENAME="bookworm"
                return 0
            fi
            ;;
    esac

    fail "Unsupported OS: ${OS_ID:-unknown} ${OS_VERSION_ID:-unknown} (${OS_CODENAME:-unknown}). Supported platforms: Ubuntu 24.04 LTS (noble) and Debian 12 (bookworm)."
}

check_arch() {
    arch=""
    if command -v dpkg >/dev/null 2>&1; then
        arch="$(dpkg --print-architecture)"
    else
        case "$(uname -m)" in
            x86_64) arch="amd64" ;;
            aarch64|arm64) arch="arm64" ;;
            *) arch="$(uname -m)" ;;
        esac
    fi

    if [ "$arch" != "amd64" ]; then
        fail "Unsupported architecture: ${arch}. Only amd64 is supported in v1."
    fi
}

check_systemd() {
    if [ ! -d "$SYSTEMD_RUN_DIR" ]; then
        fail "systemd does not appear to be running (${SYSTEMD_RUN_DIR} not found). systemd is required."
    fi
}

check_grub() {
    if command -v update-grub >/dev/null 2>&1 \
        || command -v grub-mkconfig >/dev/null 2>&1 \
        || [ -d "$GRUB_DIR" ] \
        || [ -f "$GRUB_DEFAULT_FILE" ]; then
        return 0
    fi
    fail "GRUB bootloader was not detected. GRUB is required to boot linux-image-shirudo."
}

check_secure_boot() {
    sb_enabled=0

    if command -v mokutil >/dev/null 2>&1; then
        sb_out="$(mokutil --sb-state 2>/dev/null || true)"
        case "$sb_out" in
            *"SecureBoot enabled"*)
                sb_enabled=1
                ;;
        esac
    fi

    if [ "$sb_enabled" -eq 0 ] && [ -d "$EFIVARS_DIR" ]; then
        for sb_var in "$EFIVARS_DIR"/SecureBoot-*; do
            if [ -r "$sb_var" ]; then
                # EFI variables have a 4-byte attribute header followed by the value byte.
                sb_byte="$(od -An -tx1 -j4 -N1 "$sb_var" 2>/dev/null | tr -d ' \n\r\t' || true)"
                if [ "$sb_byte" = "01" ]; then
                    sb_enabled=1
                fi
                break
            fi
        done
    fi

    if [ "$sb_enabled" -ne 0 ]; then
        cat >&2 <<'EOF'
[treeward-install] ERROR: UEFI Secure Boot is enabled.
The Shirudo kernel (linux-image-shirudo) is not yet signed for Secure Boot in v1.
Please disable Secure Boot before running this installer:
  - Bare metal / VM: disable Secure Boot in UEFI/BIOS firmware settings.
  - GCP Compute Engine: recreate or update the instance with --no-shielded-secure-boot.
  - AWS EC2: use an instance/AMI without UEFI Secure Boot enabled.
EOF
        exit 1
    fi
}

check_tpm2() {
    if [ ! -e "$TPM_DEVICE_PATH" ]; then
        cat >&2 <<'EOF'
[treeward-install] ERROR: TPM 2.0 device (/dev/tpmrm0) not found.
Treeward requires a hardware TPM 2.0 or cloud vTPM for host attestation (no unattested fallback).
  - Bare metal: enable TPM 2.0 / fTPM / PTT in UEFI/BIOS.
  - GCP Compute Engine: enable Shielded VM vTPM (--shielded-vtpm).
  - AWS EC2: use NitroTPM-enabled instances.
EOF
        exit 1
    fi
}

fetch_url() {
    url="$1"
    if command -v curl >/dev/null 2>&1; then
        curl -fsSL "$url"
    elif command -v wget >/dev/null 2>&1; then
        wget -qO- "$url"
    else
        fail "Neither curl nor wget is installed; cannot fetch ${url}."
    fi
}

configure_apt_and_install() {
    repo_line="deb [arch=amd64 signed-by=${APT_KEYRING_PATH}] ${TREEWARD_APT_URL} ${OS_CODENAME} main"

    if [ "$TREEWARD_DRY_RUN" = "1" ]; then
        log "DRY RUN: skipping system modifications."
        log "DRY RUN: would fetch GPG key from ${TREEWARD_GPG_URL} -> ${APT_KEYRING_PATH}"
        log "DRY RUN: would write ${APT_LIST_PATH}: ${repo_line}"
        log "DRY RUN: would run: apt-get update"
        log "DRY RUN: would run: apt-get install -y linux-image-shirudo shirudo-runtime treeward-agent"
        return 0
    fi

    keyring_dir="$(dirname "$APT_KEYRING_PATH")"
    install -d -m 0755 "$keyring_dir"

    log "Fetching Treeward APT signing key from ${TREEWARD_GPG_URL}..."
    tmp_key="$(mktemp)"
    trap 'rm -f "$tmp_key"' EXIT
    fetch_url "$TREEWARD_GPG_URL" > "$tmp_key"

    if grep -q "BEGIN PGP PUBLIC KEY BLOCK" "$tmp_key"; then
        if ! command -v gpg >/dev/null 2>&1; then
            fail "gpg is required to dearmor the Treeward APT signing key."
        fi
        gpg --dearmor --yes -o "$APT_KEYRING_PATH" "$tmp_key"
    else
        cp "$tmp_key" "$APT_KEYRING_PATH"
    fi
    chmod 0644 "$APT_KEYRING_PATH"
    rm -f "$tmp_key"
    trap - EXIT

    log "Configuring Treeward APT repository (${APT_LIST_PATH})..."
    printf '%s\n' "$repo_line" > "$APT_LIST_PATH"
    chmod 0644 "$APT_LIST_PATH"

    log "Updating APT package index..."
    DEBIAN_FRONTEND=noninteractive apt-get update

    log "Installing linux-image-shirudo, shirudo-runtime, and treeward-agent..."
    DEBIAN_FRONTEND=noninteractive apt-get install -y \
        linux-image-shirudo \
        shirudo-runtime \
        treeward-agent
}

print_next_steps() {
    cat <<'EOF'

Treeward Shirudo packages are installed.

Next steps:
  1. Reboot into the Shirudo kernel:
       sudo reboot

  2. Enroll this host with your fleet token and pinned tree signing key:
       printf '%s\n' '<fleet-token>' | sudo treeward-agent enroll \
         --token-stdin \
         --pubkey-sha256 '<tree-pubkey-sha256>' \
         --env-file /etc/treeward/agent.env

  3. Enable and start the agent:
       sudo systemctl enable --now treeward-agent
EOF
}

main() {
    log "Running preflight checks..."
    check_root
    check_os
    check_arch
    check_systemd
    check_grub
    check_secure_boot
    check_tpm2
    log "Preflight checks passed (${OS_ID} ${OS_CODENAME}, amd64, TPM 2.0 present, Secure Boot disabled)."

    configure_apt_and_install
    print_next_steps
}

main "$@"
