#!/usr/bin/env bash
# SPDX-FileCopyrightText: OpenTalk GmbH <mail@opentalk.eu>
#
# SPDX-License-Identifier: EUPL-1.2

# filepath: devops/opentalk-compose/extras/packaging/wrappers/ot-ansible-playbook
set -euo pipefail
PREFIX="/opt/opentalk-compose"
RUNTIME="$PREFIX/runtime"
AUTOMATION="$PREFIX/automation"
VENV_BIN="$RUNTIME/venv/bin"
BIN="$VENV_BIN/ansible-playbook"
POSTINST="$PREFIX/bin/pkg-postinst.sh"
VENDOR="$RUNTIME/vendor/collections"
PORTABLE_PY="$RUNTIME/python/bin/python3"
VENV_PY="$VENV_BIN/python3"

if [ ! -x "$BIN" ] || ! head -1 "$BIN" 2>/dev/null | grep -q '^#!'; then
  if [ -x "$POSTINST" ]; then
    bash "$POSTINST"
  fi
fi
[ -x "$BIN" ] || { echo "[wrapper] ansible-playbook unavailable" >&2; exit 1; }

export PYTHONDONTWRITEBYTECODE=1
export ANSIBLE_CONFIG="${ANSIBLE_CONFIG:-$AUTOMATION/ansible.cfg}"
# Prefer venv python (has requests & dependencies); fallback to portable runtime
if [ -x "$VENV_PY" ]; then
  export ANSIBLE_PYTHON_INTERPRETER="$VENV_PY"
  # Self-heal: ensure requests import works; else rebuild venv
  if ! "$VENV_PY" -c 'import requests' 2>/dev/null; then
    echo "[wrapper] requests missing in venv - rebuilding via postinst" >&2
    if [ -x "$POSTINST" ]; then
      bash "$POSTINST"
    fi
  fi
else
  if [ -x "$PORTABLE_PY" ]; then
    export ANSIBLE_PYTHON_INTERPRETER="$PORTABLE_PY"
  fi
fi
# Inject interpreter extra var (multiple -e flags are additive in Ansible)
if [ -n "${ANSIBLE_PYTHON_INTERPRETER:-}" ]; then
  set -- -e "ansible_python_interpreter=${ANSIBLE_PYTHON_INTERPRETER}" "$@"
fi

if [ -z "${ANSIBLE_COLLECTIONS_PATHS:-}" ]; then
  cfg_paths=""
  if [ -f "$ANSIBLE_CONFIG" ]; then
    cfg_paths="$(awk -F= '/^[[:space:]]*collections_path[s]?[[:space:]]*=/{v=$2;gsub(/^[[:space:]]+|[[:space:]]+$/,"",v);print v;exit}' "$ANSIBLE_CONFIG")"
  fi
  if [ -d "$VENDOR/ansible_collections" ]; then
    case ":$cfg_paths:" in
      *":$VENDOR:"*) ANSIBLE_COLLECTIONS_PATHS="$cfg_paths" ;;
      "::") ANSIBLE_COLLECTIONS_PATHS="$VENDOR:$HOME/.ansible/collections:/usr/share/ansible/collections" ;;
      *) ANSIBLE_COLLECTIONS_PATHS="$VENDOR:$cfg_paths" ;;
    esac
  else
    [ -n "$cfg_paths" ] && ANSIBLE_COLLECTIONS_PATHS="$cfg_paths"
  fi
  [ -n "${ANSIBLE_COLLECTIONS_PATHS:-}" ] && export ANSIBLE_COLLECTIONS_PATHS
fi

exec "$BIN" "$@"