#!/bin/bash
# sysZivo uninstaller for macOS.   Guide: https://syszivo.com/uninstall
#
#   curl -fsSL https://syszivo.com/uninstall-syszivo.sh | bash
#   curl -fsSL https://syszivo.com/uninstall-syszivo.sh | bash -s -- --dry-run
#   curl -fsSL https://syszivo.com/uninstall-syszivo.sh | bash -s -- --remove-data
#
# What it does: quits sysZivo, moves the app (and the Face Unlock helper, if you installed it) to the
# Trash so you can still put it back, and ejects a sysZivo disk image that is still mounted.
# Your settings and account sign-in are KEPT unless you add --remove-data.
# Nothing is sent over the network. Written for the macOS default bash 3.2, no extra tools needed.

DRY=0
REMOVE_DATA=0
for arg in "$@"; do
  case "$arg" in
    --dry-run|-n) DRY=1 ;;
    --remove-data) REMOVE_DATA=1 ;;
    --yes|-y) ;;
    --help|-h)
      cat <<'USAGE'
sysZivo uninstaller

  --dry-run, -n   Show what would happen, change nothing.
  --remove-data   Also delete your sysZivo settings (~/.syszivo) and the saved account sign-in.
  --help, -h      This text.

Without options the app is moved to the Trash and your settings stay, so a later reinstall picks up where you left off.
USAGE
      exit 0 ;;
    *) echo "Unknown option: $arg  (try --help)" >&2; exit 2 ;;
  esac
done

if [ "$(uname -s)" != "Darwin" ]; then
  echo "This uninstaller is for macOS only." >&2
  exit 1
fi

APP_IDS="com.syszivo.desktop com.syszivo.checkout"
FACE_ID="com.syszivo.faceunlock"
FACE_APP="SysZivo Face Unlock.app"
FACE_EXE="SysZivoFaceUnlock"
KEYCHAIN_SERVICE="com.syszivo.account.v1"
STATE_DIR="${SYSZIVO_STATE_DIR:-$HOME/.syszivo}"
PLISTBUDDY="${PLISTBUDDY:-/usr/libexec/PlistBuddy}"
TRASH="$HOME/.Trash"
# SYSZIVO_APP_DIRS (colon separated) exists only so the automated tests never touch a real /Applications.
if [ -n "$SYSZIVO_APP_DIRS" ]; then IFS=: read -r -a APP_DIRS <<<"$SYSZIVO_APP_DIRS"; else APP_DIRS=(/Applications "$HOME/Applications"); fi
VOLUMES="${SYSZIVO_VOLUMES:-/Volumes}"

say()  { printf '%s\n' "$*"; }
step() { printf '\n==> %s\n' "$*"; }
ok()   { printf '  done: %s\n' "$*"; }
warn() { printf '  note: %s\n' "$*" >&2; }

REMOVED=0
PROBLEMS=0

# Run a command, or only print it with --dry-run.
act() {
  if [ "$DRY" -eq 1 ]; then printf '  [dry run] %s\n' "$*"; return 0; fi
  "$@"
}

lower() { printf '%s' "$1" | tr '[:upper:]' '[:lower:]'; }

bundle_id() { "$PLISTBUDDY" -c 'Print :CFBundleIdentifier' "$1/Contents/Info.plist" 2>/dev/null; }

is_running() { pgrep -x "$1" >/dev/null 2>&1; }

# ---- 1. quit -------------------------------------------------------------------------------------
step "Quitting sysZivo"
RUNNING=0
for name in sysZivo SysZivo "$FACE_EXE"; do
  if is_running "$name"; then RUNNING=1; fi
done
if [ "$RUNNING" -eq 0 ]; then
  say "  sysZivo is not running."
else
  for id in $APP_IDS "$FACE_ID"; do
    act osascript -e "if application id \"$id\" is running then tell application id \"$id\" to quit" >/dev/null 2>&1
  done
  if [ "$DRY" -eq 0 ]; then
    i=0
    while [ $i -lt 10 ]; do
      still=0
      for name in sysZivo SysZivo "$FACE_EXE"; do is_running "$name" && still=1; done
      [ "$still" -eq 0 ] && break
      sleep 0.5; i=$((i + 1))
    done
    for name in sysZivo SysZivo "$FACE_EXE"; do
      if is_running "$name"; then pkill -x "$name" 2>/dev/null; fi
    done
    sleep 1
    for name in sysZivo SysZivo "$FACE_EXE"; do
      if is_running "$name"; then pkill -9 -x "$name" 2>/dev/null; fi
    done
  fi
  ok "quit"
fi

# ---- helpers: move a folder to the Trash --------------------------------------------------------
# Finder first (the item can be put back and Finder asks for a password if the folder needs it),
# then a plain move into ~/.Trash as a fallback.
trash_path() {
  local target="$1" base stamp dest
  [ -e "$target" ] || return 0
  if [ "$DRY" -eq 1 ]; then printf '  [dry run] move to Trash: %s\n' "$target"; return 0; fi
  if osascript - "$target" >/dev/null 2>&1 <<'APPLESCRIPT'
on run argv
  tell application "Finder" to delete (POSIX file (item 1 of argv) as alias)
end run
APPLESCRIPT
  then
    [ -e "$target" ] || return 0
  fi
  base="$(basename "$target")"
  stamp="$(date +%H%M%S)"
  dest="$TRASH/$base"
  [ -e "$dest" ] && dest="$TRASH/${base%.*} $stamp.${base##*.}"
  mkdir -p "$TRASH" 2>/dev/null
  if mv "$target" "$dest" 2>/dev/null && [ ! -e "$target" ]; then return 0; fi
  # Apps installed by an administrator belong to root: this is the one step that needs the Mac password.
  warn "$target needs administrator rights. Enter your Mac password if asked."
  if sudo mv "$target" "$dest" 2>/dev/null && [ ! -e "$target" ]; then return 0; fi
  return 1
}

