#!/usr/bin/env bash
# ============================================================
#  XHCOS Lite (Mint) — chroot 内品牌化 + 适度精简
#  基于 Linux Mint 22.3 XFCE 64-bit 重塑，面向 Dell Wyse 3040
#  （2GB RAM / 8GB eMMC）。桌面已是 XFCE，故只做品牌换皮 +
#  移除重量级预装 + 注入 Calamares(XHCOS) 安装器界面。
#
#  由 build-xhcos-mint.sh 在 chroot 中调用；品牌资产在
#  /root/xhcos-assets（脚本拷贝进来的），用完即删。
# ============================================================
set -uo pipefail
export DEBIAN_FRONTEND=noninteractive
AST=/root/xhcos-assets
echo "==> [chroot] XHCOS Lite (Mint) 品牌化开始"

# ---------- 0. 宿主工具（chroot 内够用即可） ----------
echo "==> [0] 刷新 apt 索引"
apt-get update -o Acquire::Retries=3 2>&1 | tail -3 || true

# ---------- 1. 系统身份（os-release / lsb / hostname） ----------
echo "==> [1] 系统身份 -> XHCOS"
mkdir -p /etc
cat > /etc/os-release <<'EOF'
NAME="XHCOS"
VERSION="2.0.0 (Calico Lite / Mint 22.3 XFCE)"
ID=xhcos
ID_LIKE=linuxmint-ubuntu-debian
PRETTY_NAME="XHCOS Lite 2.0.0 (Calico Lite)"
VERSION_ID="2.0.0"
HOME_URL="https://xhcns.org/"
SUPPORT_URL="https://xhcns.org/"
BUG_REPORT_URL="https://xhcns.org/"
LOGO=xhcos
EOF
cat > /etc/lsb-release <<'EOF'
DISTRIB_ID=XHCOS
DISTRIB_RELEASE=2.0.0
DISTRIB_CODENAME=calico
DISTRIB_DESCRIPTION="XHCOS Lite 2.0.0 (Calico Lite)"
EOF
echo "XHCOS" > /etc/hostname 2>/dev/null || true
# 清理残留 mint/ubuntu 痕迹
sed -i 's/Linux Mint/XHCOS/g; s/Ubuntu/XHCOS/g' /etc/issue /etc/issue.net 2>/dev/null || true

# ---------- 2. Plymouth 启动动画（深蓝 + XHCOS logo） ----------
echo "==> [2] Plymouth 主题 -> xhcos"
if [ -d "$AST/plymouth" ]; then
  mkdir -p /usr/share/plymouth/themes/xhcos
  cp "$AST/plymouth/xhcos.plymouth" /usr/share/plymouth/themes/xhcos/ 2>/dev/null || true
  cp "$AST/plymouth/xhcos.script"   /usr/share/plymouth/themes/xhcos/ 2>/dev/null || true
  cp "$AST/plymouth/logo.png"       /usr/share/plymouth/themes/xhcos/ 2>/dev/null || true
  mkdir -p /etc/plymouth
  cat > /etc/plymouth/plymouthd.conf <<'EOF'
[Daemon]
Theme=xhcos
ShowDelay=0
EOF
  if [ -x /usr/sbin/plymouth-set-default-theme ]; then
    /usr/sbin/plymouth-set-default-theme -R xhcos 2>/dev/null || true
  fi
  ln -sf /usr/share/plymouth/themes/xhcos/xhcos.plymouth \
         /usr/share/plymouth/themes/default.plymouth 2>/dev/null || true
  # 清掉 ubuntu/mint 遗留 logo
  rm -f /usr/share/plymouth/ubuntu-logo.png 2>/dev/null || true
  rm -f /usr/share/plymouth/themes/*/ubuntu-logo.png 2>/dev/null || true
  rm -f /usr/share/plymouth/themes/*/mint-logo.png 2>/dev/null || true
fi

# ---------- 3. 已安装系统 GRUB 身份 ----------
echo "==> [3] GRUB_DISTRIBUTOR -> XHCOS"
if [ -f /etc/default/grub ]; then
  if grep -q '^GRUB_DISTRIBUTOR=' /etc/default/grub; then
    sed -i "s|^GRUB_DISTRIBUTOR=.*|GRUB_DISTRIBUTOR='XHCOS'|" /etc/default/grub
  else
    echo "GRUB_DISTRIBUTOR='XHCOS'" >> /etc/default/grub
  fi
