#!/bin/bash
# reset-users.sh — delete all standard macOS user accounts (UID >= 501)
# except the one running this script, then create a fresh user.
# Run as: sudo ./reset-users.sh
set -euo pipefail

if [[ $EUID -ne 0 ]]; then
  echo "Run with sudo: sudo $0" >&2
  exit 1
fi

# Account to protect = whoever invoked sudo (the logged-in admin).
KEEP="${SUDO_USER:-$(logname)}"
echo "Protected account: $KEEP"

# Real accounts have UID >= 501. Collect targets, excluding KEEP.
targets=()
while IFS= read -r u; do
  uid=$(dscl . -read "/Users/$u" UniqueID 2>/dev/null | awk '{print $2}')
  [[ -z "$uid" ]] && continue
  if (( uid >= 501 )) && [[ "$u" != "$KEEP" ]]; then
    targets+=("$u")
  fi
done < <(dscl . -list /Users)

if (( ${#targets[@]} == 0 )); then
  echo "No accounts to delete."
else
  echo
  echo "WILL DELETE these accounts AND their home directories:"
  printf '  - %s\n' "${targets[@]}"
  echo
  read -r -p "Type DELETE to confirm: " ans
  [[ "$ans" == "DELETE" ]] || { echo "Aborted."; exit 1; }

  for u in "${targets[@]}"; do
    echo "Deleting $u ..."
    sysadminctl -deleteUser "$u"   # removes account + home dir
  done
fi

# --- Create new user ---
echo
read -r -p "New username: " newuser
[[ -n "$newuser" ]] || { echo "Empty username."; exit 1; }
read -r -s -p "New password: " newpass; echo
[[ -n "$newpass" ]] || { echo "Empty password."; exit 1; }

sysadminctl -addUser "$newuser" -password "$newpass"
echo "Created user: $newuser"
