#!/bin/bash

set -euo pipefail

detect_nvme_device() {
    awk '/nvme.*n[0-9]+$/ {print "/dev/"$4; exit}' /proc/partitions
}

verify_connectivity() {
    local url="$1"

    echo >&2 "Verifying internet connectivity to $url"

    for attempt in {1..100}; do
        if wget --spider -T 2 "$url" 2>/dev/null; then
            echo >&2 "Internet connectivity verified"
            return 0
        fi

        echo >&2 "[$attempt/100] Connectivity check failed"

        sleep 2
    done

    echo >&2 "Error: No internet connectivity"
    echo >&2 "Please check network configuration and internet access"
    return 1
}

# Use provided device or auto-detect first NVMe device
if [ $# -eq 1 ]; then
    device="$1"
    echo >&2 "Using specified installation target: $device"
else
    device=$(detect_nvme_device)
    if [ -z "$device" ]; then
        echo >&2 "Error: No NVMe device found for auto-detection"
        echo >&2 "Usage: $0 [device]"
        echo >&2 "  device: target block device (auto-detects first NVMe if not specified)"
        exit 1
    fi
    echo >&2 "Auto-detected installation target: $device"
fi

# Verify device exists and is a block device
if [ ! -b "$device" ]; then
    echo >&2 "Error: $device is not a valid block device"
    exit 1
fi

# Extract version from kernel command line
version=$(awk 'BEGIN { RS=" "; FS="=" } /edgeos.version/ { print $2 }' < /proc/cmdline)
env=$(awk 'BEGIN { RS=" "; FS="=" } /edgeos.env/ { print $2 }' < /proc/cmdline)

if [ -z "$version" ]; then
    echo "Warning: edgeos.version not found in kernel cmdline, using 'latest'"
    version="latest"
fi

echo >&2 "Installing edgeos version: $version from $env"

# Construct versioned URL
if [ "$env" == "dev" ]; then
    artifacts=artifacts.nimbra.dev
    url="https://$artifacts/api/artifacts/edgeos/v1/edge-connect-image-dev/$version/edge-connect-image-dev-nimbra.rootfs.wic.zst"
else
    artifacts=artifacts.nimbra.io
    url="https://$artifacts/api/artifacts/edgeos/v1/edge-connect-image/$version/edge-connect-image-nimbra.rootfs.wic.zst"
fi

echo >&2 "Will download $url"

# Verify connectivity before attempting download
if ! verify_connectivity "https://$artifacts"; then
    exit 1
fi

wget "$url" --spider # Check if the file exists - uses HEAD
wget "$url" -O - | unzstd | dd of="${device}"

echo >&2 "Fixing partition table"
parted --script --fix "${device}"

echo >&2 "Configuring UEFI boot variable"
efibootmgr --delete-bootnum --label "Edge OS" || true
# This should set the boot order but does not seem to work, at least on a 414b
efibootmgr --create --disk "${device}" --part 1 --loader "\EFI\BOOT\BOOTX64.EFI" --label "Edge OS"
# setting bootnext does however
bootnum=$(efibootmgr | awk '/Edge OS/ { print substr($1, 5, 4) }')
efibootmgr --bootnext "$bootnum"
echo >&2 "installation done"