fi
# 顺手把 os-prober 关掉（单系统瘦客户机，避免扫到多余项）
sed -i 's/^#\?GRUB_DISABLE_OS_PROBER=.*/GRUB_DISABLE_OS_PROBER=true/' /etc/default/grub 2>/dev/null || \
  echo "GRUB_DISABLE_OS_PROBER=true" >> /etc/default/grub

# ---------- 4. 桌面品牌：LightDM + XFCE 主题 + 壁纸 ----------
echo "==> [4] LightDM / XFCE 品牌化"
mkdir -p /usr/share/backgrounds/xhcos
cp "$AST/wallpaper/default.jpg" /usr/share/backgrounds/xhcos/default.jpg 2>/dev/null || true
# LightDM GTK greeter
mkdir -p /etc/lightdm
cat > /etc/lightdm/lightdm-gtk-greeter.conf <<'EOF'
[greeter]
background=/usr/share/backgrounds/xhcos/default.jpg
logo=/usr/share/backgrounds/xhcos/xhcos-logo.png
user-background=false
theme-name=xhcos-hero
icon-theme-name=xhcos-hero
font-name=Noto Sans CJK SC 11
EOF
cat > /etc/lightdm/lightdm.conf <<'EOF'
[Seat:*]
greeter-session=lightdm-gtk-greeter
user-session=xfce
EOF
# 复制 HERO 主题
if [ -d "$AST/theme/xhcos-hero" ]; then
  rm -rf /usr/share/themes/xhcos-hero
  cp -r "$AST/theme/xhcos-hero" /usr/share/themes/xhcos-hero
fi
# 生成 LightDM 用 logo（白底透明复用 logo-light）
cp "$AST/logos/logo-light.png" /usr/share/backgrounds/xhcos/xhcos-logo.png 2>/dev/null || true

# XFCE 默认配置（live 用户 mint + /etc/skel 给新装用户）
set_xfce(){
  local D="$1"
  mkdir -p "$D/.config/xfce4/xfconf/xfce-perchannel-xml"
  cat > "$D/.config/xfce4/xfconf/xfce-perchannel-xml/xsettings.xml" <<'XSF'
<?xml version="1.0" encoding="UTF-8"?>
<channel name="xsettings" version="1.0">
  <property name="Net" type="empty">
    <property name="ThemeName" type="string" value="xhcos-hero"/>
    <property name="IconThemeName" type="string" value="xhcos-hero"/>
    <property name="DoubleClickTime" type="int" value="400"/>
  </property>
  <property name="Gtk" type="empty">
    <property name="FontName" type="string" value="Noto Sans CJK SC 11"/>
    <property name="MonospaceFontName" type="string" value="Noto Sans Mono CJK SC 11"/>
    <property name="CursorThemeName" type="string" value="Adwaita"/>
  </property>
</channel>
XSF
  cat > "$D/.config/xfce4/xfconf/xfce-perchannel-xml/xfce4-desktop.xml" <<'XDF'
<?xml version="1.0" encoding="UTF-8"?>
<channel name="xfce4-desktop" version="1.0">
  <property name="backdrop" type="empty">
    <property name="screen0" type="empty">
      <property name="monitor0" type="empty">
        <property name="workspace0" type="empty">
          <property name="color-style" type="int" value="0"/>
          <property name="image-style" type="int" value="5"/>
          <property name="last-image" type="string" value="/usr/share/backgrounds/xhcos/default.jpg"/>
        </property>
      </property>
    </property>
  </property>
</channel>
XDF
  chown -R "$(stat -c '%U' "$D" 2>/dev/null || echo root)": "$D/.config" 2>/dev/null || true
}
# live 用户（Mint live 默认叫 mint）
if id mint >/dev/null 2>&1; then set_xfce /home/mint; fi
set_xfce /etc/skel

# ---------- 5. 2GB 内存优化：zram swap (1GB) ----------
echo "==> [5] zram swap (1GB) + swappiness=10"
cat > /etc/systemd/system/xhcos-zram.service <<'EOF'
[Unit]
Description=XHCOS Lite zram swap (1GB compressed)
DefaultDependencies=no
Before=swap.target
After=systemd-modules-load.service

