#!/usr/bin/env bash
set -uo pipefail

STATE_DIR="/var/lib/saikyo-kde-rebrand"
GENERATED_LIST="${STATE_DIR}/generated.list"
DIVERT_LIST="${STATE_DIR}/diverts.list"
TMP_DIR="${STATE_DIR}/tmp"

apply_replacements_sed() {
  sed \
    -e 's/\bKDE\b/SAIKYO KDE/g' \
    -e 's/\bPlasma\b/SAIKYO KDE/g' \
    -e 's/\bPLASMA\b/SAIKYO KDE/g' \
    -e 's/\bDiscover\b/SAIKYO Discover/g' \
    -e 's/\bDEBIAN\b/SAIKYO OS/g' \
    -e 's/\bDebian\b/SAIKYO OS/g'
}

mkdir -p "${STATE_DIR}" "${TMP_DIR}"
chmod 0755 "${STATE_DIR}" "${TMP_DIR}"

record_generated() {
  local f="$1"
  touch "${GENERATED_LIST}" 2>/dev/null || true
  if ! grep -qxF "$f" "${GENERATED_LIST}" 2>/dev/null; then
    echo "$f" >>"${GENERATED_LIST}"
  fi
}

record_divert() {
  local f="$1"
  touch "${DIVERT_LIST}" 2>/dev/null || true
  if ! grep -qxF "$f" "${DIVERT_LIST}" 2>/dev/null; then
    echo "$f" >>"${DIVERT_LIST}"
  fi
}

require_root() {
  if [[ "$(id -u)" -ne 0 ]]; then
    echo "ERROR: must be run as root" >&2
    exit 1
  fi
}

is_diverted_by_us() {
  local f="$1"
  dpkg-divert --list "$f" 2>/dev/null | grep -q "package: saikyo-kde-rebrand" || return 1
}

divert_mo() {
  local f="$1"
  if is_diverted_by_us "$f"; then
    record_divert "$f"
    return 0
  fi
  dpkg-divert --package saikyo-kde-rebrand --add --rename --divert "${f}.saikyo-orig" "$f" >/dev/null
  record_divert "$f"
}

overlay_path_for() {
  local f="$1"
  case "$f" in
    /usr/share/applications/*)
      printf '%s\n' "/usr/local/share/applications/${f#/usr/share/applications/}"
      ;;
    /usr/share/metainfo/*)
      printf '%s\n' "/usr/local/share/metainfo/${f#/usr/share/metainfo/}"
      ;;
    /usr/share/locale/*)
      printf '%s\n' "/usr/local/share/locale/${f#/usr/share/locale/}"
      ;;
    *)
      return 1
      ;;
  esac
}

patch_text_to_overlay() {
  local src="$1"
  local dst
  dst="$(overlay_path_for "$src")" || return 0
  mkdir -p "$(dirname "$dst")" 2>/dev/null || return 0
  if apply_replacements_sed <"$src" >"$dst" 2>/dev/null; then
    chmod 0644 "$dst" 2>/dev/null || true
    record_generated "$dst"
  fi
}

patch_mo_to_overlay() {
  local src="$1"
  local dst tmp_po tmp_mo
  dst="$(overlay_path_for "$src")" || return 0
  mkdir -p "$(dirname "$dst")"

  tmp_po="${TMP_DIR}/$(basename "$src").$$.po"
  tmp_mo="${TMP_DIR}/$(basename "$src").$$.mo"

  # Try to patch, but don't fail if msgunfmt/msgfmt fails on corrupted .mo
  if msgunfmt "$src" 2>/dev/null | apply_replacements_sed >"$tmp_po" 2>/dev/null; then
    if msgfmt -o "$tmp_mo" "$tmp_po" 2>/dev/null && [[ -f "$tmp_mo" ]]; then
      install -m 0644 "$tmp_mo" "$dst" 2>/dev/null || true
      record_generated "$dst"
    fi
  fi
  rm -f "$tmp_po" "$tmp_mo" 2>/dev/null || true
}

patch_mo_in_place_diverted() {
  local f="$1"
  local tmp_po tmp_mo

  tmp_po="${TMP_DIR}/$(basename "$f").$$.po"
  tmp_mo="${TMP_DIR}/$(basename "$f").$$.mo"

  # Try to patch, but don't fail if msgunfmt/msgfmt fails on corrupted .mo
  if msgunfmt "${f}.saikyo-orig" 2>/dev/null | apply_replacements_sed >"$tmp_po" 2>/dev/null; then
    if msgfmt -o "$tmp_mo" "$tmp_po" 2>/dev/null && [[ -f "$tmp_mo" ]]; then
      install -m 0644 "$tmp_mo" "$f" 2>/dev/null || true
    fi
  fi
  rm -f "$tmp_po" "$tmp_mo" 2>/dev/null || true
}

apply_rebrand() {
  require_root
  : >"${GENERATED_LIST}"
  touch "${DIVERT_LIST}"

  local f

  while IFS= read -r -d '' f; do
    if grep -Eqi '\b(KDE|Plasma|PLASMA|Discover|Debian|DEBIAN)\b' "$f" 2>/dev/null; then
      patch_text_to_overlay "$f" || true
    fi
  done < <(find /usr/share/applications -type f -name '*.desktop' -print0 2>/dev/null) || true

  while IFS= read -r -d '' f; do
    if grep -Eqi '\b(KDE|Plasma|PLASMA|Discover|Debian|DEBIAN)\b' "$f" 2>/dev/null; then
      patch_text_to_overlay "$f" || true
    fi
  done < <(find /usr/share/metainfo -type f \( -name '*.metainfo.xml' -o -name '*.appdata.xml' \) -print0 2>/dev/null) || true

  while IFS= read -r -d '' f; do
    if grep -a -Eq '\b(KDE|Plasma|PLASMA|Discover|Debian|DEBIAN)\b' "$f" 2>/dev/null; then
      divert_mo "$f" || true
      patch_mo_in_place_diverted "$f" || true
    fi
  done < <(find /usr/share/locale -type f -name '*.mo' -print0 2>/dev/null) || true
}

revert_rebrand() {
  require_root

  if [[ -f "${GENERATED_LIST}" ]]; then
    local f
    while IFS= read -r f; do
      [[ -n "${f}" ]] || continue
      rm -f "$f" 2>/dev/null || true
    done <"${GENERATED_LIST}"

    rm -f "${GENERATED_LIST}" 2>/dev/null || true
  fi

  if [[ -f "${DIVERT_LIST}" ]]; then
    local f
    while IFS= read -r f; do
      [[ -n "${f}" ]] || continue
      if is_diverted_by_us "$f"; then
        rm -f "$f" 2>/dev/null || true
        dpkg-divert --package saikyo-kde-rebrand --remove --rename --divert "${f}.saikyo-orig" "$f" >/dev/null || true
      fi
    done <"${DIVERT_LIST}"

    rm -f "${DIVERT_LIST}" 2>/dev/null || true
  fi

  # Best-effort cleanup of empty directories
  find /usr/local/share/applications /usr/local/share/metainfo -type d -empty -print0 2>/dev/null | xargs -0r rmdir 2>/dev/null || true
}

main() {
  local cmd="${1:-}"
  case "$cmd" in
    apply) apply_rebrand;;
    revert) revert_rebrand;;
    *)
      echo "Usage: saikyo-kde-rebrand {apply|revert}" >&2
      exit 2
      ;;
  esac
}

main "$@"
