#!/usr/bin/env bash
set -euo pipefail

# ---------------------------------------------------------------------------
# provision-tetherbox-ubuntu.sh
#
# Fresh Ubuntu Server 26.04 LTS bootstrap for Social Telecoms TetherBoxes.
#
# Expected starting state:
#   - Ubuntu Server 26.04 LTS already installed
#   - admin user "tetherx" created during installation
#   - SSH enabled
#
# This script:
#   - creates/updates Social Telecoms admin user "stcic"
#   - gives stcic sudo rights
#   - installs GitHub CLI
#   - authenticates GitHub CLI
#   - clones/updates stcic/tetherbox
#   - syntax-checks repo scripts
#   - runs preparations.sh with supplied metadata
#
# It does NOT install the TetherX service.
# TetherX provisions remotely over SSH via Cloudflare Tunnel.
# ---------------------------------------------------------------------------

REPO="stcic/tetherbox"
REPO_DIR="$HOME/tetherbox"

SOCIAL_ADMIN_USER="stcic"
TETHERX_USER="tetherx"

DEFAULT_CUSTOMER_NAME="South Tyneside Homes"
DEFAULT_SERVICES="TetherX"
DEFAULT_PRIMARY_STORAGE="Internal SSD"
DEFAULT_LAST_ACTION_BY="Oliver"
DEFAULT_NEXT_CHECK_DATE="2026-07-16"
DEFAULT_NOTES="Ubuntu Server 26.04 LTS TetherBox prepared by Social Telecoms for TetherX remote provisioning via Cloudflare Tunnel SSH"

info()    { echo "[INFO]  $*"; }
warn()    { echo "[WARN]  $*" >&2; }
section() { echo ""; echo "=== $* ==="; }

prompt_required() {
    local label="$1"
    local value=""
    while [[ -z "$value" ]]; do
        read -r -p "$label: " value
    done
    printf '%s' "$value"
}

prompt_default() {
    local label="$1"
    local default="$2"
    local value=""
    read -r -p "$label [$default]: " value
    printf '%s' "${value:-$default}"
}

require_sudo() {
    if [[ "$EUID" -eq 0 ]]; then
        warn "Running as root. This will work, but normally run as the install admin user, e.g. tetherx."
    elif ! sudo -n true 2>/dev/null; then
        info "Checking sudo access..."
        sudo true
    fi
}

check_os() {
    section "Checking OS"

    if [[ ! -f /etc/os-release ]]; then
        warn "Cannot find /etc/os-release. Continuing anyway."
        return
    fi

    # shellcheck disable=SC1091
    source /etc/os-release

    echo "Detected OS: ${PRETTY_NAME:-unknown}"

    if [[ "${ID:-}" != "ubuntu" ]]; then
        warn "This script is intended for Ubuntu Server 26.04 LTS."
        read -r -p "Continue anyway? [y/N] " response
        [[ "$response" =~ ^[Yy]$ ]] || exit 1
    fi

    if [[ "${VERSION_ID:-}" != "26.04" ]]; then
        warn "Detected Ubuntu version ${VERSION_ID:-unknown}; expected 26.04."
        read -r -p "Continue anyway? [y/N] " response
        [[ "$response" =~ ^[Yy]$ ]] || exit 1
    fi
}

create_social_admin_user() {
    section "Creating Social Telecoms admin user: $SOCIAL_ADMIN_USER"

    if id "$SOCIAL_ADMIN_USER" &>/dev/null; then
        info "User '$SOCIAL_ADMIN_USER' already exists."
    else
        sudo adduser "$SOCIAL_ADMIN_USER"
    fi

    sudo usermod -aG sudo "$SOCIAL_ADMIN_USER"

    info "Ensuring '$SOCIAL_ADMIN_USER' is in sudo group:"
    id "$SOCIAL_ADMIN_USER"

    echo ""
    echo "You should set a unique password for '$SOCIAL_ADMIN_USER'."
    echo "This should NOT be the same password given to TetherX."
    echo ""

    read -r -p "Set or reset password for '$SOCIAL_ADMIN_USER' now? [Y/n] " response
    response="${response:-Y}"

    if [[ "$response" =~ ^[Yy]$ ]]; then
        sudo passwd "$SOCIAL_ADMIN_USER"
    else
        warn "Password for '$SOCIAL_ADMIN_USER' was not changed."
        warn "Make sure you know the existing password before handing the box over."
    fi
}

install_github_cli() {
    section "Installing GitHub CLI"

    sudo apt update
    sudo apt install -y curl ca-certificates git gnupg gpg

    if command -v gh &>/dev/null; then
        info "GitHub CLI already installed: $(gh --version | head -1)"
        return
    fi

    sudo mkdir -p -m 755 /etc/apt/keyrings

    curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg | \
        sudo tee /etc/apt/keyrings/githubcli-archive-keyring.gpg > /dev/null

    sudo chmod go+r /etc/apt/keyrings/githubcli-archive-keyring.gpg

    echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/githubcli-archive-keyring.gpg] https://cli.github.com/packages stable main" | \
        sudo tee /etc/apt/sources.list.d/github-cli.list > /dev/null

    sudo apt update
    sudo apt install -y gh

    gh --version
}

