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

KEY_DIR="/etc/etharbooking"
KEY_FILE="$KEY_DIR/ai_encryption.key"
WEB_GROUP="${ETHAR_WEB_GROUP:-www-data}"

if [[ "${EUID}" -ne 0 ]]; then
  echo "ERROR: run this script as root: sudo bash install_ai_encryption_key.sh" >&2
  exit 1
fi

if ! getent group "$WEB_GROUP" >/dev/null; then
  echo "ERROR: web-server group '$WEB_GROUP' was not found." >&2
  echo "Set ETHAR_WEB_GROUP to the group used by Apache/PHP-FPM." >&2
  exit 1
fi

if ! command -v openssl >/dev/null 2>&1; then
  echo "ERROR: openssl is required." >&2
  exit 1
fi

install -d -o root -g "$WEB_GROUP" -m 0750 "$KEY_DIR"

if [[ -e "$KEY_FILE" || -L "$KEY_FILE" ]]; then
  if [[ -L "$KEY_FILE" || ! -f "$KEY_FILE" ]]; then
    echo "ERROR: existing key path is not a regular file; refusing to replace it." >&2
    exit 1
  fi
  if [[ "$(wc -c < "$KEY_FILE")" -lt 32 ]]; then
    echo "ERROR: existing key file is shorter than 32 bytes; refusing to replace it." >&2
    exit 1
  fi
  chown root:"$WEB_GROUP" "$KEY_FILE"
  chmod 0640 "$KEY_FILE"
  echo "Existing encryption key preserved; permissions secured."
else
  TMP_FILE="$(mktemp "$KEY_DIR/.ai_encryption.key.XXXXXX")"
  trap 'rm -f "$TMP_FILE"' EXIT
  openssl rand -hex 32 > "$TMP_FILE"
  chown root:"$WEB_GROUP" "$TMP_FILE"
  chmod 0640 "$TMP_FILE"
  mv -n "$TMP_FILE" "$KEY_FILE"
  if [[ -e "$TMP_FILE" ]]; then
    echo "ERROR: another process created the key file concurrently; no existing key was overwritten." >&2
    exit 1
  fi
  trap - EXIT
  echo "A new encryption key was created. Its value was not displayed."
fi

echo "Key file: $KEY_FILE"
echo "Permissions: root:$WEB_GROUP, mode 0640; directory mode 0750."
echo "Check PHP access with: sudo -u www-data test -r '$KEY_FILE' && echo OK"
echo "Back up this file securely. Losing it makes saved provider keys undecryptable."
