#!/usr/bin/env bash
# ============================================================
# Hermes Bundle Downloader — jalankan di VPS BARU
# Download 5 split dari ac.hyukii.my.id, gabung, extract, install
# ============================================================
set -e
BASE="https://ac.hyukii.my.id"
WORK="${1:-/root}"
SPLITS=00 01 02 03 04

echo "╔════════════════════════════════════════════════╗"
echo "║  HERMES BUNDLE DOWNLOADER                      ║"
echo "║  Source: $BASE"
echo "║  Target: $WORK"
echo "╚════════════════════════════════════════════════╝"

mkdir -p "$WORK"
cd "$WORK"

echo ""
echo "[1/5] Download split files (500MB each, resume-supported)..."
for i in "${SPLITS[@]}"; do
    F="hermes_bundle_full.tar.gz.$i"
    if [ -f "$F" ] && [ "$(stat -c%s "$F")" -eq 524288000 ]; then
        echo "  $F sudah lengkap, skip"
        continue
    fi
    echo "  downloading $F ..."
    curl -fL --retry 5 --retry-delay 3 -C - -o "$F" "$BASE/splits/$F"
done

echo ""
echo "[2/5] Verify ukuran split..."
EXPECT_00=524288000
for i in "${SPLITS[@]}"; do
    F="hermes_bundle_full.tar.gz.$i"
    if [ ! -f "$F" ]; then echo "  MISSING: $F"; exit 1; fi
    SZ=$(stat -c%s "$F")
    echo "  $F = $SZ bytes"
done

echo ""
echo "[3/5] Gabung jadi satu archive..."
cat hermes_bundle_full.tar.gz.* > hermes_bundle_full.tar.gz
ls -lh hermes_bundle_full.tar.gz

echo ""
echo "[4/5] Extract..."
rm -rf hermes_bundle
tar xzf hermes_bundle_full.tar.gz
ls -la hermes_bundle/

echo ""
echo "[5/5] Jalankan installer..."
cd hermes_bundle
bash install.sh

echo ""
echo "╔════════════════════════════════════════════════╗"
echo "║  SELESAI — Hermes terpasang                    ║"
echo "╚════════════════════════════════════════════════╝"
echo ""
echo "Bersihkan file download (opsional):"
echo "  cd $WORK && rm -f hermes_bundle_full.tar.gz* && rm -rf hermes_bundle"
echo ""
echo "Start gateway:"
echo "  export PATH=/root/bin:\$PATH"
echo "  systemctl --user enable --now hermes-gateway"
