#!/bin/sh
# Hubble Gateway boot-time provisioner.
#
# Reads an operator-supplied config file from the FAT boot partition
# (edited on any computer after flashing) and turns it into the runtime
# environment file consumed by hubble-gateway.service. Optionally also brings
# up wifi as a fallback to Raspberry Pi Imager's native wifi customization.
#
# Boot-partition file (default: /boot/firmware/hubble-gateway.conf):
#
#   SDK_KEY=hsk_xxxxxxxxxxxxxxxx      # required
#   LAT=37.7749                       # fixed latitude  (or use GPS=true)
#   LON=-122.4194                     # fixed longitude
#   GPS=false                         # true to use a GPS module instead of LAT/LON
#   GPS_PORT=/dev/ttyAMA0
#   GPS_BAUD=9600
#   GPS_MODULE=nmea                   # nmea | zed_f9p
#   ADAPTER=hci1                      # BLE adapter (onboard radio is hci0; a
#                                     # USB dongle is usually hci1)
#   API_URL=                          # override gateway API base URL
#   WIFI_SSID=                        # optional wifi fallback (Imager wifi preferred)
#   WIFI_PSK=
#   WIFI_COUNTRY=US
#   SSH_AUTHORIZED_KEY=ssh-ed25519 AAAA... you@laptop
#                                     # optional; authorize an SSH public key
#                                     # for the login user (uid 1000). May be
#                                     # repeated, one key per line.
#   SSH_PASSWORD_AUTH=no              # optional; yes re-enables SSH password
#                                     # login (off by default, key-only)
#
# HUBBLE_*-prefixed keys are also accepted (e.g. HUBBLE_SDK_KEY=...).

set -eu

INSTALL_DIR="/opt/hubble-gateway"
ENV_FILE="${INSTALL_DIR}/.env"

log() { echo "hubble-provision: $*"; }

# --- Locate the boot-partition config -------------------------------------

BOOT_DIR=""
for d in /boot/firmware /boot; do
    if [ -d "$d" ]; then
        BOOT_DIR="$d"
        break
    fi
done

CONF=""
if [ -n "$BOOT_DIR" ]; then
    for name in hubble-gateway.conf hubble-gateway.txt; do
        if [ -f "${BOOT_DIR}/${name}" ]; then
            CONF="${BOOT_DIR}/${name}"
            break
        fi
    done
fi

# --- Load existing baked-in values so operator config only overrides -------

SDK_KEY=""; API_URL=""; LAT=""; LON=""
GPS="false"; GPS_PORT=""; GPS_BAUD=""; GPS_MODULE=""; ADAPTER=""
WIFI_SSID=""; WIFI_PSK=""; WIFI_COUNTRY=""
SSH_KEYS=""; SSH_PASSWORD_AUTH=""
NL='
'

load_env_defaults() {
    [ -f "$ENV_FILE" ] || return 0
    # Seed from any values baked into the image at build time.
    while IFS='=' read -r k v; do
        case "$k" in
            HUBBLE_SDK_KEY)      SDK_KEY="$v" ;;
            HUBBLE_API_BASE_URL) API_URL="$v" ;;
            HUBBLE_LATITUDE)     LAT="$v" ;;
            HUBBLE_LONGITUDE)    LON="$v" ;;
            HUBBLE_GPS_ENABLED)  GPS="$v" ;;
            HUBBLE_GPS_PORT)     GPS_PORT="$v" ;;
            HUBBLE_GPS_BAUD_RATE) GPS_BAUD="$v" ;;
            HUBBLE_GPS_MODULE)   GPS_MODULE="$v" ;;
            HUBBLE_BLE_ADAPTER)  ADAPTER="$v" ;;
        esac
    done < "$ENV_FILE"
}

# Strip an inline comment (whitespace followed by '#' through end of line).
# A fully quoted value is left untouched so a '#' inside quotes (e.g. a wifi
# passphrase) is preserved.
strip_comment() {
    v="$1"
    case "$v" in
        \"*\"|\'*\') printf '%s' "$v"; return ;;
        *' #'*)  v="${v%% #*}" ;;
        *"$(printf '\t')#"*) v="${v%%"$(printf '\t')#"*}" ;;
    esac
    printf '%s' "$v"
}

