#!/bin/sh
# =============================================================================
# epc670-reset-desktop
# Reverts all changes made by epc670_setup_desktop for a given user:
#   - Removes epc670 autostart entries
#   - Removes epc670 desktop symlinks
#   - Restores waybar and labwc configs from backup (if available),
#     otherwise removes the epc670-installed files
#   - Removes the venv block from .bashrc
#   - Removes the user from the epc670 group
#   - Removes the user from users.conf
#   - Removes the user's backup directory
#   - Disables autoresolution
#
# Must be run as root (e.g. via sudo).
#
# Usage:
#   sudo epc670-reset-desktop [--yes] [username]
# =============================================================================

# Do NOT use set -e — this script is called from prerm and any unexpected exit
# would leave the package in a broken half-removed state. All errors are handled
# explicitly.

# -----------------------------------------------------------------------------
# Require root
# -----------------------------------------------------------------------------
if [ "$(id -u)" -ne 0 ]; then
  echo "Error: this script must be run as root. Try: sudo $0 $*" >&2
  exit 1
fi

VENV_GROUP="epc670"
USERS_CONF="/usr/share/epc670/users.conf"
BACKUP_BASE="/usr/share/epc670-tofhat-utils/backups"
DESKTOP_STAMP="/var/lib/epc670/desktop-setup-done"
AUTOSTART_DESKTOPS="TOFcam-670.desktop"
DESKTOP_SYMLINKS="epc670-docs.desktop epc670-update.desktop TOFcam-670.desktop"
WAYBAR_FILES="config.jsonc style.css"
BASHRC_REMOVE="/usr/lib/epc670-tofhat-utils/epc670-bashrc-remove"

log() {
  echo "epc670-reset-desktop: $*"
  logger -t epc670-reset-desktop "$*" 2>/dev/null || true
}

warn() {
  log "Warning: $*"
}

# -----------------------------------------------------------------------------
# Parse arguments
# -----------------------------------------------------------------------------
YES=false
TARGET_USER=""
for arg in "$@"; do
  case "$arg" in
    --yes) YES=true ;;
    -*) warn "Unknown option: $arg" ;;
    *)
      if [ -z "$TARGET_USER" ]; then
        TARGET_USER="$arg"
      else
        warn "Unexpected argument: $arg (ignoring)"
      fi
      ;;
  esac
done

# -----------------------------------------------------------------------------
# Resolve target user
# -----------------------------------------------------------------------------
if [ -z "$TARGET_USER" ]; then
  TARGET_USER="${SUDO_USER:-}"
fi

# Use -s (non-empty) rather than -f: a fully-reset machine can leave an empty
# users.conf, from which head would return nothing.
if [ -z "$TARGET_USER" ] && [ -s "$USERS_CONF" ]; then
  TARGET_USER="$(head -n1 "$USERS_CONF")"
fi

if [ -z "$TARGET_USER" ]; then
  TARGET_USER="epc"
  warn "Could not determine target user, falling back to 'epc'"
fi

# -----------------------------------------------------------------------------
# Confirm before proceeding
# -----------------------------------------------------------------------------
echo ""
echo "╔══════════════════════════════════════════════════════════════╗"
echo "║  epc670-reset-desktop                                        ║"
echo "║                                                              ║"
echo "║  This script will make the following changes:                ║"
echo "║                                                              ║"
echo "║  • Remove epc670 autostart entries from ~/.config/autostart  ║"
echo "║  • Remove epc670 shortcuts from ~/Desktop                    ║"
echo "║  • Restore waybar config from backup (or remove if none)     ║"
echo "║  • Restore labwc autostart from backup (or remove if none)   ║"
echo "║  • Remove the epc670 venv block from ~/.bashrc               ║"
echo "║  • Remove the user from the epc670 group                     ║"
echo "║  • Remove the user from epc670's users.conf                  ║"
echo "║  • Delete the epc670 backup for this user                    ║"
echo "║  • Disable autoresolution                                    ║"
echo "╚══════════════════════════════════════════════════════════════╝"
echo ""
echo "  Target user: $TARGET_USER"
echo ""

if [ "$YES" = true ]; then
  log "Proceeding non-interactively (--yes)"
else
  printf "Proceed? [y/N] "
  read -r answer
  case "$answer" in
    y|Y) ;;
    *) log "Aborted by user."; exit 0 ;;
  esac
fi

