#!/bin/bash
# ===============================================================
# ZahraOS Server Build Script (FIXED & SAFE VERSION)
# Base: Debian 13 (Trixie)
# Edition: Text Only Server Minimal
# Author: M Alhuda (QDEI Cloud / UNILAK)
# ===============================================================

set -euo pipefail

DISTRO_NAME="ZahraOS-Server-13"
WORKDIR="$HOME/zahraos-server-build"
CHROOT="$WORKDIR/chroot"
ISO="$WORKDIR/iso"
BRAND="$WORKDIR/branding"
CONFIG="$WORKDIR/config"

# === Fungsi bantu ===
check_root() {
  if [ "$EUID" -ne 0 ]; then
    echo "[!] Script harus dijalankan sebagai root (sudo)"
    exit 1
  fi
}

prepare_env() {
  echo "[*] Menyiapkan direktori kerja..."
  mkdir -p "$CHROOT" "$ISO/boot/grub" "$BRAND" "$CONFIG"
}

install_deps() {
  echo "[*] Memeriksa dependensi..."
  apt update -qq
  apt install -y debootstrap grub-pc-bin grub-efi-amd64-bin xorriso mtools rsync \
    debian-archive-keyring gnupg ca-certificates tar xz-utils || {
    echo "[!] Gagal memasang dependensi"; exit 1;
  }
}

create_configs() {
  echo "[*] Membuat file konfigurasi..."
  cat > "$CONFIG/sources.list" <<EOF
deb http://deb.debian.org/debian trixie main contrib non-free non-free-firmware
deb http://security.debian.org/debian-security trixie-security main contrib non-free non-free-firmware
deb http://deb.debian.org/debian trixie-updates main contrib non-free non-free-firmware
EOF

  cat > "$CONFIG/interfaces" <<EOF
auto lo
iface lo inet loopback

allow-hotplug eth0
iface eth0 inet dhcp
EOF

  cat > "$CONFIG/user_setup.sh" <<'EOF'
#!/bin/bash
echo "[*] Menambahkan user admin..."
useradd -m -s /bin/bash admin
echo "admin:admin" | chpasswd
adduser admin sudo
systemctl enable ssh
EOF
  chmod +x "$CONFIG/user_setup.sh"
}

create_branding() {
  echo "[*] Membuat file branding..."
  cat > "$BRAND/os-release" <<EOF
NAME="ZahraOS Server"
VERSION="13 (Trixie)"
ID=zahraos
PRETTY_NAME="ZahraOS Server 13 (Debian Trixie Base)"
HOME_URL="https://anycast.id"
SUPPORT_URL="https://qdei.cloud"
EOF

  cat > "$BRAND/issue" <<EOF
Welcome to ZahraOS Server (Debian 13)
Powered by QDEI Cloud – Universitas Lancang Kuning
EOF

  cat > "$BRAND/motd" <<'EOF'
===========================================================
 🌸 ZahraOS Server (Debian 13 Trixie)
 🖥️  Managed by QDEI Cloud | Faculty of Computer Science UNILAK
 🔗  https://qdei.cloud  |  https://anycast.id
===========================================================
EOF

  cat > "$BRAND/grub.cfg" <<EOF
set default=0
set timeout=5

menuentry "ZahraOS Server (Debian 13 Trixie Minimal)" {
    linux /boot/vmlinuz boot=live quiet
    initrd /boot/initrd.img
}
EOF
}

bootstrap_system() {
  echo "[*] Menjalankan debootstrap Debian Trixie..."
  if ! debootstrap --arch=amd64 --variant=minbase --no-check-gpg \
    --keyring=/usr/share/keyrings/debian-archive-keyring.gpg \
    trixie "$CHROOT" http://kartolo.sby.datautama.net.id/debian; then
      echo "[!] Bootstrap mirror lokal gagal, mencoba mirror utama..."
      debootstrap --arch=amd64 --variant=minbase --no-check-gpg \
        --keyring=/usr/share/keyrings/debian-archive-keyring.gpg \
        trixie "$CHROOT" http://deb.debian.org/debian
  fi

  # Pastikan struktur direktori penting
  install -d "$CHROOT/etc/network" "$CHROOT/etc/apt" "$CHROOT/root"
}

copy_configs() {
  echo "[*] Menyalin konfigurasi ke chroot..."
  install -Dm644 "$CONFIG/sources.list" "$CHROOT/etc/apt/sources.list"
  install -Dm644 "$CONFIG/interfaces" "$CHROOT/etc/network/interfaces"
  install -Dm755 "$CONFIG/user_setup.sh" "$CHROOT/root/user_setup.sh"
}

install_base_packages() {
  echo "[*] Memasuki chroot dan memasang paket dasar..."
  chroot "$CHROOT" bash -c "
set -eux
export DEBIAN_FRONTEND=noninteractive
apt update
apt install --no-install-recommends -y linux-image-amd64 grub-pc systemd-sysv \
  openssh-server sudo net-tools iproute2 iputils-ping vim nano less ca-certificates locales rsyslog
bash /root/user_setup.sh
apt clean
"
}

apply_branding() {
  echo "[*] Menerapkan branding ZahraOS..."
  install -Dm644 "$BRAND/os-release" "$CHROOT/etc/os-release"
  install -Dm644 "$BRAND/issue" "$CHROOT/etc/issue"
  install -Dm644 "$BRAND/motd" "$CHROOT/etc/motd"
}

build_iso() {
  echo "[*] Menyiapkan kernel dan GRUB..."
  cp "$CHROOT/boot/vmlinuz-"* "$ISO/boot/vmlinuz"
  cp "$CHROOT/boot/initrd.img-"* "$ISO/boot/initrd.img"
  cp "$BRAND/grub.cfg" "$ISO/boot/grub/grub.cfg"

  echo "[*] Membuat ISO bootable..."
  grub-mkrescue -o "$WORKDIR/${DISTRO_NAME}.iso" "$ISO" --compress=xz
}

# === Eksekusi Utama ===
check_root
prepare_env
install_deps
create_configs
create_branding
bootstrap_system
copy_configs
install_base_packages
apply_branding
build_iso

echo "=============================================================="
echo "✅ Build selesai!"
echo "📁 File ISO: $WORKDIR/${DISTRO_NAME}.iso"
echo "👤 Login Default: admin / admin"
echo "=============================================================="

