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

restart_runtime=false
case "$#" in
  0) ;;
  1)
    case "$1" in
      --verify) exec "$(dirname "$0")/verify_worker.sh" ;;
      --restart-runtime) restart_runtime=true ;;
      *)
        echo "Usage: $0 [--verify|--restart-runtime]" >&2
        exit 2
        ;;
    esac
    ;;
  *)
    echo "Usage: $0 [--verify|--restart-runtime]" >&2
    exit 2
    ;;
esac

bee_release="${BEE_RELEASE_DIR:-/var/www/releases/bee}"
bot_release="${BOT_RELEASE_DIR:-/opt/razgar-bot}"
registry_url="${WORKER_REGISTRY_URL:-}"
worker_id="${BEE_WORKER_ID:?BEE_WORKER_ID is required}"
worker_generation="${BEE_WORKER_GENERATION:?BEE_WORKER_GENERATION is required}"
worker_api_cors_allowed_urls="${WORKER_API_CORS_ALLOWED_URLS:-https://bee-app.razgar.io}"
runtime_env="${BEE_RUNTIME_ENV_FILE:-/opt/.env}"
worker_env="${BEE_WORKER_ENV_FILE:-/etc/razgar/bee-worker.env}"
web_root="${BEE_WEB_ROOT:-/var/www/html}"
worker_bee_url="${WORKER_BEE_URL:-http://127.0.0.1:8080/api}"
worker_bee_indicators_url="${WORKER_BEE_INDICATORS_URL:-http://127.0.0.1:8080/api/ind}"
worker_private_health_url="${WORKER_PRIVATE_HEALTH_URL:-https://bee-app.razgar.io/api/private/health.php}"
worker_private_health_resolve="${WORKER_PRIVATE_HEALTH_RESOLVE:?WORKER_PRIVATE_HEALTH_RESOLVE is required}"
worker_test_log_dir="${WORKER_TEST_LOG_DIR:-/var/log/bee_logs}"
worker_bot_log_dir="${WORKER_BOT_LOG_DIR:-/var/log/bot_logs}"
bot_python="${BOT_PYTHON_EXECUTABLE:-/opt/razgar-bot-venv/bin/python}"
deploy_root="$(cd "$(dirname "$0")/.." && pwd)"

require_file() {
  [[ -f "$1" ]] || { echo "Missing required file: $1" >&2; exit 1; }
}

# Maintenance rollouts leave active runtime services alone. Full worker
# activation must explicitly opt in after the maintenance artifacts are ready.
restart_worker_runtime() {
  rm -f /run/razgar/bee-data-handler.ready /run/razgar/bee-ws.ready
  systemctl restart bee_data_handler.service
  systemctl restart bee_websocket_server.service
  systemctl restart bot_management_api.service
}

require_file "$bee_release/init.inc.php"
require_file "$bee_release/bee-runtime-manifest.json"
require_file "$bot_release/runtime-manifest.json"
require_file "$bot_release/bot/endpoints/bot_management/bot_api.py"
require_file "$runtime_env"
require_file "$deploy_root/logrotate/razgar-bee"
require_file "$deploy_root/logrotate/apache2"
require_file "$deploy_root/maintenance/prune_bee_diagnostic_logs.sh"
require_file "$deploy_root/systemd/razgar-logrotate.service"
require_file "$deploy_root/systemd/razgar-logrotate.timer"
require_file "$deploy_root/systemd/razgar-bee-log-maintenance.service"
require_file "$deploy_root/systemd/razgar-bee-log-maintenance.timer"
[[ -x "$bot_python" ]] || { echo "Bot Python executable is unavailable: $bot_python" >&2; exit 1; }

[[ "$(id -u)" -eq 0 ]] || { echo "Run installer as root." >&2; exit 1; }
if ! command -v logrotate >/dev/null 2>&1; then
  apt-get install -y logrotate
