#!/bin/bash
# preflight-scan.sh — fase 1 dari 3. TIDAK mengubah apapun di target.
#
# Tujuan: sebelum menyentuh disk, pastikan 3 hal yang paling sering bikin
# instalasi Windows di VPS berakhir "hidup tapi tidak bisa dihubungi":
#
#   1. spek cukup (RAM / disk / firmware / disk driver)
#   2. edge firewall sudah membuka port yang dibutuhkan (bukan ufw — Tencent
#      Lighthouse punya firewall di level produk yang tidak terlihat dari OS)
#   3. IP publik + gateway + prefix BENAR — dicatat ke berkas supaya fase 3
#      (netfix) tidak perlu menebak. Ini akar bug DHCP-provider: trans.sh
#      hanya menulis config jaringan kalau source system static IP.
#
# Output: /root/net-backup/network.txt  (dipakai install-windows.sh stage 2)
# Exit 0 = layak lanjut. Exit 1 = ada blocker yang harus dibereskan dulu.
#
# Usage (di target, sebagai root):
#   bash preflight-scan.sh [--fix-firewall] [--region ap-singapore] [--instance-id lhins-xxx]

set -uo pipefail

FIX_FW=0
REGION="${REGION:-ap-singapore}"
INSTANCE_ID="${INSTANCE_ID:-}"

while [ $# -gt 0 ]; do
    case "$1" in
        --fix-firewall) FIX_FW=1; shift ;;
        --region)       REGION=$2; shift 2 ;;
        --instance-id)  INSTANCE_ID=$2; shift 2 ;;
        *) echo "unknown arg: $1" >&2; exit 2 ;;
    esac
done

log()  { echo -e "\033[1;36m[scan]\033[0m $*"; }
ok()   { echo -e "\033[1;32m[ ok ]\033[0m $*"; }
warn() { echo -e "\033[1;33m[warn]\033[0m $*"; }
bad()  { echo -e "\033[1;31m[FAIL]\033[0m $*"; }
die()  { echo -e "\033[1;31m[FATAL]\033[0m $*" >&2; exit 1; }

BLOCKERS=0
WARNINGS=0

[ "$(id -u)" = 0 ] || die "harus root"

echo "=========================================================="
echo " FASE 1 — PREFLIGHT SCAN"
echo "=========================================================="

# ------------------------------------------------------------------ 1. HARDWARE
log "memeriksa hardware"

RAM_MB=$(awk '/MemTotal/{printf "%d", $2/1024}' /proc/meminfo)
DISK_GB=$(df -BG --output=avail / | tail -1 | tr -dc '0-9')
DISK_TOTAL_GB=$(df -BG --output=size / | tail -1 | tr -dc '0-9')
CPU=$(nproc)

echo "  CPU      : ${CPU} vCPU"
echo "  RAM      : ${RAM_MB} MB"
echo "  Disk     : ${DISK_TOTAL_GB} GB total, ${DISK_GB} GB free"
echo "  Firmware : $([ -d /sys/firmware/efi ] && echo UEFI || echo BIOS)"

[ "$RAM_MB" -ge 1800 ] || { bad "RAM < 1.8 GB — Windows 10 tidak akan nyaman, RDP akan OOM"; BLOCKERS=$((BLOCKERS+1)); }
[ "$DISK_TOTAL_GB" -ge 32 ] || { bad "disk < 32 GB — tidak cukup untuk Windows + updates"; BLOCKERS=$((BLOCKERS+1)); }
[ "$DISK_GB" -ge 8 ] || { bad "free space < 8 GB"; BLOCKERS=$((BLOCKERS+1)); }

# disk driver: virtio butuh viostor/vioscsi di dalam image, kalau tidak
# Windows Setup tidak akan melihat disk sama sekali (INACCESSIBLE_BOOT_DEVICE)
VIRTIO=0
DISK_NAME=$(lsblk -no NAME,TYPE 2>/dev/null | awk '$2=="disk"{print $1; exit}')
[ -n "$DISK_NAME" ] && VIRTIO=$(lsblk -o NAME,TRAN 2>/dev/null | grep -c virtio || true)
if [ "$VIRTIO" -gt 0 ]; then
    ok "disk virtio terdeteksi (driver wajib ada di image)"
else
    log "disk non-virtio (driver bawaan Windows cukup)"
fi

VENDOR=$(cat /sys/devices/virtual/dmi/id/sys_vendor 2>/dev/null || echo unknown)
echo "  Vendor   : $VENDOR"

# nested KVM: kalau ada, opsi lain terbuka; kalau tidak, reinstall.sh satu-satunya jalur
NESTED=$(grep -oE '(vmx|svm)' /proc/cpuinfo 2>/dev/null | sort -u | tr '\n' ' ')
if [ -n "$NESTED" ]; then
    ok "nested KVM tersedia ($NESTED)"