# -----------------------------------------------------------------------------
# revert_user_setup <user>
# All operations log warnings on failure rather than aborting.
# -----------------------------------------------------------------------------
revert_user_setup() {
  user="$1"
  user_home=$(getent passwd "$user" | cut -d: -f6)
  backup_dir="$BACKUP_BASE/$user"

  if [ -z "$user_home" ]; then
    warn "Could not determine home directory for $user — skipping file operations"
    return
  fi

  # Autostart entries
  for entry in $AUTOSTART_DESKTOPS; do
    path="$user_home/.config/autostart/$entry"
    if [ -f "$path" ]; then
      rm -f "$path" && log "Removed autostart entry: $path" \
        || warn "Could not remove autostart entry: $path"
    fi
  done

  # Desktop symlinks
  for desktop in $DESKTOP_SYMLINKS; do
    path="$user_home/Desktop/$desktop"
    if [ -L "$path" ]; then
      rm -f "$path" && log "Removed desktop symlink: $path" \
        || warn "Could not remove desktop symlink: $path"
    fi
  done

  # Waybar config — restore from backup if available, otherwise remove
  for f in $WAYBAR_FILES; do
    dst="$user_home/.config/waybar/$f"
    src="$backup_dir/waybar/$f"
    if [ -f "$src" ]; then
      cp "$src" "$dst" && chown "$user:$user" "$dst" \
        && log "Restored waybar config from backup: $f" \
        || warn "Could not restore waybar config: $f"
    elif [ -f "$dst" ]; then
      rm -f "$dst" && log "Removed waybar config (no backup): $dst" \
        || warn "Could not remove waybar config: $dst"
    fi
  done

  # Labwc autostart — restore from backup if available, otherwise remove
  labwc_dst="$user_home/.config/labwc/autostart"
  labwc_src="$backup_dir/labwc/autostart"
  if [ -f "$labwc_src" ]; then
    cp "$labwc_src" "$labwc_dst" && chown "$user:$user" "$labwc_dst" \
      && log "Restored labwc autostart from backup" \
      || warn "Could not restore labwc autostart"
  elif [ -f "$labwc_dst" ]; then
    rm -f "$labwc_dst" && log "Removed labwc autostart (no backup): $labwc_dst" \
      || warn "Could not remove labwc autostart: $labwc_dst"
  fi

  # Bashrc venv block
  if [ -f "$user_home/.bashrc" ]; then
    "$BASHRC_REMOVE" "$user_home/.bashrc" \
      || warn "Could not remove venv block from .bashrc"
  fi

  # Kill waybar if running
  if pgrep -u "$user" waybar > /dev/null 2>&1; then
    pkill -u "$user" waybar 2>/dev/null || true
    log "Killed running waybar for $user"
  fi

  # Clean up backup directory for this user
  if [ -d "$backup_dir" ]; then
    rm -rf "$backup_dir" && log "Removed backup directory: $backup_dir" \
      || warn "Could not remove backup directory: $backup_dir"
  fi

  log "Desktop reset applied for $user"
}

# -----------------------------------------------------------------------------
# Remove user from group
# -----------------------------------------------------------------------------
remove_from_group() {
  user="$1"
  if id -nG "$user" 2>/dev/null | grep -qw "$VENV_GROUP"; then
    gpasswd -d "$user" "$VENV_GROUP" \
      && log "Removed $user from group $VENV_GROUP" \
      || warn "Could not remove $user from group $VENV_GROUP"
  else
    log "$user is not in group $VENV_GROUP, skipping"
  fi
}

# -----------------------------------------------------------------------------
# Remove user from users.conf
# Uses fixed-string matching (grep -F) so usernames containing regex-special
# characters cannot match unintended lines. Filters via a temp file rather than
# `sed`, then drops the file (and the desktop-setup stamp) once empty.
# -----------------------------------------------------------------------------
remove_from_users_conf() {
  user="$1"
  [ -f "$USERS_CONF" ] || return
  grep -qxF "$user" "$USERS_CONF" || return

  tmp="$USERS_CONF.tmp"
  # grep -v exits 1 when no lines remain; that is success here, so swallow it.
  grep -vxF "$user" "$USERS_CONF" > "$tmp" 2>/dev/null || true
  if mv "$tmp" "$USERS_CONF"; then
    log "Removed $user from $USERS_CONF"
  else
    rm -f "$tmp"
    warn "Could not update $USERS_CONF"
    return
  fi

  # If no users remain, drop the file and the desktop-setup stamp so that
  # postinst will not re-run desktop setup on a future upgrade.
  if [ ! -s "$USERS_CONF" ]; then
    rm -f "$USERS_CONF" && log "users.conf now empty, removed it"
    if [ -e "$DESKTOP_STAMP" ]; then
      rm -f "$DESKTOP_STAMP" \
        && log "No users remain; removed desktop-setup stamp" \
        || warn "Could not remove desktop-setup stamp: $DESKTOP_STAMP"
    fi
  fi
}

# -----------------------------------------------------------------------------
# Run revert for target user
# -----------------------------------------------------------------------------
if id "$TARGET_USER" >/dev/null 2>&1; then
  revert_user_setup "$TARGET_USER"
  remove_from_group "$TARGET_USER"
  remove_from_users_conf "$TARGET_USER"
else
  warn "User '$TARGET_USER' not found — skipping user-specific reset."
fi

# -----------------------------------------------------------------------------
# Disable autoresolution
# -----------------------------------------------------------------------------
epc670-disable-autoresolution 2>/dev/null \
  && log "Autoresolution disabled." \
  || warn "epc670-disable-autoresolution failed or was not found — skipping."

log "Desktop reset complete."
