echo "======================================"
echo "[NASBEERY UI HARDENING PATCH]"
echo "======================================"

# -----------------------------
# 1. FONT BASICS (SYSTEM SAFE)
# -----------------------------
echo "[UI] Installing fonts + rendering base..."

apt install -y \
  fonts-dejavu \
  fonts-liberation \
  fontconfig

# -----------------------------
# 2. 45DRIVES FONT FIX (OFFICIAL REPO)
# -----------------------------
echo "[UI] Applying 45Drives cockpit font fix..."

rm -rf /tmp/45drives-scripts
git clone https://github.com/45Drives/scripts.git /tmp/45drives-scripts

if [ -d /tmp/45drives-scripts/cockpit_font_fix ]; then
  cd /tmp/45drives-scripts/cockpit_font_fix

  if [ -f install.sh ]; then
    bash install.sh || true
  else
    find . -type f -name "*.ttf" -exec cp {} /usr/share/fonts/ \; || true
    find . -type f -name "*.otf" -exec cp {} /usr/share/fonts/ \; || true
  fi
fi

fc-cache -f -v

# -----------------------------
# 3. UTF-8 / FONT FALLBACK FIX
# -----------------------------
echo "[UI] Configuring font fallback..."

cat << EOF > /etc/fonts/local.conf
<?xml version="1.0"?>
<!DOCTYPE fontconfig SYSTEM "fonts.dtd">
<fontconfig>
  <alias>
    <family>monospace</family>
    <prefer>
      <family>DejaVu Sans Mono</family>
    </prefer>
  </alias>
</fontconfig>
EOF

fc-cache -f -v

# -----------------------------
# 4. OPTIONAL ASCII SAFE MODE
# -----------------------------
echo "[UI] Applying ASCII-safe fallback (optional)..."

find /usr/share/cockpit/zfs -type f 2>/dev/null | while read f; do
  sed -i 's/✔/OK/g' "$f" 2>/dev/null || true
  sed -i 's/✖/FAIL/g' "$f" 2>/dev/null || true
  sed -i 's/⚠/WARN/g' "$f" 2>/dev/null || true
done

# -----------------------------
# 5. COCKPIT UI RESTART
# -----------------------------
echo "[UI] Restarting Cockpit..."

systemctl restart cockpit.socket || true
systemctl restart cockpit || true

# -----------------------------
# CLEANUP
# -----------------------------
rm -rf /tmp/45drives-scripts

echo "======================================"
echo "[UI HARDENING COMPLETE]"
echo "======================================"