else
    log "tidak ada nested KVM (normal di cloud VPS) -> reinstall.sh jalur yang benar"
fi

# --------------------------------------------------------------- 2. JARINGAN
log "merekam konfigurasi jaringan"

IFACE=$(ip route 2>/dev/null | awk '/^default/{print $5; exit}')
[ -n "$IFACE" ] || die "tidak ada default route — jaringan rusak, perbaiki dulu"

CIDR=$(ip -4 -o addr show dev "$IFACE" | awk '{print $4}' | head -1)
[ -n "$CIDR" ] || die "tidak ada IPv4 di $IFACE"

IP=${CIDR%%/*}
PREFIX=${CIDR##*/}
GW=$(ip route | awk '/^default/{print $3; exit}')
MAC=$(cat "/sys/class/net/$IFACE/address" 2>/dev/null || echo "")

echo "  iface    : $IFACE"
echo "  ip       : $IP/$PREFIX"
echo "  gateway  : $GW"
echo "  mac      : $MAC"

# gateway harus di dalam subnet, kalau tidak Windows akan menolak config-nya
# diam-diam (persis kegagalan yang bikin RDP tidak pernah terbuka)
if command -v python3 >/dev/null 2>&1; then
    if python3 - "$IP" "$PREFIX" "$GW" <<'PY' 2>/dev/null
import ipaddress, sys
net = ipaddress.ip_network(f"{sys.argv[1]}/{sys.argv[2]}", strict=False)
sys.exit(0 if ipaddress.ip_address(sys.argv[3]) in net else 1)
PY
    then ok "gateway $GW di dalam $IP/$PREFIX"
    else bad "gateway $GW DI LUAR subnet $IP/$PREFIX — Windows akan menolak IP ini"; BLOCKERS=$((BLOCKERS+1))
    fi
else
    warn "python3 tidak ada, validasi gateway dilewati"
fi

ping -c1 -W3 "$GW" >/dev/null 2>&1 && ok "gateway merespon ping" || warn "gateway tidak merespon ping (bisa jadi ICMP diblok, belum tentu masalah)"

# IP publik: pastikan yang kita rekam memang IP publik, bukan private
case "$IP" in
    10.*|192.168.*|172.1[6-9].*|172.2[0-9].*|172.3[0-1].*)
        warn "$IP adalah IP privat — VPS pakai NAT, IP publik dipetakan di edge"
        NAT=1 ;;
    *) ok "$IP adalah IP publik"; NAT=0 ;;
esac

# ---- CRITICAL: on a NAT box the guest MUST keep its private address ----------
# Tencent Lighthouse (and most NAT'd clouds) do 1:1 static NAT at the edge. The
# public IP is NOT configured inside the guest — if you push the public IP onto
# the NIC, the guest ends up with an address it does not own and the return
# path breaks completely (no ping, no RDP, nothing).
#
# So: the address we inject into Windows is ALWAYS the one the NIC actually has.
# On a NAT host that is the private one, and RDP still works from outside
# because the edge translates it. Getting this backwards is silent death.
WINDOWS_IP="$IP"
if [ "$NAT" = 1 ]; then
    ok "alamat yang di-inject = $IP (privat) — benar untuk host NAT"
    log "IP publik tetap dilayani edge; JANGAN pasang IP publik di NIC"
fi

# DNS yang benar-benar dipakai
DNS_LIST=$(awk '/^nameserver/{print $2}' /etc/resolv.conf 2>/dev/null | grep -vE '^(127\.|::1)' | head -2 | tr '\n' ' ')
[ -n "$DNS_LIST" ] || DNS_LIST="183.60.83.19 8.8.8.8"
echo "  dns      : $DNS_LIST"

# simpan — fase 3 membaca berkas ini, tidak menebak
mkdir -p /root/net-backup /dev/netconf/$IFACE
{
  echo "IP=$IP"
  echo "PREFIX=$PREFIX"
  echo "GW=$GW"
  echo "MAC=$MAC"
  echo "IFACE=$IFACE"
  echo "NAT=$NAT"
  echo "WINDOWS_IP=$WINDOWS_IP"
  echo "PUBLIC_IP=${PUBLIC_IP:-}"
  set -- $DNS_LIST
  echo "DNS1=${1:-183.60.83.19}"
  echo "DNS2=${2:-8.8.8.8}"
} > /root/net-backup/network.txt
ok "konfigurasi disimpan ke /root/net-backup/network.txt"

# juga tulis ke /dev/netconf supaya netfix-inject.sh bisa autodetect
# (format yang sama dengan yang dibaca trans.sh)
echo "$CIDR"   > "/dev/netconf/$IFACE/ipv4_addr"
echo "$GW"     > "/dev/netconf/$IFACE/ipv4_gateway"
echo "$MAC"    > "/dev/netconf/$IFACE/mac_addr"
ok "konfigurasi dicatat di /dev/netconf/$IFACE (autodetect fase 3)"

