#!/usr/bin/env bash
# quantumunix-bootstrap.sh
# Reference bootstrap for QuantumUnix on top of Omarchy / Arch Linux.
#
# Author: Dr. Sarunas Grigaliunas
# License: MIT
# Source: https://github.com/quantumunix/quantumunix
#
# Profiles:
#   layer  -- apply QuantumUnix privacy/PQC layer onto an existing Omarchy install
#   full   -- partition target disk, install Arch + Omarchy + QuantumUnix from a live ISO
#
# This script is intentionally minimal and readable. Read it before running it as root.

set -Eeuo pipefail

QU_VERSION="0.1.0"
QU_REPO_URL="https://github.com/quantumunix/quantumunix"
QU_PROFILE_REPO="https://raw.githubusercontent.com/quantumunix/quantumunix/main"
QU_LOG="/var/log/quantumunix-bootstrap.log"

PROFILE=""
DISK=""
HOSTNAME_NEW="quantumunix"
USERNAME=""
CRYPTO_PROFILE="hybrid"
ASSUME_YES=0

log()  { printf '[qu] %s\n' "$*" | tee -a "${QU_LOG}" >&2; }
die()  { printf '[qu:error] %s\n' "$*" >&2; exit 1; }
need() { command -v "$1" >/dev/null 2>&1 || die "missing required command: $1"; }

usage() {
  cat <<USAGE
QuantumUnix bootstrap v${QU_VERSION}

Usage:
  $0 --profile layer
  $0 --profile full --disk /dev/nvmeXn1 --user NAME [--hostname H] [--crypto hybrid|pq-strict]

Options:
  --profile <layer|full>   install profile (required)
  --disk <device>          target block device for 'full' profile (e.g. /dev/nvme0n1)
  --hostname <name>        system hostname (default: quantumunix)
  --user <name>            primary username for 'full' profile
  --crypto <name>          crypto profile: hybrid (default) or pq-strict
  -y, --yes                assume "yes" for non-destructive prompts
  -h, --help               show this help
USAGE
}

parse_args() {
  while [[ $# -gt 0 ]]; do
    case "$1" in
      --profile)   PROFILE="${2:-}"; shift 2 ;;
      --disk)      DISK="${2:-}"; shift 2 ;;
      --hostname)  HOSTNAME_NEW="${2:-}"; shift 2 ;;
      --user)      USERNAME="${2:-}"; shift 2 ;;
      --crypto)    CRYPTO_PROFILE="${2:-}"; shift 2 ;;
      -y|--yes)    ASSUME_YES=1; shift ;;
      -h|--help)   usage; exit 0 ;;
      *)           die "unknown argument: $1" ;;
    esac
  done

  [[ -n "${PROFILE}" ]] || { usage; die "missing --profile"; }
  case "${PROFILE}" in layer|full) ;; *) die "invalid profile: ${PROFILE}";; esac
  case "${CRYPTO_PROFILE}" in hybrid|pq-strict) ;; *) die "invalid --crypto: ${CRYPTO_PROFILE}";; esac
}

require_root() {
  [[ ${EUID} -eq 0 ]] || die "this script must run as root (use sudo)"
}

require_arch_like() {
  [[ -f /etc/arch-release || -f /etc/omarchy-release ]] \
    || die "this looks like a non-Arch system. QuantumUnix targets Arch / Omarchy."
}

confirm() {
  local prompt="$1"
  if [[ ${ASSUME_YES} -eq 1 ]]; then return 0; fi
  read -r -p "${prompt} [y/N] " ans
  [[ "${ans,,}" == "y" || "${ans,,}" == "yes" ]]
}

network_check() {
  log "checking network..."
  curl -fsI --max-time 8 https://archlinux.org/ >/dev/null \
    || die "no working HTTPS network. Connect first (iwctl / dhcp), then retry."
}

install_packages() {
  log "synchronising and installing core packages..."
  pacman -Syu --noconfirm
  pacman -S --needed --noconfirm \
    base base-devel git curl ca-certificates \
    openssh openssl gnupg \
    apparmor audit \
    nftables iptables-nft \
    age sbctl \
    python python-pip
}

