#!/bin/bash
set -e

# AeThex OS - Unikernel Build Script (OPS)
# Requires 'ops' (https://ops.city)

echo "═══════════════════════════════════════════════════════════════"
echo "  AeThex OS - Unikernel Builder"
echo "  Target: Nanos Unikernel (Bootable Image)"
echo "═══════════════════════════════════════════════════════════════"

# 0. Check for MinGW/Git Bash (Windows NPM environment)
if [ -n "$MSYSTEM" ] || [[ "$OSTYPE" == "msys" ]] || [[ "$OSTYPE" == "cygwin" ]]; then
    echo "[*] Detected Windows Environment (MinGW/Git Bash)."
    echo "[*] Switching to WSL Context..."
    
    # Convert the current script path to a WSL path
    # $0 is likely "script/build-unikernel.sh"
    # We assume the current directory is the project root in Windows format, accessible via /mnt/c
    
    # Simple re-execution in WSL, assuming we are at project root
    wsl bash script/build-unikernel.sh
    exit $?
fi

# Try to find 'ops' in various ways
OPS_CMD=""

# 1. Check if 'ops' is already in PATH
if command -v ops &> /dev/null; then
    OPS_CMD="ops"
fi

# 2. Hardcoded check for known user 'mrpiglr' (The specific fix)
if [ -z "$OPS_CMD" ]; then
    if [ -f "/home/mrpiglr/.ops/bin/ops" ]; then
        OPS_CMD="/home/mrpiglr/.ops/bin/ops"
    fi
fi

# 3. Check current user's Linux home
if [ -z "$OPS_CMD" ]; then
    LINUX_USER=$(whoami)
    if [ -f "/home/$LINUX_USER/.ops/bin/ops" ]; then
        OPS_CMD="/home/$LINUX_USER/.ops/bin/ops"
    fi
fi

# 4. Final check
if [ -z "$OPS_CMD" ]; then
    echo "[!] OPS binary not found."
    echo "    Checked: PATH, /home/mrpiglr/.ops/bin/ops"
    echo "    Please run this command directly in your WSL terminal:"
    echo "       export PATH=\$PATH:\$HOME/.ops/bin"
    echo "       bash script/build-unikernel.sh"
    exit 1
fi

echo "[*] Using OPS binary: $OPS_CMD"

if [ ! -d "dist" ]; then
    echo "[!] 'dist' directory not found. Building project..."
    npm run build
fi

echo "[*] Updating OPS package list..."
$OPS_CMD update

echo "[*] Building Unikernel Image..."

# Try fully qualified name format: account/package:version
PACKAGE="eyberg/node:v18.12.1"

echo "    Running: $OPS_CMD pkg load $PACKAGE ..."
if ! $OPS_CMD pkg load $PACKAGE -c ops.json -i aethex-kernel-v1; then
    echo "[!] $PACKAGE failed."
    
    # Fallback to another format seen in the list
    PACKAGE="eyberg/node:20.5.0"
    echo "    Trying fallback: $PACKAGE ..."
    $OPS_CMD pkg load $PACKAGE -c ops.json -i aethex-kernel-v1
fi

echo ""
echo "[✓] Build Complete."
echo "    Image: ~/.ops/images/aethex-kernel-v1"
echo ""
echo "To boot the kernel:"
echo "    $OPS_CMD run aethex-kernel-v1"
echo ""
echo "To deploy to AWS/GCP:"
echo "    $OPS_CMD image create -c ops.json -i aethex-kernel-v1 -t aws"
