#!/bin/sh
# /etc/waouw/waouw-keyfetch
#
# LUKS keyscript: fetches the disk encryption key from waouw-admin
# during early boot (initramfs). Called by cryptsetup, must output
# the raw key on stdout.
#
# Environment: minimal initramfs (busybox + binaries added by hook).
# POSIX sh only — no bash, no arrays, no [[ ]].
#
# Network strategy:
#   1. Try Ethernet first (may already have IP via ip=dhcp in cmdline.txt)
#   2. Fall back to WiFi if Ethernet has no link
#
# Auth: HMAC-SHA256(timestamp + serial, SHA256(serial + "waouw-boot-2026"))
# Endpoint: POST https://admin.waouw.eu/api/device_luks_key.php

set -e

# -------------------------------------------------------------------
# Configuration
# -------------------------------------------------------------------
CA_BUNDLE="/etc/ssl/certs/ca-certificates.crt"
WIFI_CONF="/boot/firmware/wifi-initramfs.conf"
DEVICE_ID_FILE="/boot/firmware/waouw-device-id"
LOCAL_KEY_FILE="/boot/firmware/.waouw-luks-localkey"
LOT_ID_FILE="/boot/firmware/.waouw-lot-id"
ADMIN_URL_FILE="/boot/firmware/waouw-admin-url.txt"
BOOT_SALT="waouw-boot-2026"

# Read admin URL from boot partition
ADMIN_URL=""
if [ -f "$ADMIN_URL_FILE" ]; then
    ADMIN_URL="$(cat "$ADMIN_URL_FILE" 2>/dev/null | tr -d '\r\n ')"
fi
if [ -z "$ADMIN_URL" ]; then
    ADMIN_URL="https://admin.waouw.eu"
fi
ADMIN_URL="${ADMIN_URL}/api/device_luks_key.php"

MAX_ATTEMPTS=30
RETRY_INTERVAL=10

# Interfaces
ETH_IFACE="eth0"
WLAN_IFACE="wlan0"

# PIDs to clean up
WPA_PID=""
UDHCPC_PID=""

# -------------------------------------------------------------------
# Logging (visible on serial console, helps debugging)
# -------------------------------------------------------------------
log() {
    echo "waouw-keyfetch: $*" >/dev/console 2>/dev/null || true
}

log_err() {
    echo "waouw-keyfetch: ERROR: $*" >/dev/console 2>/dev/null || true
}

# -------------------------------------------------------------------
# Cleanup handler
# -------------------------------------------------------------------
cleanup() {
    # Kill wpa_supplicant if we started it
    if [ -n "$WPA_PID" ] && kill -0 "$WPA_PID" 2>/dev/null; then
        kill "$WPA_PID" 2>/dev/null || true
        wait "$WPA_PID" 2>/dev/null || true
        log "wpa_supplicant stopped"
    fi

    # Kill udhcpc if we started it
    if [ -n "$UDHCPC_PID" ] && kill -0 "$UDHCPC_PID" 2>/dev/null; then
        kill "$UDHCPC_PID" 2>/dev/null || true
        wait "$UDHCPC_PID" 2>/dev/null || true
    fi

    # Remove WiFi config copy from tmpfs (contains password)
    rm -f /tmp/wpa-initramfs.conf 2>/dev/null || true

    # Clear any key material from environment
    unset LUKS_KEY BOOT_SECRET HMAC_SIG TIMESTAMP SERIAL DEVICE_ID
}

trap cleanup EXIT

