#!/bin/sh
# Ephemeral RSSH bastion users (Match User ra-* in sshd_config.d/ra.conf).
# Usage: rssh_bastion_user.sh add|remove USERNAME [PASSWORD]
set -eu

ACTION="${1:-}"
USER="${2:-}"
PASS="${3:-}"

die() {
  echo "rssh_bastion_user: $*" >&2
  exit 1
}

validate_user() {
  case "$USER" in
    ra-*)
      return 0
      ;;
    *)
      die "invalid username (expected ra-* prefix)"
      ;;
  esac
}

cmd_add() {
  validate_user
  [ -n "$PASS" ] || die "password required for add"
  if id "$USER" >/dev/null 2>&1; then
    echo "$USER:$PASS" | chpasswd
    exit 0
  fi
  if command -v adduser >/dev/null 2>&1; then
    adduser -D -h /dev/null -s /bin/sh "$USER"
  elif command -v useradd >/dev/null 2>&1; then
    useradd -M -s /bin/sh "$USER"
  else
    die "no adduser/useradd"
  fi
  echo "$USER:$PASS" | chpasswd
}

cmd_remove() {
  validate_user
  if ! id "$USER" >/dev/null 2>&1; then
    exit 0
  fi
  if command -v deluser >/dev/null 2>&1; then
    deluser "$USER" 2>/dev/null || true
  elif command -v userdel >/dev/null 2>&1; then
    userdel "$USER" 2>/dev/null || true
  fi
}

case "$ACTION" in
  add) cmd_add ;;
  remove) cmd_remove ;;
  *) die "usage: $0 add|remove USERNAME [PASSWORD]" ;;
esac
