#!/usr/bin/env bash
# nems-userctl
# Unified user management for NEMS Linux - https://nemslinux.com/
# By Robbie Ferguson // Bald Nerd
# Version 1.0 // October 29, 2025 - Initial release
# Version 1.1 // October 30, 2025 - Add audit log
# Version 1.2 // October 31, 2025
# Version 1.3 // July 31, 2026 - Allow empty keys and fix order of SUPERADMIN_CREATE to accommodate NEMS Web-based Init
# Version 1.4 // September 23, 2026 - Suppress SQLite WAL output in favor of user-friendly init message
# Version 1.5 // October 12, 2026 - API Integration: Auto-generates Bearer tokens and links to user_tokens
# Version 1.6 // October 14, 2026 - API Integration: Profile Fields, and Token Regen

set -euo pipefail

# ---- Config ----
HTPASSWD_FILE="/var/www/htpasswd"
DB_DIR="/usr/local/share/nems/database"
DB_FILE="${DB_DIR}/users.db"
NEMS_CONF="/usr/local/share/nems/nems.conf"

MANAGED_GROUPS=(sudo www-data nagios gpio netdev monit)

declare -A ROLE_GROUPS
ROLE_GROUPS[superadmin]="sudo www-data nagios gpio netdev monit"
ROLE_GROUPS[admin]="sudo www-data nagios gpio netdev monit"
ROLE_GROUPS[operator]="www-data nagios gpio netdev monit"
ROLE_GROUPS[reporter]="www-data nagios"
ROLE_GROUPS[viewer]="www-data"

declare -A ROLE_PREC=( [viewer]=1 [reporter]=2 [operator]=3 [admin]=4 [superadmin]=5 )

LOGFILE="/var/log/nems/nems-userctl.log"
log_action() {
  local _ts; _ts=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
  printf '%s action=%s target=%s actor=%s detail=%s\n' \
      "$_ts" "$1" "$2" "$3" "$4" >> "$LOGFILE"
}

log(){ logger -t nems-userctl "$*"; }
die(){ echo "ERROR: $*" >&2; log "ERROR: $*"; exit 1; }
need_root(){ [[ ${EUID} -eq 0 ]] || die "Must run as root."; }
now_epoch(){ date +%s; }

check_bins(){
  command -v useradd >/dev/null 2>&1 || die "useradd missing."
  command -v usermod >/dev/null 2>&1 || die "usermod missing."
  command -v userdel >/dev/null 2>&1 || die "userdel missing."
  command -v chpasswd >/dev/null 2>&1 || die "chpasswd missing."
  command -v smbpasswd >/dev/null 2>&1 || die "smbpasswd missing."
  command -v htpasswd >/dev/null 2>&1 || die "htpasswd missing."
  command -v sqlite3  >/dev/null 2>&1 || die "sqlite3 missing."
}

usage(){
  cat <<EOF
NEMS unified user management

USAGE:
  nems-userctl create         --user <name> [--role <role>] [--full-name <name>] [--email <email>] [--mobile <num>] [--password-stdin | --password-file <path>]
  nems-userctl delete         --user <name> [--actor <name>]
  nems-userctl set-role       --user <name> --role <role> [--actor <name>]
  nems-userctl set-pass       --user <name> [--password-stdin | --password-file <path>] [--actor <name>]
  nems-userctl update-profile --user <name> [--full-name <name>] [--email <email>] [--mobile <num>] [--actor <name>]
  nems-userctl regen-token    --user <name> [--actor <name>]
  nems-userctl info           --user <name> [--json]
  nems-userctl list-roles
  nems-userctl list-users
EOF
}

get_boot_superadmin() { echo $(/usr/local/bin/nems-info username) | tr -d '\r\n'; }
have_user(){ id -u "$1" >/dev/null 2>&1; }

ensure_htpasswd(){
  if [[ ! -e "$HTPASSWD_FILE" ]]; then install -m 640 -o root -g www-data /dev/null "$HTPASSWD_FILE"; fi
  chgrp www-data "$HTPASSWD_FILE" || true
  chmod 640 "$HTPASSWD_FILE" || true
}

