#!/bin/bash
# SPDX-License-Identifier: AGPL-3.0-only
# SPDX-FileCopyrightText: 2025 Univention GmbH

#
# ucs-backup2master-and-reinit-provisioning.sh
#
# Promotes a UCS Backup Directory Node to Primary (Master)
# and reinitializes the "provisioning" app afterwards.
#
# Usage: sudo ./ucs-backup2master-and-reinit-provisioning.sh
# Optional env:
#   APP_NAME=provisioning-service   # override if needed
#   DRY_RUN=0               # show what would run
#
set -euo pipefail

APP_NAME="${APP_NAME:-provisioning-service}"
APP_BACKEND_NAME="${APP_BACKEND_NAME:-provisioning-service-backend}"
LOG_DIR="/var/log/univention"
SCRIPT_LOG="${LOG_DIR}/backup2master_and_${APP_NAME}_post.log"
DRY_RUN="${DRY_RUN:-0}"

eval "$(univention-config-registry shell)"

exec > >(tee -a "$SCRIPT_LOG") 2>&1

echo "=== $(date -Is) :: Starting UCS Backup->Master promotion + app reinitialize (${APP_NAME}) ==="

require_cmd() {
  if ! command -v "$1" >/dev/null 2>&1; then
    echo "ERROR: Required command '$1' not found in PATH." >&2
    exit 1
  fi
}
red="$(tput setaf 1)"
# green="$(tput setaf 2)"
orange="$(tput setaf 3)"
blue="$(tput setaf 4)"
op="$(tput op)"

echo-warning () {
    echo "${orange}$*${op}"
}
echo-error () {
    echo "${red}$*${op}"
}
echo-success () {
    echo "${green}$*${op}"
}
run() {
  if [[ "$DRY_RUN" == "1" ]]; then
    echo "[DRY-RUN] $*"
  else
    echo "+ $*"
    eval "$@"
  fi
}

# --- Pre-flight checks ---
require_cmd ucr
require_cmd univention-app
require_cmd univention-run-join-scripts

# --- Check installed apps ---

# --- Check APP_NAME is installed and backend not yet installed ---
if ! univention-app info | grep -P '^(?=.*\bprovisioning-service=[^ ]+\b).*' > /dev/null; then
  echo "ERROR: App '${APP_NAME}' not installed." >&2
  exit 1
fi


# --- Check current server role ---
ROLE="$(ucr get server/role)"
if [[ -z "$ROLE" ]]; then
  echo "ERROR: Could not determine UCS server role via UCR." >&2
  exit 1
fi
echo "Detected server role: ${ROLE}"

if [[ "$ROLE" != "domaincontroller_master" ]]; then
  echo "ERROR: This system is not a Master Directory Node (found: ${ROLE}). Aborting."
  exit 1
fi

# --- App Center cache refresh (harmless) ---
echo "Refreshing App Center cache..."
run "univention-app update"

# --- Listener activation ---
echo "Activating ${APP_NAME} listener module"
ucr unset listener/module/nubus-provisioning/deactivate
systemctl restart univention-directory-listener.service
systemctl restart stunnel4.service

# Reinitialize: this recreates the app container with current settings.
# This is supported by the App Center and is commonly used by several UCS apps
# to apply updated configuration. (See docs and forum references.)

echo "Reinitializing ${APP_NAME}..."

run "univention-app configure ${APP_NAME} --set provisioning-service/udm-rest-api-host=\"$ldap_master\" --set provisioning-service/primary=\"$ldap_master\""

echo-warning "WARNING: Please do the following on all other backups where the provisioning-service app is installed."
echo-warning "    univention-app configure ${APP_NAME} --set provisioning-service/udm-rest-api-host=<REPLACE_ME> --set provisioning-service/primary=<REPLACE_ME>"
echo-warning "    systemctl restart stunnel4.service"

echo "=== $(date -Is) :: Completed. Log: ${SCRIPT_LOG} ==="
