#!/usr/bin/env bash
# ============================================================================
#  MVP OS 1.1 - bootable aarch64 live ISO builder (Kali-based)
#
#  Produces: mvpos-1.1-arm64.iso  (UEFI / GRUB / Linux kernel / systemd init /
#  BusyBox + coreutils / real sudo / real DHCP networking / apt package manager)
#
#  Run this on an x86_64 Linux host (WSL2/Ubuntu on a Windows PC, or a Ubuntu
#  VM in UTM on a Mac). The target is the same architecture as your PC, so it
#  is a native build - no cross toolchain.
#
#  Usage:  sudo ./build-mvpos.sh            # core build, amd64 ISO (~1.2 GB)
#          sudo TOOLS=full ./build-mvpos.sh # + kali-linux-core toolset
#          sudo ARCH=arm64 ./build-mvpos.sh # only on an aarch64 host
# ============================================================================
set -Eeuo pipefail

VERSION="1.1"
ARCH="${ARCH:-amd64}"
SUITE="${SUITE:-kali-rolling}"
MIRROR="${MIRROR:-http://http.kali.org/kali}"
TOOLS="${TOOLS:-core}"
USERNAME="${USERNAME:-kali}"
USERPASS="${USERPASS:-kali}"
ROOTPASS="${ROOTPASS:-toor}"
WORK="${WORK:-$PWD/mvpos-build}"
CHROOT="$WORK/chroot"
IMAGE="$WORK/image"
OUT="$PWD/mvpos-${VERSION}-${ARCH}.iso"

case "$ARCH" in
  arm64) EFI_NAME="BOOTAA64.EFI"; GRUB_TARGET="arm64-efi"; KERNEL_PKG="linux-image-arm64" ;;
  amd64) EFI_NAME="BOOTX64.EFI";  GRUB_TARGET="x86_64-efi"; KERNEL_PKG="linux-image-amd64" ;;
  *) echo "unsupported ARCH=$ARCH"; exit 1 ;;
esac

log() { printf '\n\033[1;34m[mvpos]\033[0m %s\n' "$*"; }
die() { printf '\n\033[1;31m[mvpos] ERROR:\033[0m %s\n' "$*" >&2; exit 1; }
[ "$(id -u)" -eq 0 ] || die "run as root (sudo $0)"

# ---------------------------------------------------------------------------
# 0. host dependencies
# ---------------------------------------------------------------------------
log "checking host tools"
need=()
for t in debootstrap mksquashfs xorriso grub-mkstandalone mkfs.vfat bsdtar curl chroot; do
  command -v "$t" >/dev/null 2>&1 || need+=("$t")