read_password() {
  local PW=""
  if [[ ${PASSWORD_STDIN:-0} -eq 1 ]]; then
    if IFS= read -r PW; then :; else die "No password on stdin."; fi
  elif [[ -n ${PASSWORD_FILE:-} ]]; then
    PW=$(head -n1 "$PASSWORD_FILE" 2>/dev/null || true)
    [[ -n "$PW" ]] || die "Password file empty."
  else
    die "Password not provided. Use --password-stdin or --password-file."
  fi
  printf '%s' "$PW"
}

linux_create_user(){
  local u="$1" pw="$2"
  if ! have_user "$u"; then useradd -m -s /bin/bash "$u"; echo "${u}:${pw}" | chpasswd; log "Created Linux user $u"
  else echo "${u}:${pw}" | chpasswd; log "Updated Linux password for $u"; fi
}

linux_delete_user(){ local u="$1"; if have_user "$u"; then userdel -r "$u" || die "Failed to delete Linux user $u"; log "Deleted Linux user $u"; fi; }
samba_upsert(){ local u="$1" pw="$2"; (echo "$pw"; echo "$pw") | smbpasswd -s -a "$u"; smbpasswd -e "$u" >/dev/null 2>&1 || true; log "Samba user ensured for $u"; }
samba_delete(){ local u="$1"; smbpasswd -x "$u" >/dev/null 2>&1 || true; log "Removed Samba user $u"; }
htpasswd_upsert(){ local u="$1" pw="$2"; ensure_htpasswd; echo "$pw" | htpasswd -B -i "$HTPASSWD_FILE" "$u" >/dev/null; log "htpasswd ensured for $u"; }
htpasswd_delete(){ local u="$1"; if [[ -f "$HTPASSWD_FILE" ]]; then htpasswd -D "$HTPASSWD_FILE" "$u" >/dev/null 2>&1 || true; log "Removed htpasswd entry for $u"; fi; }

set_role_groups(){
  local u="$1" role="$2"
  [[ -n ${ROLE_GROUPS[$role]:-} ]] || die "Unknown role: $role"
  local desired=(${ROLE_GROUPS[$role]})

  for g in "${desired[@]}"; do getent group "$g" >/dev/null 2>&1 || groupadd "$g"; gpasswd -a "$u" "$g" >/dev/null; done
  for g in "${MANAGED_GROUPS[@]}"; do
    if printf '%s\0' "${desired[@]}" | grep -zqx "$g"; then :; else gpasswd -d "$u" "$g" >/dev/null 2>&1 || true; fi
  done
  log "Applied role '$role' to $u"
}

ensure_db(){
  install -d -m 0755 -o www-data -g www-data "$DB_DIR"
  if [[ ! -f "$DB_FILE" ]]; then
    install -m 0600 -o root -g root /dev/null "$DB_FILE"
    sqlite3 "$DB_FILE" >/dev/null <<'SQL'
PRAGMA journal_mode=WAL;
CREATE TABLE IF NOT EXISTS users(username TEXT PRIMARY KEY, role TEXT NOT NULL, full_name TEXT, email TEXT, mobile_phone TEXT, created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL, deleted_at INTEGER);
CREATE TABLE IF NOT EXISTS user_audit(id INTEGER PRIMARY KEY, username TEXT NOT NULL, action TEXT NOT NULL, old_role TEXT, new_role TEXT, actor TEXT, ts INTEGER NOT NULL);
CREATE TABLE IF NOT EXISTS user_tokens (username TEXT PRIMARY KEY, api_token TEXT NOT NULL, FOREIGN KEY(username) REFERENCES users(username) ON DELETE CASCADE);
SQL
  else
    chmod 0600 "$DB_FILE" || true; chown root:root "$DB_FILE" || true
    # Schema upgrades (fail silently if columns already exist)
    sqlite3 "$DB_FILE" "ALTER TABLE users ADD COLUMN full_name TEXT;" 2>/dev/null || true
    sqlite3 "$DB_FILE" "ALTER TABLE users ADD COLUMN email TEXT;" 2>/dev/null || true
    sqlite3 "$DB_FILE" "ALTER TABLE users ADD COLUMN mobile_phone TEXT;" 2>/dev/null || true
  fi
}