# Strip surrounding whitespace and matching single/double quotes from a value.
trim() {
    v="$1"
    v="${v#"${v%%[![:space:]]*}"}"   # leading ws
    v="${v%"${v##*[![:space:]]}"}"   # trailing ws
    case "$v" in
        \"*\") v="${v#\"}"; v="${v%\"}" ;;
        \'*\') v="${v#\'}"; v="${v%\'}" ;;
    esac
    printf '%s' "$v"
}

parse_conf() {
    [ -n "$CONF" ] || return 0
    log "reading operator config from ${CONF}"
    while IFS= read -r line || [ -n "$line" ]; do
        case "$line" in
            ''|'#'*) continue ;;
        esac
        key="${line%%=*}"
        val="${line#*=}"
        [ "$key" = "$line" ] && continue   # no '=' on the line
        key="$(trim "$key")"
        val="$(strip_comment "$val")"
        val="$(trim "$val")"
        case "$key" in
            SDK_KEY|HUBBLE_SDK_KEY)          SDK_KEY="$val" ;;
            API_URL|HUBBLE_API_BASE_URL)     API_URL="$val" ;;
            LAT|LATITUDE|HUBBLE_LATITUDE)    LAT="$val" ;;
            LON|LONGITUDE|HUBBLE_LONGITUDE)  LON="$val" ;;
            GPS|GPS_ENABLED|HUBBLE_GPS_ENABLED) GPS="$val" ;;
            GPS_PORT|HUBBLE_GPS_PORT)        GPS_PORT="$val" ;;
            GPS_BAUD|GPS_BAUD_RATE|HUBBLE_GPS_BAUD_RATE) GPS_BAUD="$val" ;;
            GPS_MODULE|HUBBLE_GPS_MODULE)    GPS_MODULE="$val" ;;
            ADAPTER|HUBBLE_BLE_ADAPTER)      ADAPTER="$val" ;;
            WIFI_SSID)                       WIFI_SSID="$val" ;;
            WIFI_PSK|WIFI_PASSWORD)          WIFI_PSK="$val" ;;
            WIFI_COUNTRY)                    WIFI_COUNTRY="$val" ;;
            SSH_AUTHORIZED_KEY|SSH_AUTHORIZED_KEYS|SSH_KEY)
                if [ -n "$val" ]; then SSH_KEYS="${SSH_KEYS}${val}${NL}"; fi ;;
            SSH_PASSWORD_AUTH)               SSH_PASSWORD_AUTH="$val" ;;
            *) log "ignoring unknown key '${key}'" ;;
        esac
    done < "$CONF"
}

write_env() {
    umask 077
    mkdir -p "$INSTALL_DIR"
    tmp="${ENV_FILE}.tmp"
    : > "$tmp"
    [ -n "$SDK_KEY" ]    && echo "HUBBLE_SDK_KEY=${SDK_KEY}"        >> "$tmp"
    [ -n "$API_URL" ]    && echo "HUBBLE_API_BASE_URL=${API_URL}"  >> "$tmp"
    [ -n "$LAT" ]        && echo "HUBBLE_LATITUDE=${LAT}"          >> "$tmp"
    [ -n "$LON" ]        && echo "HUBBLE_LONGITUDE=${LON}"         >> "$tmp"
    echo "HUBBLE_GPS_ENABLED=${GPS:-false}"                        >> "$tmp"
    [ -n "$GPS_PORT" ]   && echo "HUBBLE_GPS_PORT=${GPS_PORT}"     >> "$tmp"
    [ -n "$GPS_BAUD" ]   && echo "HUBBLE_GPS_BAUD_RATE=${GPS_BAUD}" >> "$tmp"
    [ -n "$GPS_MODULE" ] && echo "HUBBLE_GPS_MODULE=${GPS_MODULE}" >> "$tmp"
    [ -n "$ADAPTER" ]    && echo "HUBBLE_BLE_ADAPTER=${ADAPTER}"   >> "$tmp"
    mv "$tmp" "$ENV_FILE"
    chmod 600 "$ENV_FILE"
    log "wrote ${ENV_FILE}"
}

# --- Optional wifi fallback (Imager's native wifi is preferred) ------------

configure_wifi() {
    [ -n "$WIFI_SSID" ] || return 0
    command -v nmcli >/dev/null 2>&1 || { log "nmcli not available, skipping wifi"; return 0; }

    if [ -n "$WIFI_COUNTRY" ] && command -v iw >/dev/null 2>&1; then
        iw reg set "$WIFI_COUNTRY" 2>/dev/null || true
    fi

    if nmcli -t -f NAME connection show 2>/dev/null | grep -qx "$WIFI_SSID"; then
        log "wifi connection '${WIFI_SSID}' already present"
        return 0
    fi

    log "creating wifi connection for SSID '${WIFI_SSID}'"
    if [ -n "$WIFI_PSK" ]; then
        nmcli connection add type wifi con-name "$WIFI_SSID" ifname wlan0 \
            ssid "$WIFI_SSID" \
            wifi-sec.key-mgmt wpa-psk wifi-sec.psk "$WIFI_PSK" \
            connection.autoconnect yes >/dev/null 2>&1 || log "wifi setup failed"
    else
        nmcli connection add type wifi con-name "$WIFI_SSID" ifname wlan0 \
            ssid "$WIFI_SSID" connection.autoconnect yes >/dev/null 2>&1 || log "wifi setup failed"
    fi
}