done
if [ ${#need[@]} -gt 0 ]; then
  echo "Missing: ${need[*]}"
  if command -v pacman >/dev/null 2>&1; then
    log "installing them with pacman"
    pacman -Sy --needed --noconfirm debootstrap squashfs-tools xorriso grub dosfstools \
      libarchive curl arch-install-scripts mtools
  elif command -v apt-get >/dev/null 2>&1; then
    apt-get update
    apt-get install -y debootstrap squashfs-tools xorriso grub-efi-${ARCH}-bin \
      grub-common dosfstools libarchive-tools curl mtools
  else
    die "install the missing tools manually, then re-run"
  fi
fi

trap 'umount -lf "$CHROOT/dev/pts" "$CHROOT/dev" "$CHROOT/proc" "$CHROOT/sys" "$CHROOT/run" 2>/dev/null || true' EXIT

rm -rf "$WORK"; mkdir -p "$CHROOT" "$IMAGE/live" "$IMAGE/boot/grub" "$IMAGE/EFI/BOOT"

# ---------------------------------------------------------------------------
# 1. Kali archive keyring (needed because the host is not Debian-based)
# ---------------------------------------------------------------------------
log "fetching kali-archive-keyring"
KEYDIR="$WORK/keyring"; mkdir -p "$KEYDIR"
KEYDEB=$(curl -fsSL "$MIRROR/pool/main/k/kali-archive-keyring/" \
  | grep -o 'kali-archive-keyring_[0-9._~a-z-]*_all\.deb' | sort -u | tail -n1) \
  || die "cannot reach mirror $MIRROR"
curl -fSL "$MIRROR/pool/main/k/kali-archive-keyring/$KEYDEB" -o "$KEYDIR/keyring.deb"
( cd "$KEYDIR" && bsdtar -xf keyring.deb && bsdtar -xf data.tar.* )
KEYRING="$KEYDIR/usr/share/keyrings/kali-archive-keyring.gpg"
[ -f "$KEYRING" ] || die "keyring extraction failed"

# ---------------------------------------------------------------------------
# 2. bootstrap the base system
# ---------------------------------------------------------------------------
log "debootstrap $SUITE/$ARCH (this takes a while)"
debootstrap --arch="$ARCH" --variant=minbase --keyring="$KEYRING" \
  --include=apt-utils,ca-certificates "$SUITE" "$CHROOT" "$MIRROR"

mount -t proc  proc  "$CHROOT/proc"
mount -t sysfs sys   "$CHROOT/sys"
mount --bind /dev    "$CHROOT/dev"
mount -t devpts pts  "$CHROOT/dev/pts"
mount -t tmpfs  tmp  "$CHROOT/run"
cp /etc/resolv.conf "$CHROOT/etc/resolv.conf"

# ---------------------------------------------------------------------------
# 3. configure the OS inside the chroot
# ---------------------------------------------------------------------------
log "configuring MVP OS $VERSION inside chroot"

cat > "$CHROOT/etc/apt/sources.list" <<EOF
deb $MIRROR $SUITE main contrib non-free non-free-firmware
EOF

PKGS_CORE="$KERNEL_PKG live-boot live-config live-config-systemd systemd-sysv \
dbus busybox coreutils util-linux bash bash-completion sudo \
network-manager iproute2 iputils-ping dnsutils curl wget openssh-client \
ca-certificates nano vim-tiny less man-db procps psmisc htop file tree git \
locales tzdata kmod firmware-linux-free apt-transport-https"

PKGS_FULL="kali-linux-core kali-defaults nmap net-tools tcpdump whois traceroute"

INSTALL="$PKGS_CORE"
[ "$TOOLS" = "full" ] && INSTALL="$PKGS_CORE $PKGS_FULL"

cat > "$CHROOT/root/setup.sh" <<CHROOTEOF
#!/bin/bash
set -Eeuo pipefail
export DEBIAN_FRONTEND=noninteractive LC_ALL=C

echo mvpos > /etc/hostname
cat > /etc/hosts <<EOF
127.0.0.1	localhost
127.0.1.1	mvpos
::1		localhost ip6-localhost ip6-loopback
EOF

apt-get update
apt-get install -y --no-install-recommends $INSTALL

# --- identity: MVP OS 1.1 -------------------------------------------------
cat > /etc/os-release <<EOF
PRETTY_NAME="MVP OS $VERSION"
NAME="MVP OS"
VERSION_ID="$VERSION"
VERSION="$VERSION (kali-rolling base)"
ID=mvpos
ID_LIKE="kali debian"
HOME_URL="https://mvpos.local/"
EOF
cat > /etc/issue <<EOF
MVP OS $VERSION \\n \\l

EOF
cat > /etc/motd <<EOF
 
  ###  MVP OS $VERSION  ###   bootloader + kernel + init + shell
  user: $USERNAME    root shell: sudo -i    network: nmtui / dhclient
 
EOF

# --- real users + real sudo ----------------------------------------------
echo "root:$ROOTPASS" | chpasswd
if ! id -u $USERNAME >/dev/null 2>&1; then
  useradd -m -s /bin/bash -G sudo,adm,cdrom,dip,plugdev,netdev $USERNAME
fi
echo "$USERNAME:$USERPASS" | chpasswd
install -d -m 0750 /etc/sudoers.d
echo "$USERNAME ALL=(ALL:ALL) ALL" > /etc/sudoers.d/10-mvpos
chmod 0440 /etc/sudoers.d/10-mvpos

# --- live session autologin on tty1 -------------------------------------
mkdir -p /etc/systemd/system/getty@tty1.service.d
cat > /etc/systemd/system/getty@tty1.service.d/autologin.conf <<EOF
[Service]
ExecStart=
ExecStart=-/sbin/agetty --autologin $USERNAME --noclear %I \\\$TERM
EOF

# --- networking: DHCP on every wired link, always on --------------------
systemctl enable NetworkManager
cat > /etc/NetworkManager/conf.d/10-mvpos.conf <<EOF
[main]
plugins=keyfile
[device]
wifi.scan-rand-mac-address=no
EOF
cat > /etc/systemd/network/20-wired.network <<EOF
[Match]
Type=ether
[Network]
DHCP=yes
EOF

echo 'en_US.UTF-8 UTF-8' > /etc/locale.gen
locale-gen || true

# initramfs with live-boot so the squashfs root is found on the ISO
update-initramfs -u -k all

apt-get clean
rm -rf /tmp/* /var/lib/apt/lists/* /var/tmp/*
CHROOTEOF

chmod +x "$CHROOT/root/setup.sh"
chroot "$CHROOT" /root/setup.sh
rm -f "$CHROOT/root/setup.sh"

# ---------------------------------------------------------------------------
# 4. kernel + initrd out, squashfs root in
# ---------------------------------------------------------------------------
log "extracting kernel + initrd"
cp "$(ls -1 "$CHROOT"/boot/vmlinuz-* | tail -n1)" "$IMAGE/live/vmlinuz"
cp "$(ls -1 "$CHROOT"/boot/initrd.img-* | tail -n1)" "$IMAGE/live/initrd.img"

log "squashing root filesystem"
umount -lf "$CHROOT/dev/pts" "$CHROOT/dev" "$CHROOT/proc" "$CHROOT/sys" "$CHROOT/run" 2>/dev/null || true
mksquashfs "$CHROOT" "$IMAGE/live/filesystem.squashfs" \
  -comp xz -noappend -e boot/vmlinuz-* boot/initrd.img-*

# ---------------------------------------------------------------------------
# 5. GRUB (UEFI) boot media
# ---------------------------------------------------------------------------
log "building GRUB $GRUB_TARGET boot image"
cat > "$IMAGE/boot/grub/grub.cfg" <<'EOF'
set default=0
set timeout=5
insmod all_video
menuentry "MVP OS 1.1  (live)" {
    linux /live/vmlinuz boot=live components quiet splash \
          username=kali hostname=mvpos net.ifnames=0
    initrd /live/initrd.img
}
menuentry "MVP OS 1.1  (verbose / rescue shell)" {
    linux /live/vmlinuz boot=live components username=kali hostname=mvpos \
          console=ttyAMA0 console=tty0
    initrd /live/initrd.img
}
EOF

cat > "$WORK/grub-embed.cfg" <<'EOF'
search --set=root --file /live/vmlinuz
set prefix=($root)/boot/grub
configfile /boot/grub/grub.cfg
EOF

grub-mkstandalone \
  --format="$GRUB_TARGET" \
  --output="$IMAGE/EFI/BOOT/$EFI_NAME" \
  --locales="" --fonts="" --themes="" \
  "boot/grub/grub.cfg=$WORK/grub-embed.cfg"

log "creating EFI El Torito image"
dd if=/dev/zero of="$IMAGE/boot/efiboot.img" bs=1M count=20 status=none
mkfs.vfat -n MVPOSEFI "$IMAGE/boot/efiboot.img" >/dev/null
mmd  -i "$IMAGE/boot/efiboot.img" ::/EFI ::/EFI/BOOT
mcopy -i "$IMAGE/boot/efiboot.img" "$IMAGE/EFI/BOOT/$EFI_NAME" "::/EFI/BOOT/$EFI_NAME"

# ---------------------------------------------------------------------------
# 6. master the ISO
# ---------------------------------------------------------------------------
log "mastering $OUT"
xorriso -as mkisofs \
  -iso-level 3 -full-iso9660-filenames \
  -volid "MVPOS_${VERSION}" \
  -e boot/efiboot.img -no-emul-boot \
  -append_partition 2 0xef "$IMAGE/boot/efiboot.img" \
  -output "$OUT" \
  "$IMAGE"

log "done -> $OUT  ($(du -h "$OUT" | cut -f1))"
cat <<EOF

Boot it (amd64 / UEFI):

  # Windows (WSL2) or any Linux x86_64 host - QEMU with OVMF:
  qemu-system-x86_64 -M q35 -m 2048 \\
    -bios /usr/share/OVMF/OVMF_CODE.fd \\
    -cdrom $OUT -nic user,model=virtio-net-pci

  # Mac - add the ISO as a boot device in UTM:
  #   New VM -> Virtualize -> Linux -> Boot ISO = $OUT
  #   Architecture: x86_64,  UEFI Boot: ON,  Network: Shared

  (On Debian/Ubuntu install OVMF first:  sudo apt install -y ovmf qemu-system-x86)
  (On Arch:  sudo pacman -S ovmf qemu-desktop)

Login: $USERNAME / $USERPASS      root shell: sudo -i      root pass: $ROOTPASS
Network check inside the OS: ip a && ping -c3 1.1.1.1 && apt update
EOF