#!/bin/bash
set -euo pipefail

# Idempotent: safe to re-run — skips existing users, refreshes SSH keys

echo "=== Setting up TF Users ==="

DEBIAN_FRONTEND=noninteractive apt-get install -y zsh >/dev/null 2>&1

add_user() {
  local username="$1"
  local fullname="$2"
  local shell="$3"
  local github_user="$4"

  if id "$username" &>/dev/null; then
    echo "[OK] User '$username' already exists"
  else
    useradd -m -G sudo -s "$shell" \
      -p '$6$w6py6llD3P4FgJR4$EzDQ9yIrpNDskKLAPUQrsBqVnDeBbVaeOzRyJp2R8k7L8IC7SjZEXFYyhxywS7J9r5uw/tB1korefeEbJjUS31' \
      -c "$fullname" "$username"
    echo "[OK] Created user '$username'"
  fi

  mkdir -p "/home/$username/.ssh"
  chmod 700 "/home/$username/.ssh"

  # Refresh SSH keys from GitHub
  if wget -qO "/home/$username/.ssh/authorized_keys" "https://github.com/${github_user}.keys" 2>/dev/null; then
    chmod 600 "/home/$username/.ssh/authorized_keys"
    echo "[OK] Updated SSH keys for '$username' from github.com/${github_user}"
  else
    echo "[WARN] Could not fetch SSH keys for '$username' from github.com/${github_user}"
  fi

  chown -R "$username:$username" "/home/$username/.ssh"
}

add_user "delandtj" "Jan De Landtsheer" "/usr/bin/zsh" "delandtj"
add_user "lee"      "Lee Smet"          "/usr/bin/zsh" "LeeSmet"
add_user "nashaatp" "Peter Nashaat"     "/bin/bash"    "PeterNashaat"
add_user "hossnys"  "Samir Hossny"      "/bin/bash"    "hossnys"
add_user "nazmya"   "Atef Nazmy"        "/bin/bash"    "atefnazmy"
echo ""
echo "[OK] TF Users setup complete"
