#!/usr/bin/env bash
set -euo pipefail

SELF_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=/usr/local/libexec/brixcli/common.sh
source "${SELF_DIR%/bin}/libexec/brixcli/common.sh"

usage() {
  cat <<'EOF'
Usage:
  set-agent-password <agent-name> [new-password]

If no password is provided, one is generated automatically.
EOF
}

main() {
  require_root
  load_config
  ensure_runtime_dirs

  local agent="${1:-}"
  local password="${2:-}"

  [[ -n "${agent}" ]] || { usage; exit 1; }
  validate_agent_name "${agent}"
  agent_must_exist "${agent}"

  if [[ -z "${password}" ]]; then
    password="$(generate_password)"
  fi

  htpasswd -Bbc "${AUTH_DIR}/${agent}.htpasswd" "${agent}" "${password}" >/dev/null
  chmod 0644 "${AUTH_DIR}/${agent}.htpasswd"

  printf 'Updated password for %s\nUsername: %s\nPassword: %s\n' "${agent}" "${agent}" "${password}"
}

main "$@"