# ---- 2. the app ---------------------------------------------------------------------------------
step "Looking for the sysZivo app"
CANDIDATES=""
for dir in "${APP_DIRS[@]}"; do
  for name in sysZivo.app SysZivo.app; do
    [ -d "$dir/$name" ] && CANDIDATES="$CANDIDATES
$dir/$name"
  done
done
# Anywhere else Spotlight knows about (for example an app dragged to the Desktop).
for id in $APP_IDS; do
  found="$(mdfind "kMDItemCFBundleIdentifier == '$id'" 2>/dev/null)"
  [ -n "$found" ] && CANDIDATES="$CANDIDATES
$found"
done

SEEN=""
FOUND_APP=0
IFS_SAVE="$IFS"
IFS='
'
for app in $CANDIDATES; do
  [ -n "$app" ] && [ -d "$app" ] || continue
  key="$(lower "$app")"
  case "$SEEN" in *"|$key|"*) continue ;; esac
  SEEN="$SEEN|$key|"
  case "$app" in "$VOLUMES"/*) continue ;; esac   # a mounted disk image is ejected below
  id="$(bundle_id "$app")"
  case " $APP_IDS " in
    *" $id "*) ;;
    *) warn "skipped $app (it is not sysZivo)"; continue ;;
  esac
  FOUND_APP=1
  say "  found: $app"
  if trash_path "$app"; then
    ok "moved to Trash: $app"; REMOVED=1
  else
    warn "could not remove $app. Delete it from Finder, then run this again."; PROBLEMS=1
  fi
done
IFS="$IFS_SAVE"
if [ "$FOUND_APP" -eq 0 ]; then
  say "  The installed sysZivo app was not found (already removed, or you ran it from the disk image)."
fi

# ---- 3. Face Unlock helper ----------------------------------------------------------------------
step "Looking for Face Unlock"
FOUND_FACE=0
for dir in "${APP_DIRS[@]}"; do
  helper="$dir/$FACE_APP"
  [ -d "$helper" ] || continue
  [ "$(bundle_id "$helper")" = "$FACE_ID" ] || { warn "skipped $helper (not the sysZivo helper)"; continue; }
  FOUND_FACE=1
  say "  found: $helper"
  # Its own --uninstall deletes saved faces, the stored password and key, and the login item.
  if [ -x "$helper/Contents/MacOS/$FACE_EXE" ]; then
    act "$helper/Contents/MacOS/$FACE_EXE" --uninstall >/dev/null 2>&1
  fi
  if trash_path "$helper"; then
    ok "Face Unlock removed, including saved faces and the stored password"; REMOVED=1
  else
    warn "could not remove $helper. Delete it from Finder."; PROBLEMS=1
  fi
done
[ "$FOUND_FACE" -eq 0 ] && say "  Face Unlock is not installed."

# ---- 4. start-at-login entries ------------------------------------------------------------------
for plist in "$HOME"/Library/LaunchAgents/com.syszivo.*.plist; do
  [ -e "$plist" ] || continue
  step "Removing start-at-login entry"
  act launchctl bootout "gui/$(id -u)" "$plist" >/dev/null 2>&1
  if trash_path "$plist"; then ok "$(basename "$plist")"; REMOVED=1; fi
done

# ---- 5. disk image still mounted ----------------------------------------------------------------
step "Looking for a mounted sysZivo disk image"
FOUND_VOL=0
for vol in "$VOLUMES"/*; do
  [ -d "$vol" ] || continue
  case "$(lower "$(basename "$vol")")" in
    *syszivo*)
      FOUND_VOL=1
      say "  found: $vol"
      if act hdiutil detach "$vol" >/dev/null 2>&1; then ok "ejected $vol"; else warn "could not eject $vol. Close sysZivo, then drag the disk to the Trash in Finder."; PROBLEMS=1; fi ;;
  esac
done
[ "$FOUND_VOL" -eq 0 ] && say "  No sysZivo disk image is mounted."

# ---- 6. settings and sign-in --------------------------------------------------------------------
step "Settings and account sign-in"
if [ "$REMOVE_DATA" -eq 1 ]; then
  if [ -d "$STATE_DIR" ]; then
    if trash_path "$STATE_DIR"; then ok "settings moved to Trash: $STATE_DIR"; else warn "could not remove $STATE_DIR"; PROBLEMS=1; fi
  else
    say "  No settings folder found."
  fi
  if [ "$DRY" -eq 1 ]; then
    say "  [dry run] delete Keychain item $KEYCHAIN_SERVICE"
  else
    n=0
    while security delete-generic-password -s "$KEYCHAIN_SERVICE" >/dev/null 2>&1 && [ $n -lt 10 ]; do n=$((n + 1)); done
    [ $n -gt 0 ] && ok "removed the saved account sign-in from Keychain" || say "  No saved account sign-in found."
  fi
else
  say "  Kept, so a later reinstall continues where you left off."
  say "  To delete them too, run this again with --remove-data."
fi

# ---- summary ------------------------------------------------------------------------------------
printf '\n'
if [ "$DRY" -eq 1 ]; then
  say "Dry run finished. Nothing was changed."
elif [ "$PROBLEMS" -ne 0 ]; then
  say "Finished with the notes above. Fix those by hand, then run the command again."
  exit 1
elif [ "$REMOVED" -eq 1 ]; then
  say "sysZivo is uninstalled. Empty the Trash when you are sure."
else
  say "Nothing to remove. sysZivo was not found on this Mac."
fi
exit 0