github_login() {
    section "GitHub authentication"

    if gh auth status &>/dev/null; then
        info "GitHub CLI is already authenticated."
        gh auth status || true
        return
    fi

    echo ""
    echo "GitHub CLI needs to authenticate to clone the private repo."
    echo "Choose:"
    echo "  GitHub.com"
    echo "  HTTPS"
    echo "  Authenticate Git with your GitHub credentials: Yes"
    echo "  Login with a web browser"
    echo ""
    echo "If it cannot open a browser, copy the one-time code and open:"
    echo "  https://github.com/login/device"
    echo "on your laptop."
    echo ""

    gh auth login
    gh auth status
}

clone_or_update_repo() {
    section "Cloning/updating repo"

    if [[ -d "$REPO_DIR/.git" ]]; then
        info "$REPO_DIR already exists. Pulling latest changes."
        git -C "$REPO_DIR" pull --ff-only
    else
        gh repo clone "$REPO" "$REPO_DIR"
    fi

    cd "$REPO_DIR"

    chmod +x ./*.sh 2>/dev/null || true

    section "Syntax-checking repo scripts"

    bash -n bootstrap.sh
    bash -n preparations.sh
    bash -n flash-prep.sh
    bash -n install.sh

    info "Repo scripts passed bash syntax checks."
}

collect_metadata() {
    section "Deployment metadata"

    echo "Enter the values for this specific TetherBox."
    echo ""

    ASSET_TAG="$(prompt_required "Asset tag, e.g. TB-STH-001")"
    SITE_NAME="$(prompt_required "Site name, e.g. Calf Close House")"
    SITE_ADDRESS="$(prompt_default "Site address" "$SITE_NAME")"
    CUSTOMER_NAME="$(prompt_default "Customer name" "$DEFAULT_CUSTOMER_NAME")"
    PRIMARY_STORAGE_MEDIUM="$(prompt_default "Primary storage medium" "$DEFAULT_PRIMARY_STORAGE")"
    TUNNEL_HOSTNAME="$(prompt_required "Cloudflare tunnel hostname, e.g. calf-close-house-tetherbox.backbonettf.co.uk")"
    LAST_ACTION_BY="$(prompt_default "Last action by" "$DEFAULT_LAST_ACTION_BY")"
    NEXT_CHECK_DATE="$(prompt_default "Next check date" "$DEFAULT_NEXT_CHECK_DATE")"
    NOTES="$(prompt_default "Notes" "$DEFAULT_NOTES")"

    echo ""
    echo "Summary:"
    echo "  Asset tag:       $ASSET_TAG"
    echo "  Customer:        $CUSTOMER_NAME"
    echo "  Site:            $SITE_NAME"
    echo "  Site address:    $SITE_ADDRESS"
    echo "  TetherX user:    $TETHERX_USER"
    echo "  STCIC user:      $SOCIAL_ADMIN_USER"
    echo "  Tunnel hostname: $TUNNEL_HOSTNAME"
    echo ""

    read -r -p "Continue with these details? [Y/n] " response
    response="${response:-Y}"
    [[ "$response" =~ ^[Yy]$ ]] || exit 1
}

run_preparations() {
    section "Running repo preparations.sh"

    cd "$REPO_DIR"

    ./preparations.sh \
        --asset-tag "$ASSET_TAG" \
        --customer-name "$CUSTOMER_NAME" \
        --site-name "$SITE_NAME" \
        --site-address "$SITE_ADDRESS" \
        --host-machine "x64 TetherBox" \
        --primary-storage-medium "$PRIMARY_STORAGE_MEDIUM" \
        --admin-username "$TETHERX_USER" \
        --tunnel-hostname "$TUNNEL_HOSTNAME" \
        --last-action-by "$LAST_ACTION_BY" \
        --next-check-date "$NEXT_CHECK_DATE" \
        --notes "$NOTES"
}

print_next_steps() {
    section "Next steps"

    cat <<EOF
If Tailscale authentication is required for Social Telecoms maintenance access, run:

  sudo tailscale up

Then approve the device in the browser and re-run:

  cd "$REPO_DIR"
  ./preparations.sh

If the Cloudflare Tunnel token was not supplied or the tunnel was not active,
re-run:

  cd "$REPO_DIR"
  ./preparations.sh

Final checks:

  systemctl is-active ssh
  systemctl is-active cockpit.socket
  tailscale status
  tailscale ip -4
  cloudflared --version
  systemctl is-active cloudflared
  systemctl status cloudflared --no-pager
  journalctl -u cloudflared -n 50 --no-pager

For TetherX handover, provide:

  Hostname: $TUNNEL_HOSTNAME
  Username: $TETHERX_USER
  Access method: Cloudflare Tunnel SSH via cloudflared ProxyCommand

Do NOT give TetherX the '$SOCIAL_ADMIN_USER' account details.

Keep '$SOCIAL_ADMIN_USER' as the Social Telecoms admin/break-glass account.
EOF
}

main() {
    echo ""
    echo "============================================================"
    echo " Social Telecoms — Fresh Ubuntu TetherBox Provisioning"
    echo "============================================================"
    echo ""

    require_sudo
    check_os
    create_social_admin_user
    install_github_cli
    github_login
    clone_or_update_repo
    collect_metadata
    run_preparations
    print_next_steps

    echo ""
    echo "============================================================"
    echo " Provisioning wrapper complete."
    echo " Review the preparations.sh final status above before handover."
    echo "============================================================"
    echo ""
}

main "$@"