[Service]
Type=oneshot
RemainAfterExit=yes
ExecStartPre=/bin/sh -c 'modprobe zram 2>/dev/null || true'
ExecStart=/bin/sh -c 'if [ ! -b /dev/zram0 ]; then exit 0; fi; echo 1G > /sys/block/zram0/disksize; mkswap /dev/zram0 2>/dev/null; swapon -p 100 /dev/zram0 2>/dev/null || true'
ExecStop=/bin/sh -c 'swapoff /dev/zram0 2>/dev/null || true'

[Install]
WantedBy=swap.target
EOF
systemctl enable xhcos-zram.service 2>/dev/null || true
# 低换页，尽量用 zram
echo "vm.swappiness=10" >> /etc/sysctl.d/99-xhcos.conf 2>/dev/null || { mkdir -p /etc/sysctl.d; echo "vm.swappiness=10" > /etc/sysctl.d/99-xhcos.conf; }

# ---------- 6. 适度精简（保留 XFCE+LightDM+Firefox+基础工具） ----------
echo "==> [6] 移除重量级预装（适度精简）"
PURGE="libreoffice* libreoffice-core* thunderbird* rhythmbox* \
       gnome-sudoku gnome-mines aisleriot mate-* pidgin* timeshift* \
       shotwell* brasero* gnome-maps* gnome-calendar* deja-dup* \
       gnome-orca simple-scan* gnome-characters* gnome-font-viewer* \
       mintwelcome* mintreport* "
# 尽力移除，缺包不报错
apt-get purge -y --auto-remove $PURGE 2>&1 | tail -5 || true
# 清残留依赖
apt-get autoremove -y --purge 2>&1 | tail -3 || true
# 保留但确保装上的基础工具
apt-get install -y --no-install-recommends curl wget git gparted \
  xfce4-terminal xfce4-screenshooter 2>&1 | tail -3 || true

# ---------- 7. Calamares 安装器：XHCOS 品牌界面 ----------
echo "==> [7] 注入 Calamares XHCOS 品牌（对齐 XHCOSEmulator 安装界面）"
if [ -d "$AST/calamares" ]; then
  mkdir -p /etc/calamares/branding/XHCOS
  cp -r "$AST/calamares/." /etc/calamares/branding/XHCOS/ 2>/dev/null || true
  # 让 Calamares 使用本品牌
  if [ -f /etc/calamares/settings.conf ]; then
    sed -i -E 's/^[[:space:]]*branding:[[:space:]]*.*/branding: "XHCOS"/' /etc/calamares/settings.conf
  else
    mkdir -p /etc/calamares
    cat > /etc/calamares/settings.conf <<'EOF'
---
branding: "XHCOS"
EOF
  fi
  # 把 live 桌面“安装 Linux Mint”入口改名为“安装 XHCOS”
  for d in /usr/share/applications/*.desktop /home/mint/Desktop/*.desktop /etc/skel/Desktop/*.desktop; do
    [ -f "$d" ] || continue
    if grep -qi "calamares" "$d" || grep -qi "安装 Linux Mint\|Install Linux Mint" "$d"; then
      sed -i 's/^Name=.*/Name=安装 XHCOS/' "$d" 2>/dev/null || true
      sed -i 's/^Name\[.*\]=.*//' "$d" 2>/dev/null || true
    fi
  done
fi

# ---------- 8. XHC 软件商店（桌面快捷方式） ----------
echo "==> [8] 安装 XHC 软件商店"
if [ -f "$AST/store/xhcos-store.py" ]; then
  mkdir -p /opt/xhcos
  cp "$AST/store/xhcos-store.py" /opt/xhcos/xhcos-store.py
  chmod +x /opt/xhcos/xhcos-store.py
  cp "$AST/store/xhcos-store.desktop" /usr/share/applications/xhcos-store.desktop 2>/dev/null || true
  # 修正 desktop 里 Exec 路径
  sed -i 's|^Exec=.*|Exec=/opt/xhcos/xhcos-store.py|' /usr/share/applications/xhcos-store.desktop 2>/dev/null || true
fi

# ---------- 9. 收尾：清理 apt / 临时资产 ----------
echo "==> [9] 收尾清理"
apt-get clean 2>/dev/null || true
rm -rf /var/lib/apt/lists/* 2>/dev/null || true
rm -rf /root/xhcos-assets 2>/dev/null || true
echo "==> [chroot] XHCOS Lite (Mint) 品牌化完成"
