#!/usr/bin/env bash
set -euo pipefail
export DEBIAN_FRONTEND=noninteractive

LOG=/var/log/nebios-x-upgrade.log
exec > >(tee -a "$LOG") 2>&1

# --------------------------
# Detect original codename BEFORE we touch sources
# --------------------------
ORIGINAL_CODENAME="$(lsb_release -sc || echo unknown)"
MIGRATE_MODE="backup"   # default: backup to -3.0.bak
if [[ "$ORIGINAL_CODENAME" == "jammy" ]] && dpkg -l | awk '{print $2}' | grep -qx "nebios-kde"; then
  # Special rule you asked: on Jammy with nebios-kde installed, do NOT back up NebiSoft; overwrite it.
  MIGRATE_MODE="overwrite-nebisoft"
fi

TARGET_CODENAME="noble"          # Ubuntu 24.04
NEBI_CODENAME="cappadocia"       # NebiOS X

require_root() { [[ $EUID -eq 0 ]] || { echo "Run this script with sudo/root."; exit 1; }; }
require_root

echo "[1/11] Remove packages that are gone in NebiOS X"
apt purge -y biolock winegui nebios-windows-support winbind || true
apt purge -y howdy || true
apt purge -y tlp || true
apt autoremove -y || true

echo "[2/11] Add PPAs (do this while still on ${ORIGINAL_CODENAME})"
add-apt-repository -y ppa:pipewire-debian/pipewire-upstream || true
add-apt-repository -y ppa:pipewire-debian/wireplumber-upstream || true
add-apt-repository -y ppa:ernstp/mesarc || true

echo "[3/11] Flip sources to ${TARGET_CODENAME} + NebiOS ${NEBI_CODENAME} (no new repo files)"
# Ubuntu base: <jammy> -> <noble>
sed -i "s/$(lsb_release -sc)/${TARGET_CODENAME}/g" /etc/apt/sources.list || true
sed -i "s/$(lsb_release -sc)/${TARGET_CODENAME}/g" /etc/apt/sources.list.d/*.list 2>/dev/null || true

# NebiOS list(s): galata -> cappadocia (convert existing list; do NOT add a new .list)
for f in /etc/apt/sources.list.d/*nebios*galata*.list /etc/apt/sources.list.d/archive_uri-https_legacypkg_nebisoftware_com_nebios_galata_-jammy.list; do
  [[ -f "$f" ]] && sed -i "s/galata/${NEBI_CODENAME}/g" "$f" || true
done

apt update

echo "[4/11] Pre-fetch NebiDE package (download-only)"
apt install -y nebide --download-only || true

echo "[5/11] Force full system upgrade + NebiDE (your tactic)"
# Take new config files automatically; keep old ones as .dpkg-old
apt-get -o Dpkg::Options::="--force-confnew" -y dist-upgrade nebide || true
apt --fix-broken install
apt-get -o Dpkg::Options::="--force-confnew" -y dist-upgrade nebide

echo "[6/11] Switch display manager → greetd + nebigreeter"
apt purge -y lightdm nody-greeter sddm || true
apt install -y greetd nebigreeter
systemctl enable greetd || true
# You requested this exact permission:
chmod 7777 /etc/greetd || true

echo "[7/11] System Apps packages"
apt install -y \
  evince gnome-text-editor lollypop nautilus gnome-disk-utility \
  gnome-system-monitor totem gnome-characters geary eog \
  ca-certificates curl easyeffects calf-plugins

echo "[8/11] Unicode fonts"
apt install -y fonts-noto fonts-noto-cjk fonts-noto-color-emoji \
               fonts-dejavu fonts-dejavu-core fonts-dejavu-extra
fc-cache -fv || true

echo "[9/11] Migrate configs under /Users with -3.0.bak backups"
echo "       Mode: ${MIGRATE_MODE} (special overwrite only applies to NebiSoft on Jammy+nebios-kde)"
for udir in /Users/*; do
  [[ -d "$udir" ]] || continue

  # NebiSoft
  if [[ "$MIGRATE_MODE" == "overwrite-nebisoft" ]]; then
    # Do NOT back up NebiSoft; place fresh one
    rm -rf "$udir/.config/NebiSoft" || true
    mkdir -p "$udir/.config/NebiSoft"
    [[ -d /etc/skel/.config/NebiSoft ]] && cp -r /etc/skel/.config/NebiSoft/. "$udir/.config/NebiSoft/"
  else
    # Default: backup to -3.0.bak if exists
    if [[ -d "$udir/.config/NebiSoft" ]]; then
      mv "$udir/.config/NebiSoft" "$udir/.config/NebiSoft-3.0.bak" || true
    fi
    mkdir -p "$udir/.config/NebiSoft"
    [[ -d /etc/skel/.config/NebiSoft ]] && cp -r /etc/skel/.config/NebiSoft/. "$udir/.config/NebiSoft/"
  fi

  # GTK4 (backup regardless)
  if [[ -d "$udir/.config/gtk-4.0" ]]; then
    mv "$udir/.config/gtk-4.0" "$udir/.config/gtk-4.0-3.0.bak" || true
  fi
  mkdir -p "$udir/.config/gtk-4.0"
  [[ -d /etc/skel/.config/gtk-4.0 ]] && cp -r /etc/skel/.config/gtk-4.0/. "$udir/.config/gtk-4.0/"

  chown -R "$(stat -c %u:%g "$udir")" "$udir/.config" || true
done

# Apply to root as well
if [[ "$MIGRATE_MODE" == "overwrite-nebisoft" ]]; then
  rm -rf /root/.config/NebiSoft || true
  mkdir -p /root/.config/NebiSoft
  [[ -d /etc/skel/.config/NebiSoft ]] && cp -r /etc/skel/.config/NebiSoft/. /root/.config/NebiSoft/
else
  if [[ -d /root/.config/NebiSoft ]]; then
    mv /root/.config/NebiSoft /root/.config/NebiSoft-3.0.bak || true
  fi
  mkdir -p /root/.config/NebiSoft
  [[ -d /etc/skel/.config/NebiSoft ]] && cp -r /etc/skel/.config/NebiSoft/. /root/.config/NebiSoft/
fi

if [[ -d /root/.config/gtk-4.0 ]]; then
  mv /root/.config/gtk-4.0 /root/.config/gtk-4.0-3.0.bak || true
fi
mkdir -p /root/.config/gtk-4.0
[[ -d /etc/skel/.config/gtk-4.0 ]] && cp -r /etc/skel/.config/gtk-4.0/. /root/.config/gtk-4.0/

echo "[10/11] Installing missing components and updating napp database"
sudo apt install nebios-*
sudo update-napp-launchers
sudo systemctl enable greetd

echo "[11/11] Cleanup"
apt install kde*- plasma*- sddm- kdeconnect plasma-framework kded5 blueman  notification-daemon nebide
apt autoremove -y || true
apt autoclean -y || true

echo "Done. A reboot is recommended."