# --- SSH access -------------------------------------------------------------

# The image ships with no password for the login user and SSH restricted to
# public keys. These let an operator authorize a key (or opt back in to
# password SSH) from the boot partition, without Imager.

# Login user = uid 1000 (Imager's customization may have renamed it).
login_user() { getent passwd 1000 | cut -d: -f1; }

install_ssh_keys() {
    [ -n "$SSH_KEYS" ] || return 0
    user="$(login_user)"
    if [ -z "$user" ]; then
        log "no uid 1000 login user; cannot install SSH_AUTHORIZED_KEY"
        return 0
    fi
    home="$(getent passwd "$user" | cut -d: -f6)"
    group="$(id -gn "$user")"
    [ -d "$home" ] || { log "home ${home} for ${user} missing; skipping SSH keys"; return 0; }
    install -d -m 0700 -o "$user" -g "$group" "${home}/.ssh"
    ak="${home}/.ssh/authorized_keys"
    [ -f "$ak" ] || install -m 0600 -o "$user" -g "$group" /dev/null "$ak"
    printf '%s' "$SSH_KEYS" | while IFS= read -r key; do
        [ -n "$key" ] || continue
        case "$key" in
            ssh-*|ecdsa-*|sk-*) ;;
            *) log "ignoring SSH_AUTHORIZED_KEY that is not an OpenSSH public key"; continue ;;
        esac
        if grep -qxF -- "$key" "$ak"; then
            log "SSH key already authorized for ${user}"
        else
            printf '%s\n' "$key" >> "$ak"
            log "authorized SSH key (${key%% *}) for ${user}"
        fi
    done
    chown "$user:$group" "$ak"
    chmod 0600 "$ak"
}

configure_ssh_password_auth() {
    [ -n "$SSH_PASSWORD_AUTH" ] || return 0
    # Sorts before rpi-image-gen's 01pubkey-only.conf; sshd uses the first
    # value it reads for each keyword.
    dropin=/etc/ssh/sshd_config.d/00-hubble-password-auth.conf
    case "$(printf '%s' "$SSH_PASSWORD_AUTH" | tr 'A-Z' 'a-z')" in
        1|y|yes|true|on)
            mkdir -p /etc/ssh/sshd_config.d
            printf '%s\n' \
                "# Written by hubble-provision (SSH_PASSWORD_AUTH=yes)." \
                "PasswordAuthentication yes" \
                "AuthenticationMethods any" > "$dropin"
            chmod 0644 "$dropin"
            log "SSH password authentication ENABLED"
            pw="$(getent shadow "$(login_user)" 2>/dev/null | cut -d: -f2)"
            case "$pw" in
                ''|'!'*|'*'*) log "WARNING: $(login_user) has no password set; password SSH will not work until one is set (e.g. via Imager)" ;;
            esac
            ;;
        0|n|no|false|off)
            rm -f "$dropin"
            log "SSH password authentication disabled (key-only)"
            ;;
        *) log "ignoring SSH_PASSWORD_AUTH='${SSH_PASSWORD_AUTH}' (use yes or no)"; return 0 ;;
    esac
    systemctl try-reload-or-restart ssh.service 2>/dev/null || true
}

# --- Bluetooth ------------------------------------------------------------

# Fresh images boot with the Bluetooth radio rfkill soft-blocked, which makes
# BlueZ scanning fail with "Resource Not Ready". Clear the soft block (via
# sysfs, so no rfkill package is required) and power the adapters up.
unblock_bluetooth() {
    for d in /sys/class/rfkill/*; do
        [ -r "$d/type" ] || continue
        if [ "$(cat "$d/type" 2>/dev/null)" = "bluetooth" ]; then
            echo 0 > "$d/soft" 2>/dev/null \
                && log "unblocked $(cat "$d/name" 2>/dev/null)"
        fi
    done
    if command -v hciconfig >/dev/null 2>&1; then
        for h in /sys/class/bluetooth/hci*; do
            [ -e "$h" ] || continue
            hciconfig "$(basename "$h")" up 2>/dev/null || true
        done
    fi
}

# --- Run --------------------------------------------------------------------

load_env_defaults
parse_conf
write_env
unblock_bluetooth
configure_wifi
install_ssh_keys
configure_ssh_password_auth

if [ -z "$SDK_KEY" ]; then
    log "WARNING: no SDK key set. Add SDK_KEY=... to ${BOOT_DIR:-/boot/firmware}/hubble-gateway.conf and reboot."
fi

# Avoid leaving the SDK key in plaintext on the FAT partition and avoid
# reprocessing on subsequent boots. Keep a copy the operator can re-enable.
if [ -n "$CONF" ]; then
    mv "$CONF" "${CONF}.applied" 2>/dev/null || true
    log "consumed ${CONF} -> ${CONF}.applied"
fi

exit 0