apply_quantumunix_layer() {
  log "applying QuantumUnix privacy + crypto policy layer..."
  install -d -m 0755 /etc/quantumunix /etc/quantumunix/profiles.d /var/lib/quantumunix

  cat > /etc/quantumunix/quantumunix.conf <<CONF
# QuantumUnix profile
QU_VERSION=${QU_VERSION}
QU_PROFILE=${PROFILE}
QU_CRYPTO_PROFILE=${CRYPTO_PROFILE}
QU_INSTALLED_AT=$(date -u +%FT%TZ)
CONF

  log "enabling baseline hardening services..."
  systemctl enable --now apparmor.service auditd.service nftables.service || true

  log "writing baseline DNS over TLS / privacy resolver config..."
  cat > /etc/systemd/resolved.conf.d/quantumunix.conf <<'CONF'
[Resolve]
DNS=9.9.9.9#dns.quad9.net 149.112.112.112#dns.quad9.net
DNSOverTLS=yes
DNSSEC=allow-downgrade
ReadEtcHosts=yes
CONF
  systemctl restart systemd-resolved.service || true

  log "writing SSH crypto policy (${CRYPTO_PROFILE})..."
  if [[ "${CRYPTO_PROFILE}" == "pq-strict" ]]; then
    cat > /etc/ssh/sshd_config.d/10-quantumunix.conf <<'CONF'
KexAlgorithms mlkem768x25519-sha256
HostKeyAlgorithms ssh-ed25519,sk-ssh-ed25519@openssh.com
PubkeyAcceptedAlgorithms ssh-ed25519,sk-ssh-ed25519@openssh.com
CONF
  else
    cat > /etc/ssh/sshd_config.d/10-quantumunix.conf <<'CONF'
KexAlgorithms mlkem768x25519-sha256,curve25519-sha256,curve25519-sha256@libssh.org
HostKeyAlgorithms ssh-ed25519,rsa-sha2-512,sk-ssh-ed25519@openssh.com
PubkeyAcceptedAlgorithms ssh-ed25519,rsa-sha2-512,sk-ssh-ed25519@openssh.com
CONF
  fi

  log "QuantumUnix layer applied."
}

install_helper_cli() {
  log "installing quantumunix-status helper..."
  cat > /usr/local/bin/quantumunix-status <<'CLI'
#!/usr/bin/env bash
set -euo pipefail
case "${1:-}" in
  --check)
    echo "[qu] AppArmor:  $(systemctl is-active apparmor.service || true)"
    echo "[qu] auditd:    $(systemctl is-active auditd.service || true)"
    echo "[qu] nftables:  $(systemctl is-active nftables.service || true)"
    echo "[qu] resolved:  $(systemctl is-active systemd-resolved.service || true)"
    ;;
  --crypto)
    grep -E '^(KexAlgorithms|HostKeyAlgorithms|PubkeyAcceptedAlgorithms)' \
      /etc/ssh/sshd_config.d/10-quantumunix.conf 2>/dev/null \
      || echo "[qu] no QuantumUnix SSH policy installed."
    ;;
  *)
    echo "usage: quantumunix-status --check | --crypto"
    exit 2 ;;
esac
CLI
  chmod 0755 /usr/local/bin/quantumunix-status
}

partition_disk() {
  [[ -n "${DISK}" ]] || die "--disk is required for the 'full' profile"
  [[ -b "${DISK}" ]] || die "not a block device: ${DISK}"
  lsblk "${DISK}"
  log "this will ERASE ${DISK} and create a LUKS2-encrypted root."
  confirm "Proceed and wipe ${DISK}?" || die "user cancelled"
  log "(reference) partitioning step is intentionally a no-op in this PoC script."
  log "use the bundled installer module 'qu-installer' for the real partitioning flow."
}

main() {
  require_root
  : > "${QU_LOG}" || true
  log "QuantumUnix bootstrap v${QU_VERSION} starting (profile=${PROFILE})"

  if [[ "${PROFILE}" == "full" ]]; then
    network_check
    partition_disk
  else
    require_arch_like
    network_check
  fi

  install_packages
  apply_quantumunix_layer
  install_helper_cli

  log "done. Run 'quantumunix-status --check' to verify."
  log "source: ${QU_REPO_URL}"
}

parse_args "$@"
main
