#!/bin/sh
#
# bootstrap.sh -- stage-0 bootstrap for new aitken.com hosts
#
# Downloads the OS-specific setup.sh and its dependencies from the web tree,
# then runs setup.sh under script(1) to produce a transcript log.
#
# Usage:
#   sh bootstrap.sh <fqdn>
#
# Environment (override for testing):
#   DIST_SITE   base URL of the distribution tree  (default: https://dist.aitken.com)
#   DEST_DIR    local staging directory             (default: /root/initial-setup)
#
# Self-contained: does NOT source aitken.conf or common.sh.  Stage-0 runs
# before NFS is mounted so /home/admin does not exist yet.

umask 022
PATH=/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin
export PATH
set -e
trap '[ $? -eq 0 ] || printf "ERROR: bootstrap.sh did not complete successfully.\n" >&2' EXIT
trap 'exit 1' INT HUP TERM

DIST_SITE="${DIST_SITE:-https://dist.aitken.com}"
DEST_DIR="${DEST_DIR:-/root/initial-setup}"


die() { printf 'ERROR: %s\n' "$*" >&2; exit 1; }


# --------------------------------------------------------------------------
# detect_os -- print the OS identifier string, or "Unknown-OS"
# --------------------------------------------------------------------------
detect_os() {
    _uname=$(uname -s)
    case "$_uname" in
        Linux)
            if [ -f /etc/os-release ]; then
                # shellcheck source=/dev/null
                . /etc/os-release
                _distro=$(printf '%s' "$NAME" | tr ' ' '_')
                printf '%s-%s' "$_distro" "$VERSION_ID"
            else
                printf 'Linux-Unknown'
            fi
            ;;
        FreeBSD)
            printf 'FreeBSD-%s' "$(freebsd-version | cut -d'-' -f1)"
            ;;
        *)
            printf 'Unknown-OS'
            ;;
    esac
}


# --------------------------------------------------------------------------
# dl url dest_file -- fetch url to dest_file using the first available tool
# --------------------------------------------------------------------------
_DL=""

_find_downloader() {
    if command -v curl > /dev/null 2>&1; then
        _DL=curl
    elif command -v fetch > /dev/null 2>&1; then
        _DL=fetch
    elif command -v wget > /dev/null 2>&1; then
        _DL=wget
    else
        die "No supported downloader found (curl, fetch, or wget is required)"
    fi
}

dl() {
    _url="$1" _dest="$2"
    case "$_DL" in
        curl)  curl  -fsSL -o "$_dest" "$_url" ;;
        fetch) fetch -q    -o "$_dest" "$_url" ;;
        wget)  wget  -qO       "$_dest" "$_url" ;;
    esac
}


# --------------------------------------------------------------------------
# main
# --------------------------------------------------------------------------

[ -n "$1" ] || die "Usage: sh bootstrap.sh <fqdn>"
_fqdn="$1"

_os=$(detect_os | tr '[:upper:]' '[:lower:]')
case "$_os" in
    ubuntu-26.04 | freebsd-14.4) ;;
    *) die "Unsupported OS: $_os" ;;
esac

printf 'OS:           %s\n' "$_os"
printf 'Target FQDN:  %s\n' "$_fqdn"
printf 'Staging dir:  %s\n' "$DEST_DIR"
printf 'Source:       %s/admin\n' "$DIST_SITE"

_find_downloader
printf 'Downloader:   %s\n' "$_DL"

_setup_dir="${DEST_DIR}/${_os}"
_setup="${_setup_dir}/setup.sh"
_log="${_setup_dir}/log"
mkdir -p "$_setup_dir"

printf '\nFetching bootstrap files...\n'
dl "${DIST_SITE}/admin/aitken.conf"      "${DEST_DIR}/aitken.conf"
dl "${DIST_SITE}/admin/common.sh"        "${DEST_DIR}/common.sh"
dl "${DIST_SITE}/admin/${_os}/setup.sh"  "${_setup}"

printf 'Running setup.sh under script(1); log: %s\n' "$_log"
case "$_os" in
    ubuntu-26.04)
        script -c "sh ${_setup} ${_fqdn}" "${_log}"
        ;;
    freebsd-14.4)
        script -q "${_log}" sh "${_setup}" "${_fqdn}"
        ;;
esac