# -------------------------------------------------------------------
# Check for local key file (first boot after encryption)
# If present, use it directly — no network needed.
# The key will be registered on waouw-admin during install-complete.sh
# and the local file deleted afterwards.
# -------------------------------------------------------------------
if [ -f "$LOCAL_KEY_FILE" ]; then
    LOCAL_KEY=$(cat "$LOCAL_KEY_FILE" 2>/dev/null)
    if [ -n "$LOCAL_KEY" ] && [ ${#LOCAL_KEY} -ge 32 ]; then
        log "Using local key from $LOCAL_KEY_FILE (first boot)"
        printf '%s' "$LOCAL_KEY"
        unset LOCAL_KEY
        exit 0
    fi
    log "Local key file present but invalid, falling back to network"
fi

# -------------------------------------------------------------------
# Read device serial from /proc/cpuinfo
# -------------------------------------------------------------------
get_serial() {
    _serial=""
    if [ -f /proc/cpuinfo ]; then
        _serial=$(sed -n 's/^Serial[[:space:]]*:[[:space:]]*0*//p' /proc/cpuinfo)
    fi
    if [ -z "$_serial" ]; then
        log_err "cannot read device serial from /proc/cpuinfo"
        return 1
    fi
    echo "$_serial"
}

# -------------------------------------------------------------------
# Read device ID from boot partition
# -------------------------------------------------------------------
get_device_id() {
    if [ -f "$DEVICE_ID_FILE" ]; then
        _devid=$(cat "$DEVICE_ID_FILE" 2>/dev/null | tr -d '[:space:]')
        if [ -n "$_devid" ]; then
            echo "$_devid"
            return 0
        fi
    fi
    log_err "cannot read device ID from ${DEVICE_ID_FILE}"
    return 1
}

# -------------------------------------------------------------------
# Compute HMAC-SHA256 using openssl
#   $1 = message
#   $2 = key (hex or plaintext)
# Outputs hex-encoded HMAC
# -------------------------------------------------------------------
hmac_sha256() {
    _msg="$1"
    _key="$2"
    # openssl dgst outputs "stdin= <hex>" or "(stdin)= <hex>"
    _hmac=$(printf '%s' "$_msg" | openssl dgst -sha256 -hmac "$_key" 2>/dev/null | sed 's/^.*=[[:space:]]*//')
    if [ -z "$_hmac" ]; then
        log_err "HMAC computation failed"
        return 1
    fi
    echo "$_hmac"
}

# -------------------------------------------------------------------
# Compute SHA256 hash of a string
# -------------------------------------------------------------------
sha256_hash() {
    _input="$1"
    _hash=$(printf '%s' "$_input" | openssl dgst -sha256 2>/dev/null | sed 's/^.*=[[:space:]]*//')
    if [ -z "$_hash" ]; then
        log_err "SHA256 computation failed"
        return 1
    fi
    echo "$_hash"
}

# -------------------------------------------------------------------
# Check if an interface has a usable IP address
# -------------------------------------------------------------------
has_ip() {
    _iface="$1"
    ip addr show "$_iface" 2>/dev/null | grep -q 'inet [0-9]'
}

# -------------------------------------------------------------------
# Check if Ethernet cable is plugged in (carrier detected)
# -------------------------------------------------------------------
eth_has_link() {
    _carrier=$(cat "/sys/class/net/${ETH_IFACE}/carrier" 2>/dev/null)
    [ "$_carrier" = "1" ]
}

# -------------------------------------------------------------------
# Bring up WiFi
# -------------------------------------------------------------------
start_wifi() {
    if [ ! -f "$WIFI_CONF" ]; then
        log "no WiFi config found at ${WIFI_CONF}"
        return 1
    fi

    log "starting WiFi..."

    # Load WiFi driver
    modprobe brcmfmac 2>/dev/null || true
    sleep 2

    # Check interface appeared
    if [ ! -d "/sys/class/net/${WLAN_IFACE}" ]; then
        log_err "WiFi interface ${WLAN_IFACE} not found after loading driver"
        return 1
    fi

    # Bring interface up
    ip link set "$WLAN_IFACE" up 2>/dev/null || true
    sleep 1

    # Copy WiFi config to tmpfs (boot partition may be read-only)
    cp "$WIFI_CONF" /tmp/wpa-initramfs.conf 2>/dev/null || true
    chmod 600 /tmp/wpa-initramfs.conf

    # Start wpa_supplicant
    wpa_supplicant -B -i "$WLAN_IFACE" -c /tmp/wpa-initramfs.conf -P /tmp/wpa_supplicant.pid 2>/dev/null
    if [ -f /tmp/wpa_supplicant.pid ]; then
        WPA_PID=$(cat /tmp/wpa_supplicant.pid)
    fi

    # Wait for association (up to 15 seconds)
    _wifi_wait=0
    while [ "$_wifi_wait" -lt 15 ]; do
        if wpa_cli -i "$WLAN_IFACE" status 2>/dev/null | grep -q 'wpa_state=COMPLETED'; then
            log "WiFi associated"
            break
        fi
        sleep 1
        _wifi_wait=$(( _wifi_wait + 1 ))
    done

    if [ "$_wifi_wait" -ge 15 ]; then
        log_err "WiFi association timeout"
        return 1
    fi

    # Get IP via DHCP
    if command -v udhcpc >/dev/null 2>&1; then
        udhcpc -i "$WLAN_IFACE" -t 5 -T 3 -n -q 2>/dev/null
    elif command -v dhclient >/dev/null 2>&1; then
        dhclient -1 -timeout 15 "$WLAN_IFACE" 2>/dev/null
    else
        log_err "no DHCP client available"
        return 1
    fi

    sleep 1

    if has_ip "$WLAN_IFACE"; then
        log "WiFi IP acquired on ${WLAN_IFACE}"
        return 0
    else
        log_err "WiFi DHCP failed — no IP on ${WLAN_IFACE}"
        return 1
    fi
}

# -------------------------------------------------------------------
# Ensure we have network connectivity on some interface
# -------------------------------------------------------------------
ensure_network() {
    # Check Ethernet first
    if has_ip "$ETH_IFACE"; then
        log "Ethernet already has IP"
        return 0
    fi

    # If Ethernet has link but no IP, try DHCP on it
    if eth_has_link; then
        log "Ethernet link detected, requesting DHCP..."
        ip link set "$ETH_IFACE" up 2>/dev/null || true
        if command -v udhcpc >/dev/null 2>&1; then
            udhcpc -i "$ETH_IFACE" -t 5 -T 3 -n -q 2>/dev/null
        elif command -v dhclient >/dev/null 2>&1; then
            dhclient -1 -timeout 15 "$ETH_IFACE" 2>/dev/null
        fi
        sleep 1
        if has_ip "$ETH_IFACE"; then
            log "Ethernet IP acquired"
            return 0
        fi
    fi

    # Fall back to WiFi
    log "no Ethernet connectivity, trying WiFi..."
    if start_wifi; then
        return 0
    fi

    log_err "no network connectivity available"
    return 1
}

# -------------------------------------------------------------------
# Fetch LUKS key from waouw-admin (lot mode or device mode)
# -------------------------------------------------------------------
fetch_key_lot() {
    # Lot mode: use lot_id as identifier
    _lot_id="$1"
    TIMESTAMP=$(date +%s)

    BOOT_SECRET=$(sha256_hash "${_lot_id}${BOOT_SALT}") || return 1
    HMAC_SIG=$(hmac_sha256 "${TIMESTAMP}${_lot_id}" "$BOOT_SECRET") || return 1

    _payload="{\"action\":\"retrieve_lot\",\"lot_id\":\"${_lot_id}\"}"

    _response=$(curl \
        --silent --show-error --max-time 15 \
        --cacert "$CA_BUNDLE" \
        --header "Content-Type: application/json" \
        --header "X-Waouw-Boot-Hmac: ${HMAC_SIG}" \
        --header "X-Waouw-Timestamp: ${TIMESTAMP}" \
        --data "$_payload" \
        "$ADMIN_URL" 2>/dev/null)

    _curl_rc=$?
    if [ "$_curl_rc" -ne 0 ]; then
        log_err "curl failed (exit code ${_curl_rc})"
        return 1
    fi

    if echo "$_response" | grep -q '"error"'; then
        _errmsg=$(echo "$_response" | sed -n 's/.*"error"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p')
        log_err "server error (lot): ${_errmsg:-unknown}"
        return 1
    fi

    LUKS_KEY=$(echo "$_response" | sed -n 's/.*"luks_key"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p')
    [ -n "$LUKS_KEY" ] && [ ${#LUKS_KEY} -ge 32 ] && return 0

    log_err "no valid key in lot response"
    return 1
}

fetch_key_device() {
    # Device mode: use serial as identifier
    SERIAL=$(get_serial) || return 1
    DEVICE_ID=$(get_device_id) || return 1
    TIMESTAMP=$(date +%s)

    BOOT_SECRET=$(sha256_hash "${SERIAL}${BOOT_SALT}") || return 1
    HMAC_SIG=$(hmac_sha256 "${TIMESTAMP}${SERIAL}" "$BOOT_SECRET") || return 1

    _payload="{\"serial\":\"${SERIAL}\",\"device_id\":\"${DEVICE_ID}\"}"

    _response=$(curl \
        --silent --show-error --max-time 15 \
        --cacert "$CA_BUNDLE" \
        --header "Content-Type: application/json" \
        --header "X-Waouw-Boot-Hmac: ${HMAC_SIG}" \
        --header "X-Waouw-Timestamp: ${TIMESTAMP}" \
        --data "$_payload" \
        "$ADMIN_URL" 2>/dev/null)

    _curl_rc=$?
    if [ "$_curl_rc" -ne 0 ]; then
        log_err "curl failed (exit code ${_curl_rc})"
        return 1
    fi

    if echo "$_response" | grep -q '"error"'; then
        _errmsg=$(echo "$_response" | sed -n 's/.*"error"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p')
        log_err "server error (device): ${_errmsg:-unknown}"
        return 1
    fi

    LUKS_KEY=$(echo "$_response" | sed -n 's/.*"luks_key"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p')
    [ -n "$LUKS_KEY" ] && [ ${#LUKS_KEY} -ge 32 ] && return 0

    log_err "no valid key in device response"
    return 1
}

fetch_key() {
    # Try lot mode first (if lot ID file exists)
    LOT_ID=""
    if [ -f "$LOT_ID_FILE" ]; then
        LOT_ID=$(cat "$LOT_ID_FILE" 2>/dev/null | tr -d '\r\n ')
    fi

    if [ -n "$LOT_ID" ]; then
        log "lot mode: $LOT_ID"
        if fetch_key_lot "$LOT_ID"; then
            return 0
        fi
        log "lot fetch failed, trying device mode..."
    fi

    # Device mode
    fetch_key_device
}

# ===================================================================
# Main
# ===================================================================
log "starting LUKS key fetch..."

_attempt=0
_success=0

while [ "$_attempt" -lt "$MAX_ATTEMPTS" ]; do
    _attempt=$(( _attempt + 1 ))
    log "attempt ${_attempt}/${MAX_ATTEMPTS}"

    # Ensure network is up
    if ! ensure_network; then
        log "waiting ${RETRY_INTERVAL}s before retry..."
        sleep "$RETRY_INTERVAL"
        continue
    fi

    # Try to fetch the key
    if fetch_key; then
        _success=1
        break
    fi

    log "key fetch failed, waiting ${RETRY_INTERVAL}s before retry..."
    sleep "$RETRY_INTERVAL"
done

if [ "$_success" -eq 1 ]; then
    log "LUKS key obtained successfully"
    # Output the key on stdout for cryptsetup
    printf '%s' "$LUKS_KEY"
    # Clear from memory immediately
    unset LUKS_KEY
    exit 0
else
    log_err "FAILED to obtain LUKS key after ${MAX_ATTEMPTS} attempts ($(( MAX_ATTEMPTS * RETRY_INTERVAL ))s)"
    log_err "device will not boot — check network and admin server"
    exit 1
fi
