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

# Shared helper to load Argus build user/group configuration.
# Usage:
#   source "${PROJECT_ROOT}/scripts/common/build_user.sh"
#   load_build_user
#   echo "$ARGUS_BUILD_UID:$ARGUS_BUILD_GID"

ARGUS_BUILD_UID_DEFAULT=2133
ARGUS_BUILD_GID_DEFAULT=2015

shopt -s extglob

_ARGUS_BUILD_USER_LOADED="${_ARGUS_BUILD_USER_LOADED:-0}"

_argus_build_user_script_dir() {
  local dir
  dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
  echo "$dir"
}

argus_project_root() {
  local script_dir
  script_dir="$(_argus_build_user_script_dir)"
  (cd "$script_dir/../.." >/dev/null && pwd)
}

_argus_trim() {
  local value="$1"
  value="${value##+([[:space:]])}"
  value="${value%%+([[:space:]])}"
  printf '%s' "$value"
}

_argus_is_number() {
  [[ "$1" =~ ^[0-9]+$ ]]
}

load_build_user() {
  if [[ "$_ARGUS_BUILD_USER_LOADED" == "1" ]]; then
    return 0
  fi

  local project_root config_files config uid gid
  project_root="$(argus_project_root)"
  config_files=(
    "$project_root/configs/build_user.local.conf"
    "$project_root/configs/build_user.conf"
  )

  uid="$ARGUS_BUILD_UID_DEFAULT"
  gid="$ARGUS_BUILD_GID_DEFAULT"

  for config in "${config_files[@]}"; do
    if [[ -f "$config" ]]; then
      while IFS= read -r raw_line || [[ -n "$raw_line" ]]; do
        local line key value
        line="${raw_line%%#*}"
        line="$(_argus_trim "${line}")"
        [[ -z "$line" ]] && continue
        if [[ "$line" != *=* ]]; then
          echo "[ARGUS build_user] Ignoring malformed line in $config: $raw_line" >&2
          continue
        fi
        key="${line%%=*}"
        value="${line#*=}"
        key="$(_argus_trim "$key")"
        value="$(_argus_trim "$value")"
        case "$key" in
          UID)
            uid="$value"
            ;;
          GID)
            gid="$value"
            ;;
          *)
            echo "[ARGUS build_user] Unknown key '$key' in $config" >&2
            ;;
        esac
      done < "$config"
      break
    fi
  done

  if [[ -n "${ARGUS_BUILD_UID:-}" ]]; then
    uid="$ARGUS_BUILD_UID"
  fi
  if [[ -n "${ARGUS_BUILD_GID:-}" ]]; then
    gid="$ARGUS_BUILD_GID"
  fi

  if ! _argus_is_number "$uid"; then
    echo "[ARGUS build_user] Invalid UID '$uid'" >&2
    return 1
  fi
  if ! _argus_is_number "$gid"; then
    echo "[ARGUS build_user] Invalid GID '$gid'" >&2
    return 1
  fi

  export ARGUS_BUILD_UID="$uid"
  export ARGUS_BUILD_GID="$gid"
  _ARGUS_BUILD_USER_LOADED=1
}

argus_build_user_args() {
  load_build_user
  printf '%s' "--build-arg ARGUS_BUILD_UID=${ARGUS_BUILD_UID} --build-arg ARGUS_BUILD_GID=${ARGUS_BUILD_GID}"
}

print_build_user() {
  load_build_user
  echo "ARGUS build user: UID=${ARGUS_BUILD_UID} GID=${ARGUS_BUILD_GID}"
}