set_superadmin_username() {
  local u="$1"
  [[ -n "$u" ]] || die "No username provided for NEMS Admin user."
  if [[ ! -f "$NEMS_CONF" ]]; then install -m 0600 -o root -g root /dev/null "$NEMS_CONF"; fi
  if grep -qE '^nemsuser=' "$NEMS_CONF"; then echo "NEMS Admin is initialized."; else printf 'nemsuser=%s\n' "$u" >> "$NEMS_CONF"; fi
}

sqlq() { local s="$1"; s=${s//\'/\'\'}; printf "'%s'" "$s"; }
sqln() { local s="${1-}"; if [[ -z "$s" ]]; then printf "NULL"; else sqlq "$s"; fi; }

db_upsert_user(){
  local u="$1" role="$2" fn="$3" em="$4" mob="$5" t; t=$(now_epoch)
  sqlite3 "$DB_FILE" \
    "INSERT INTO users(username,role,full_name,email,mobile_phone,created_at,updated_at) VALUES($(sqlq "$u"),$(sqlq "$role"),$(sqln "$fn"),$(sqln "$em"),$(sqln "$mob"),$t,$t)
     ON CONFLICT(username) DO UPDATE SET role=excluded.role, full_name=excluded.full_name, email=excluded.email, mobile_phone=excluded.mobile_phone, updated_at=$t, deleted_at=NULL;"
}

db_upsert_user_token() {
  local u="$1" token="$2"
  sqlite3 "$DB_FILE" "INSERT INTO user_tokens(username, api_token) VALUES($(sqlq "$u"), $(sqlq "$token")) ON CONFLICT(username) DO UPDATE SET api_token=excluded.api_token;" || true
}

db_touch_pass(){ local u="$1" t; t=$(now_epoch); sqlite3 "$DB_FILE" "UPDATE users SET updated_at=$t WHERE username=$(sqlq "$u");" || true; }
db_mark_deleted(){ local u="$1" t; t=$(now_epoch); sqlite3 "$DB_FILE" "UPDATE users SET deleted_at=$t, updated_at=$t WHERE username=$(sqlq "$u");" || true; }
db_audit(){ local u="$1" action="$2" old="${3-}" new="${4-}" actor="$5" t; t=$(now_epoch); sqlite3 "$DB_FILE" "INSERT INTO user_audit(username,action,old_role,new_role,actor,ts) VALUES($(sqlq "$u"),$(sqlq "$action"),$(sqln "$old"),$(sqln "$new"),$(sqlq "$actor"),$t);" || true; }
db_get_role(){ sqlite3 -noheader -batch "$DB_FILE" "SELECT role FROM users WHERE username=$(sqlq "$1") AND deleted_at IS NULL LIMIT 1;"; }

forbid_self_action(){ local target="$1"; if [[ -n "${SUDO_USER:-}" && "$SUDO_USER" == "$target" ]]; then die "Users cannot perform this action on themselves."; fi; }
prec_of(){ local r="${1:-}"; if [[ -n "$r" && -n "${ROLE_PREC[$r]:-}" ]]; then echo "${ROLE_PREC[$r]}"; else echo 0; fi; }

forbid_higher_or_equal() {
  local actor="$1" target="$2" action="$3" actor_role target_role ar tr boot_super
  actor_role="$(db_get_role "$actor")"; target_role="$(db_get_role "$target")"
  [[ -z "$actor_role" ]] && actor_role="admin"; [[ -z "$target_role" ]] && target_role="viewer"
  ar=$(prec_of "$actor_role"); tr=$(prec_of "$target_role"); boot_super="$(get_boot_superadmin)"

  if [[ "$actor" == "$target" ]]; then die "Insufficient privilege: cannot act on yourself."; fi
  if [[ -n "$boot_super" && "$target" == "$boot_super" ]]; then
    if [[ "$action" == "delete" || "$action" == "set-role" ]]; then die "Insufficient privilege: cannot $action the primary NEMS Admin account."; fi
  fi
  if [[ "$actor_role" != "superadmin" ]]; then
    if (( tr >= ar )); then die "Insufficient privilege: $actor_role cannot act on $target ($target_role)."; fi
  fi
  return 0
}

need_root; check_bins; ensure_db
ACTION="${1:-}"; [[ -z "$ACTION" ]] && { usage; exit 1; }; shift || true

USER=""; ROLE=""; FULL_NAME=""; EMAIL=""; MOBILE=""; PASSWORD_STDIN=0; PASSWORD_FILE=""; ACTOR="<system>"; JSON=0; SUPERADMIN_CREATE=0

while [[ $# -gt 0 ]]; do
  case "$1" in
    --user) USER="$2"; shift 2;;
    --role) ROLE="$2"; shift 2;;
    --full-name) FULL_NAME="$2"; shift 2;;
    --email) EMAIL="$2"; shift 2;;
    --mobile) MOBILE="$2"; shift 2;;
    --password-stdin) PASSWORD_STDIN=1; shift;;
    --password-file) PASSWORD_FILE="$2"; shift 2;;
    --actor) ACTOR="$2"; shift 2;;
    --json) JSON=1; shift;;
    --superadmin-create) SUPERADMIN_CREATE=1; shift;;
    -h|--help) usage; exit 0;;
    *) die "Unknown arg: $1";;
  esac
