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

MAP=${SENTINEL_LINUX_ICON_MAP:-/usr/share/sentinel-linux/icon-variants.tsv}
ICON_ROOT=${SENTINEL_LINUX_ICON_ROOT:-/usr/share/icons}
CONFIRM=APPLY_SENTINEL_LINUX_ICONS

die(){ printf 'ERROR: %s\n' "$*" >&2; exit 1; }
need_user(){ [[ ${EUID:-$(id -u)} -ne 0 ]] || die 'run icon selection as the normal desktop user, not with sudo'; }
need_map(){ [[ -r "$MAP" ]] || die "icon map missing: $MAP"; }
lookup(){ awk -F '\t' -v wanted="$1" 'NR>1 && $1==wanted {print $2"\t"$3; found=1} END{if(!found) exit 1}' "$MAP"; }

usage(){
  cat <<USAGE
Usage:
  sentinel-linux-icon-selector --list
  sentinel-linux-icon-selector --current
  sentinel-linux-icon-selector --verify-system
  sentinel-linux-icon-selector --apply COLOUR --confirm $CONFIRM

Available colours: light-cyan, dark-red, light-purple, dark-pink, light-green
This changes only the current user's icon and matching cursor themes. GTK,
Marco, wallpaper, panel, programs and system policy are not changed.
USAGE
}

list_variants(){ need_map; column -t -s $'\t' "$MAP" 2>/dev/null || cat "$MAP"; }
current(){
  need_user
  printf 'icons=%s\n' "$(gsettings get org.mate.interface icon-theme)"
  printf 'cursor=%s\n' "$(gsettings get org.gnome.desktop.interface cursor-theme)"
}
verify_system(){
  need_map
  local variant icons cursor
  while IFS=$'\t' read -r variant icons cursor; do
    [[ "$variant" == variant ]] && continue
    [[ -s "$ICON_ROOT/$icons/index.theme" ]] || die "$variant icon theme missing: $icons"
    [[ -s "$ICON_ROOT/$cursor/index.theme" ]] || die "$variant cursor theme missing: $cursor"
    printf 'PASS: %s\n' "$variant"
  done < "$MAP"
  printf 'verify: ok\n'
}
apply_variant(){
  local variant=$1 confirm=$2 values icons cursor
  need_user; need_map
  [[ "$confirm" == "$CONFIRM" ]] || die "confirmation required: --confirm $CONFIRM"
  values=$(lookup "$variant") || die "unknown icon colour: $variant"
  IFS=$'\t' read -r icons cursor <<< "$values"
  [[ -s "$ICON_ROOT/$icons/index.theme" ]] || die "icon theme missing: $icons"
  [[ -s "$ICON_ROOT/$cursor/index.theme" ]] || die "cursor theme missing: $cursor"
  gsettings set org.mate.interface icon-theme "$icons"
  gsettings set org.gnome.desktop.interface cursor-theme "$cursor"
  [[ "$(gsettings get org.mate.interface icon-theme)" == "'$icons'" ]] || die 'icon setting did not persist'
  [[ "$(gsettings get org.gnome.desktop.interface cursor-theme)" == "'$cursor'" ]] || die 'cursor setting did not persist'
  printf 'Applied Sentinel Linux icon colour: %s\n' "$variant"
}

case "${1:-}" in
  --list) [[ $# -eq 1 ]] || die 'unexpected arguments'; list_variants ;;
  --current) [[ $# -eq 1 ]] || die 'unexpected arguments'; current ;;
  --verify-system) [[ $# -eq 1 ]] || die 'unexpected arguments'; verify_system ;;
  --apply) [[ $# -eq 4 && ${3:-} == --confirm ]] || { usage; exit 2; }; apply_variant "$2" "$4" ;;
  -h|--help|'') usage ;;
  *) usage; exit 2 ;;
esac
