#!/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:
  create-agent <agent-name> [--password <password>]

Examples:
  create-agent agent7
  create-agent agent7 --password 'supersecret'
EOF
}

main() {
  require_root
  load_config
  ensure_runtime_dirs

  local agent=""
  local password=""

  while [[ $# -gt 0 ]]; do
    case "$1" in
      --password)
        shift
        [[ $# -gt 0 ]] || die "missing value for --password"
        password="$1"
        ;;
      -h|--help)
        usage
        exit 0
        ;;
      *)
        [[ -z "${agent}" ]] || die "unexpected argument: $1"
        agent="$1"
        ;;
    esac
    shift
  done

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

  if user_exists "${agent}" || agent_exists_in_db "${agent}"; then
    die "agent '${agent}' already exists"
  fi

  local port
  port="$(next_free_port)"

  useradd --create-home --home-dir "/home/${agent}" --shell "${AGENT_DEFAULT_SHELL}" "${agent}"

  copy_skeleton "${agent}"

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

  printf '%s:%s:%s\n' "${agent}" "${port}" "$(date -Iseconds)" >>"${AGENTS_DB}"
  printf 'PORT=%s\n' "${port}" >"${AGENTS_DIR}/${agent}.env"
  chmod 0644 "${AGENTS_DIR}/${agent}.env"

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

  rebuild_nginx_map
  rebuild_index

  systemctl daemon-reload
  systemctl enable --now "brixcli-session@${agent}.service"
  systemctl enable --now "brixcli-agent@${agent}.service"

  reload_nginx

  cat <<EOF
Created agent: ${agent}
Linux user:    ${agent}
Home:          /home/${agent}
Port:          ${port}
URL:           ${EXTERNAL_SCHEME}://${agent}.${DOMAIN}
Username:      ${agent}
Password:      ${password}

The terminal should now be live.
EOF
}

main "$@"
