#!/bin/bash
# deploy-bios.sh - Deploy BIOS update files to a running PXE server
# Copies Flash64W.exe, BIOS binaries, models.txt, and check-bios.cmd
#
# Usage: ./deploy-bios.sh [server-ip]
#   Default server: 10.9.100.1

set -e

REPO_ROOT="$(cd "$(dirname "$0")"/.. && pwd)"
PXE_SERVER="${1:-10.9.100.1}"
PXE_USER="pxe"
PXE_PASS="pxe"
REMOTE_DIR="/srv/samba/enrollment/BIOS"
BIOS_DIR="$REPO_ROOT/bios-staging"
MANIFEST="$REPO_ROOT/playbook/shopfloor-setup/BIOS/models.txt"
CHECK_SCRIPT="$REPO_ROOT/playbook/shopfloor-setup/BIOS/check-bios.cmd"

SSH="sshpass -p $PXE_PASS ssh -o StrictHostKeyChecking=no -o ConnectTimeout=10 $PXE_USER@$PXE_SERVER"
SCP="sshpass -p $PXE_PASS scp -o StrictHostKeyChecking=no -o ConnectTimeout=10"

# Verify sources exist
if [ ! -d "$BIOS_DIR" ] || [ -z "$(ls -A "$BIOS_DIR" 2>/dev/null)" ]; then
    echo "ERROR: bios-staging/ is empty or missing. Run ./pull-bios.sh first."
    exit 1
fi

if [ ! -f "$MANIFEST" ]; then
    echo "ERROR: playbook/shopfloor-setup/BIOS/models.txt not found."
    exit 1
fi

echo "Deploying BIOS files to $PXE_SERVER..."

# Create remote directory
$SSH "sudo mkdir -p '$REMOTE_DIR' && sudo chown $PXE_USER:$PXE_USER '$REMOTE_DIR'"

# Copy check-bios.cmd and models.txt
echo "  Copying check-bios.cmd + models.txt..."
$SCP "$CHECK_SCRIPT" "$MANIFEST" "$PXE_USER@$PXE_SERVER:$REMOTE_DIR/"

# Copy BIOS binaries
COUNT=$(find "$BIOS_DIR" -name '*.exe' | wc -l)
SIZE=$(du -sh "$BIOS_DIR" | cut -f1)
echo "  Copying $COUNT BIOS binaries ($SIZE)..."
$SCP "$BIOS_DIR"/*.exe "$PXE_USER@$PXE_SERVER:$REMOTE_DIR/"

# Verify
REMOTE_COUNT=$($SSH "find '$REMOTE_DIR' -name '*.exe' | wc -l")
echo "Done: $REMOTE_COUNT files on $PXE_SERVER:$REMOTE_DIR"