done

if [[ "$ACTOR" == "<system>" ]]; then
  if [[ -n "${SUDO_USER:-}" ]]; then ACTOR="$SUDO_USER"; elif [[ -n "${USER:-}" ]]; then ACTOR="$USER"; else ACTOR="root"; fi
fi

case "$ACTION" in
  create)
    [[ -n "$USER" ]] || die "--user required"
    if (( SUPERADMIN_CREATE )); then
      boot_super="$(get_boot_superadmin)"
      if [[ -n "$boot_super" && "$USER" != "$boot_super" ]]; then die "Only the configured NEMS Admin ($boot_super) may be created as superadmin."; fi
      ROLE="superadmin"; effective_role="superadmin"
    else
      effective_role="${ROLE:-viewer}"
      forbid_higher_or_equal "$ACTOR" "$USER" "create"
      actor_role="$(db_get_role "$ACTOR")"; [[ -z "$actor_role" ]] && actor_role="admin"
      actor_prec=$(prec_of "$actor_role"); new_prec=$(prec_of "$effective_role")
      if (( new_prec > actor_prec )); then die "Insufficient privilege: $actor_role cannot assign role '$effective_role'."; fi
    fi

    PW="$(read_password)"
    linux_create_user "$USER" "$PW"
    samba_upsert "$USER" "$PW"
    htpasswd_upsert "$USER" "$PW"
    set_role_groups "$USER" "$effective_role"
    db_upsert_user "$USER" "$effective_role" "$FULL_NAME" "$EMAIL" "$MOBILE"

    if [ -x "/usr/local/bin/nems-api-key" ]; then
      API_TOKEN=$(/usr/local/bin/nems-api-key create "$USER" --raw)
      if [[ -n "$API_TOKEN" ]]; then db_upsert_user_token "$USER" "$API_TOKEN"; fi
    fi

    db_audit "$USER" "create" "" "$effective_role" "$ACTOR"
    if (( SUPERADMIN_CREATE )); then set_superadmin_username "$USER"; fi
    echo "OK: created/updated user '$USER'."
  ;;

  delete)
    [[ -n "$USER" ]] || die "--user required"
    forbid_self_action "$USER"
    boot_super="$(get_boot_superadmin)"
    if [[ -n "$boot_super" && "$USER" == "$boot_super" ]]; then die "Insufficient privilege: cannot delete primary NEMS Admin."; fi
    [[ "$ACTOR" != "<system>" ]] && forbid_higher_or_equal "$ACTOR" "$USER" "delete"

    old_role="$(db_get_role "$USER")"
    htpasswd_delete "$USER"
    samba_delete "$USER"
    linux_delete_user "$USER"
    db_mark_deleted "$USER"
    sqlite3 "$DB_FILE" "DELETE FROM user_tokens WHERE username=$(sqlq "$USER");" || true
    if [ -x "/usr/local/bin/nems-api-key" ]; then /usr/local/bin/nems-api-key delete "$USER" >/dev/null 2>&1 || true; fi

    db_audit "$USER" "delete" "$old_role" "" "$ACTOR"
    echo "OK: deleted user '$USER'."
  ;;

  set-role)
    [[ -n "$USER" && -n "$ROLE" ]] || die "--user and --role required"
    have_user "$USER" || die "User $USER not found."
    actor_role="$(db_get_role "$ACTOR")"; [[ -z "$actor_role" ]] && actor_role="admin"
    actor_prec=$(prec_of "$actor_role"); new_prec=$(prec_of "$ROLE")
    if (( new_prec > actor_prec )); then die "Insufficient privilege: $actor_role cannot assign role '$ROLE'."; fi
    boot_super="$(get_boot_superadmin)"
    if [[ -n "$boot_super" && "$USER" == "$boot_super" ]]; then die "Insufficient privilege: cannot change role of primary NEMS Admin."; fi
    [[ "$ACTOR" != "<system>" ]] && forbid_higher_or_equal "$ACTOR" "$USER" "set-role"

    old_role="$(db_get_role "$USER")"
    set_role_groups "$USER" "$ROLE"
    sqlite3 "$DB_FILE" "UPDATE users SET role=$(sqlq "$ROLE") WHERE username=$(sqlq "$USER");"
    db_audit "$USER" "set-role" "$old_role" "$ROLE" "$ACTOR"
    echo "OK: role '$ROLE' applied to '$USER'."
  ;;

  update-profile)
    [[ -n "$USER" ]] || die "--user required"
    self_change=0
    if [[ -n "${SUDO_USER:-}" && "${SUDO_USER}" == "$USER" ]]; then self_change=1; fi
    if [[ "$ACTOR" == "$USER" ]]; then self_change=1; fi
    if (( self_change == 0 )); then forbid_higher_or_equal "$ACTOR" "$USER" "update-profile"; fi
    
    t=$(now_epoch)
    sqlite3 "$DB_FILE" "UPDATE users SET full_name=$(sqln "$FULL_NAME"), email=$(sqln "$EMAIL"), mobile_phone=$(sqln "$MOBILE"), updated_at=$t WHERE username=$(sqlq "$USER");"
    echo "OK: profile updated for '$USER'."
  ;;

  regen-token)
    [[ -n "$USER" ]] || die "--user required"
    self_change=0
    if [[ -n "${SUDO_USER:-}" && "${SUDO_USER}" == "$USER" ]]; then self_change=1; fi
    if [[ "$ACTOR" == "$USER" ]]; then self_change=1; fi
    if (( self_change == 0 )); then forbid_higher_or_equal "$ACTOR" "$USER" "regen-token"; fi

    if [ -x "/usr/local/bin/nems-api-key" ]; then
      API_TOKEN=$(/usr/local/bin/nems-api-key create "$USER" --raw)
      if [[ -n "$API_TOKEN" ]]; then
        db_upsert_user_token "$USER" "$API_TOKEN"
        echo "OK: token regenerated for '$USER'."
      else
        die "Failed to generate token."
      fi
    else
      die "nems-api-key utility missing."
    fi
  ;;

  set-pass)
    [[ -n "$USER" ]] || die "--user required"
    self_change=0
    if [[ -n "${SUDO_USER:-}" && "${SUDO_USER}" == "$USER" ]]; then self_change=1; fi
    if [[ "$ACTOR" == "$USER" ]]; then self_change=1; fi

    if (( self_change == 0 )); then
      forbid_higher_or_equal "$ACTOR" "$USER" "set-pass"
      boot_super="$(get_boot_superadmin)"
      if [[ -n "$boot_super" && "$USER" == "$boot_super" ]]; then
          actor_role="$(db_get_role "$ACTOR")"
          if [[ "$actor_role" != "superadmin" ]]; then die "Insufficient privilege: cannot change password for primary NEMS Admin."; fi
      fi
    fi

    PW="$(read_password)"
    echo "${USER}:${PW}" | chpasswd
    samba_upsert "$USER" "$PW"
    htpasswd_upsert "$USER" "$PW"
    db_touch_pass "$USER"
    db_audit "$USER" "set-pass" "" "" "$ACTOR"
    echo "OK: password updated for '$USER'."
  ;;

  list-roles)
    for k in "${!ROLE_GROUPS[@]}"; do echo "$k => ${ROLE_GROUPS[$k]}"; done
  ;;

  list-users)
    if [[ ! -f "$DB_FILE" ]]; then echo "[]" ; exit 0; fi
    sqlite3 -separator $'\t' "$DB_FILE" \
      "SELECT u.username, u.role, u.full_name, u.email, u.mobile_phone, u.created_at, u.updated_at, t.api_token
       FROM users u LEFT JOIN user_tokens t ON u.username = t.username
       WHERE u.deleted_at IS NULL ORDER BY u.username ASC" \
    | awk -F$'\t' 'BEGIN{print "["}
           {
             u=$1; r=$2; fn=$3; em=$4; mo=$5; ca=$6; ua=$7; tok=$8;
             has_tok = (tok != "" ? "true" : "false");
             if(NR>1) printf ",";
             printf "{\"username\":\"%s\",\"role\":\"%s\",\"full_name\":\"%s\",\"email\":\"%s\",\"mobile_phone\":\"%s\",\"created_at\":%s,\"updated_at\":%s,\"has_token\":%s}", u, r, fn, em, mo, (ca?ca:"null"), (ua?ua:"null"), has_tok
           }
           END{print "]"}'
    exit 0
  ;;

  info)
    [[ -n "$USER" ]] || die "--user required"
    if (( JSON )); then
      role="$(db_get_role "$USER")"
      created=$(sqlite3 "$DB_FILE" "SELECT created_at FROM users WHERE username=$(sqlq "$USER");")
      updated=$(sqlite3 "$DB_FILE" "SELECT updated_at FROM users WHERE username=$(sqlq "$USER");")
      deleted=$(sqlite3 "$DB_FILE" "SELECT deleted_at FROM users WHERE username=$(sqlq "$USER");")
      groups="$(id -nG "$USER" 2>/dev/null || true)"
      tok=$(sqlite3 "$DB_FILE" "SELECT api_token FROM user_tokens WHERE username=$(sqlq "$USER");")
      
      printf '{"username":"%s","role":"%s","full_name":"%s","email":"%s","mobile_phone":"%s","created_at":%s,"updated_at":%s,"deleted_at":%s,"api_token":"%s","groups":[%s]}\n' \
        "$USER" "${role:-""}" "" "" "" "${created:-null}" "${updated:-null}" "${deleted:-null}" "${tok:-""}" \
        "$(printf '%s' "$groups" | awk '{for(i=1;i<=NF;i++) printf "%s\"%s\"", (i>1?",":""), $i}')"
      exit 0
    else
      have_user "$USER" || die "User $USER not found."
      echo "User: $USER"; echo "UID: $(id -u "$USER")"; echo "Groups: $(id -nG "$USER")"
      echo "Role (DB): $(db_get_role "$USER" || true)"
      exit 0
    fi
  ;;

  *) usage; exit 1;;
esac