# pastikan IP publik memang sampai ke mesin ini, bukan CGNAT
if [ "$NAT" = 0 ]; then
    PUB_CHECK=$(curl -s --max-time 8 https://api.ipify.org 2>/dev/null || echo "")
    if [ -n "$PUB_CHECK" ]; then
        if [ "$PUB_CHECK" = "$IP" ]; then ok "IP publik keluar = $PUB_CHECK (cocok)"
        else warn "IP keluar = $PUB_CHECK, beda dengan NIC $IP (NAT/弹性IP, dicatat)"; fi
    else
        warn "tidak bisa cek IP keluar (egress HTTPS diblok atau DNS mati)"
    fi
fi

# ------------------------------------------------------------- 3. FIREWALL
log "memeriksa firewall edge"
echo "  catatan: firewall Tencent Lighthouse ada di level PRODUK."
echo "           ufw/iptables di dalam OS tidak relevan untuk port publik."

if command -v ufw >/dev/null 2>&1 && ufw status 2>/dev/null | grep -q "Status: active"; then
    warn "ufw aktif — setelah jadi Windows, ini hilang, tapi pastikan tidak blokir egress"
    ufw status numbered 2>/dev/null | head -15
else
    ok "ufw tidak aktif (tidak akan mengganggu)"
fi

NEED_PORTS="3389 22 80 443"
if command -v tccli >/dev/null 2>&1 && [ -n "$INSTANCE_ID" ]; then
    log "membaca firewall Lighthouse via API (instance $INSTANCE_ID)"
    FW=$(tccli lighthouse DescribeFirewallRules --region "$REGION" --InstanceId "$INSTANCE_ID" 2>/dev/null)
    if [ -n "$FW" ]; then
        echo "$FW" | python3 -c '
import json,sys
d=json.load(sys.stdin)
print("  FirewallVersion:", d.get("FirewallVersion"))
rules=d.get("FirewallRuleSet",[])
open_ports=set()
for r in rules:
    if r.get("Action")=="ACCEPT":
        open_ports.add(str(r.get("Port")))
        print(f"    {r.get(\"Protocol\"):4} {str(r.get(\"Port\")):8} {r.get(\"CidrBlock\")}")
missing=[p for p in ["3389"] if p not in open_ports and "ALL" not in open_ports]
if missing: print("MISSING:"+",".join(missing))
' > /tmp/fwcheck.txt 2>/dev/null
        cat /tmp/fwcheck.txt
        if grep -q '^MISSING:' /tmp/fwcheck.txt; then
            MISS=$(grep '^MISSING:' /tmp/fwcheck.txt | cut -d: -f2)
            if [ "$FIX_FW" = 1 ]; then
                log "membuka port $MISS via API"
                python3 - "$MISS" > /tmp/fwrules.json <<'PY'
import json,sys
ports=sys.argv[1].split(",")
rules=[]
for p in ports:
    rules.append({"Protocol":"TCP","Port":p,"CidrBlock":"0.0.0.0/0","Action":"ACCEPT","FirewallRuleDescription":"auto preflight"})
print(json.dumps(rules))
PY
                tccli lighthouse CreateFirewallRules --region "$REGION" --InstanceId "$INSTANCE_ID" \
                    --FirewallRules "$(cat /tmp/fwrules.json)" 2>&1 | head -5
                sleep 3
                tccli lighthouse DescribeFirewallRules --region "$REGION" --InstanceId "$INSTANCE_ID" \
                    --query 'FirewallRuleSet[?Port==`3389`]' 2>/dev/null | head -8
                ok "port $MISS dibuka"
            else
                bad "port $MISS TERTUTUP di edge firewall — jalankan ulang dengan --fix-firewall"; BLOCKERS=$((BLOCKERS+1))
            fi
        else
            ok "3389 sudah terbuka di edge firewall"
        fi
    else
        warn "tccli tidak bisa baca firewall (credential/region?) — cek manual di panel"
    fi
else
    warn "tccli tidak ada atau --instance-id kosong — firewall TIDAK diverifikasi"
    warn "buka manual: panel Lighthouse > Firewall > TCP 3389 dari 0.0.0.0/0"
fi

# ------------------------------------------------------------------ RINGKASAN
echo
echo "=========================================================="
if [ "$BLOCKERS" -gt 0 ]; then
    bad "$BLOCKERS BLOCKER — perbaiki dulu sebelum install"
    echo
    echo "Setelah beres, ulangi fase 1. JANGAN lanjut ke fase 2"
    echo "selama masih ada BLOCKER: install akan jalan lalu Windows"
    echo "boot tanpa IP seperti kejadian sebelumnya."
    exit 1
fi

ok "LAYAK INSTALL — tidak ada blocker"
echo
echo "Lanjut fase 2:"
echo "  bash install-windows.sh --iso <URL> --image \"<NAMA EDITION>\""
echo
exit 0