fi
[[ -x /usr/sbin/logrotate ]] || {
  echo "/usr/sbin/logrotate is required after provisioning." >&2
  exit 1
}
set -a
source "$runtime_env"
set +a
if [[ -f "$worker_env" ]]; then
  set -a
  source "$worker_env"
  set +a
fi
mtls_cert_file="${BEE_MTLS_CERT_FILE:-${BEE_MTLS_CERT_PATH:-}}"
mtls_key_file="${BEE_MTLS_KEY_FILE:-${BEE_MTLS_KEY_PATH:-}}"
mtls_ca_file="${BEE_MTLS_CA_FILE:-${BEE_MTLS_CLIENT_CA_PATH:-}}"
require_file "$mtls_cert_file"
require_file "$mtls_key_file"
require_file "$mtls_ca_file"
for secret_name in BEE_SERVICE_HMAC_KEY BOT_SERVICE_HMAC_KEY; do
  secret_value="${!secret_name:-}"
  if [[ ${#secret_value} -lt 32 || "$secret_value" == *$'\r'* || "$secret_value" == *$'\n'* ]]; then
    echo "$secret_name must contain at least 32 bytes without control characters." >&2
    exit 1
  fi
done
if [[ -z "${FERNET_KEY:-}" || "$FERNET_KEY" == *$'\r'* || "$FERNET_KEY" == *$'\n'* ]]; then
  echo "FERNET_KEY is required and must not contain control characters." >&2
  exit 1
fi
env FERNET_KEY="$FERNET_KEY" "$bot_python" - <<'PY'
import os
from cryptography.fernet import Fernet

Fernet(os.environ["FERNET_KEY"].encode())
PY
chown root:www-data "$bot_release/runtime-manifest.json"
chmod 0640 "$bot_release/runtime-manifest.json"
install -d -m 0755 /run/razgar
install -d -m 0750 -o root -g www-data /etc/razgar
install -d -m 0770 -o www-data -g www-data "$worker_test_log_dir" "$worker_bot_log_dir"
loopback_site=/etc/apache2/sites-available/bee-worker-loopback.conf
loopback_site_source="$(dirname "$0")/apache/bee-worker-loopback.conf"
require_file "$loopback_site_source"
install -m 0644 "$loopback_site_source" "$loopback_site"
a2ensite bee-worker-loopback.conf >/dev/null
apache2ctl configtest
systemctl reload apache2
[[ ! -e /opt/razgar-bot.next || -L /opt/razgar-bot.next ]] || {
  echo '/opt/razgar-bot.next exists and is not a symlink.' >&2
  exit 1
}
rm -f /opt/razgar-bot.next
ln -s "$bot_release" /opt/razgar-bot.next
mv -Tf /opt/razgar-bot.next /opt/razgar-bot
bee_manifest="$bee_release/bee-runtime-manifest.json"
bee_runtime_sha256="$(sha256sum "$bee_manifest" | awk '{print $1}')"
umask 027
cat > /etc/razgar/bee-worker.env <<EOF
BEE_TEST_API_URL=http://127.0.0.1:8080
BEE_URL=$worker_bee_url
BEE_INDICATORS_URL=$worker_bee_indicators_url
BEE_PRIVATE_HEALTH_URL=$worker_private_health_url
BEE_PRIVATE_HEALTH_RESOLVE=$worker_private_health_resolve
TEST_LOG_FILES_LOCATION=$worker_test_log_dir
BOT_LOG_FILES_LOCATION=$worker_bot_log_dir
BOT_PYTHON_EXECUTABLE=$bot_python
BOT_RUNTIME_MANIFEST=$bot_release/runtime-manifest.json
BOT_RUN_COMMAND=$bot_release
BEE_RUNTIME_MANIFEST=$bee_manifest
BEE_RUNTIME_SHA256=$bee_runtime_sha256
BEE_WORKER_ID=$worker_id
BEE_WORKER_GENERATION=$worker_generation
BEE_MTLS_CERT_FILE=$mtls_cert_file
BEE_MTLS_KEY_FILE=$mtls_key_file
BEE_MTLS_CA_FILE=$mtls_ca_file
BEE_MTLS_CERT_PATH=$mtls_cert_file
BEE_MTLS_KEY_PATH=$mtls_key_file
BEE_MTLS_CLIENT_CA_PATH=$mtls_ca_file
BOT_HOST_ID=bee-worker-$worker_id
API_CORS_ALLOWED_URLS=$worker_api_cors_allowed_urls
EOF
chown root:www-data /etc/razgar/bee-worker.env
chmod 0640 /etc/razgar/bee-worker.env
[[ -L "$web_root" ]] || { echo "$web_root must be a symlink before release activation." >&2; exit 1; }
[[ ! -e "$web_root.next" || -L "$web_root.next" ]] || {
  echo "$web_root.next exists and is not a symlink." >&2
  exit 1
}
rm -f "$web_root.next"
ln -s "$bee_release" "$web_root.next"
mv -Tf "$web_root.next" "$web_root"
install -m 0644 "$(dirname "$0")/../systemd/bee_data_handler.service" /etc/systemd/system/bee_data_handler.service
install -m 0644 "$(dirname "$0")/../systemd/bee_websocket_server.service" /etc/systemd/system/bee_websocket_server.service
install -m 0644 "$(dirname "$0")/../systemd/bot_management_api.service" /etc/systemd/system/bot_management_api.service
install -d -m 0755 /etc/logrotate.d
install -d -m 0700 /var/lib/razgar/logrotate-backups
if [[ -f /etc/logrotate.d/razgar-bee ]]; then
  install -m 0600 /etc/logrotate.d/razgar-bee "/var/lib/razgar/logrotate-backups/razgar-bee.$(date -u +%Y%m%dT%H%M%SZ)"
fi
install -m 0644 "$deploy_root/logrotate/razgar-bee" /etc/logrotate.d/razgar-bee
install -m 0644 "$deploy_root/logrotate/apache2" /etc/logrotate.d/apache2
install -m 0755 "$deploy_root/maintenance/prune_bee_diagnostic_logs.sh" /usr/local/sbin/prune_bee_diagnostic_logs.sh
install -m 0644 "$deploy_root/systemd/razgar-logrotate.service" /etc/systemd/system/razgar-logrotate.service
install -m 0644 "$deploy_root/systemd/razgar-logrotate.timer" /etc/systemd/system/razgar-logrotate.timer
install -m 0644 "$deploy_root/systemd/razgar-bee-log-maintenance.service" /etc/systemd/system/razgar-bee-log-maintenance.service
install -m 0644 "$deploy_root/systemd/razgar-bee-log-maintenance.timer" /etc/systemd/system/razgar-bee-log-maintenance.timer
systemctl daemon-reload
systemctl enable bee_data_handler.service bee_websocket_server.service bot_management_api.service >/dev/null
package_timer="$(systemctl list-unit-files --type=timer --no-legend --no-pager logrotate.timer)"
if [[ "$package_timer" == logrotate.timer* ]]; then
  systemctl disable --now logrotate.timer
fi
if [[ -e /etc/cron.daily/logrotate ]]; then
  dpkg-divert --local --rename --add /etc/cron.daily/logrotate
fi
systemctl enable --now razgar-logrotate.timer >/dev/null
systemctl enable --now razgar-bee-log-maintenance.timer >/dev/null
if [[ "$restart_runtime" == true ]]; then
  restart_worker_runtime
fi

if [[ -n "$registry_url" ]]; then
  curl --fail --silent --show-error --request POST "$registry_url" \
    --header 'Content-Type: application/json' \
    --data '{"state":"provisioning"}' >/dev/null
fi

echo "Worker installed in provisioning state; verification does not enable scheduling."
