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

GITLAB_URL="https://gitlab.yesplatt.de"
MAIN_REPO_PATH="yesplatt/core.git"
GITLAB_APPLICATIONS_GROUP="yesplatt/plugins/applications"
GITLAB_EXTENSIONS_GROUP="yesplatt/plugins/extensions"

# APPLICATION_PLUGINS und ADDON_PLUGINS werden nicht mehr hart codiert,
# sondern zur Laufzeit per GitLab-API befüllt (siehe fetch_group_plugins()
# und den Start-Abschnitt weiter unten).
APPLICATION_PLUGINS=()
ADDON_PLUGINS=()

fail() {
  echo "$1" >&2
  exit 1
}

 cleanleave() {
  clear
  echo
  echo "$1" >&2
  echo
  exit 1
 }

check_prerequisites() {
  local missing=()
  local cmd

  for cmd in "$@"; do
    command -v "$cmd" >/dev/null 2>&1 || missing+=("$cmd")
  done

  if [[ "${#missing[@]}" -gt 0 ]]; then
    local list
    list="$(printf -- '- %s\n' "${missing[@]}")"
    fail "Es fehlen folgende Voraussetzungen:
${list}
Bitte installieren Sie diese und starten Sie das Skript erneut."
  fi
}

ui_msg() {
  local title="$1"
  local text="$2"
  dialog --title "$title" --msgbox "$text" 20 80
}

ui_textbox() {
    local title="$1"
    local text="$2"
    local tmpfile
    tmpfile="$(mktemp)"
    printf '%s' "$text" > "$tmpfile"
    dialog --title "$title" --textbox "$tmpfile" 20 80
    local rc=$?
    rm -f "$tmpfile"
    return $rc
}

ui_confirm() {
    local title="$1"
    local text="$2"
    dialog \
        --title "$title" \
        --yes-label "Weiter" \
        --no-label "Abbrechen" \
        --yesno "$text" 20 80
}

ui_input() {
  local title="$1"
  local text="$2"
  local default="${3:-}"
  dialog --title "$title" --inputbox "$text" 10 80 "$default" 3>&1 1>&2 2>&3
}

ui_password() {
  local title="$1"
  local text="$2"
  dialog --title "$title" --passwordbox "$text" 10 80 3>&1 1>&2 2>&3
}

ui_menu() {
  local title="$1"
  local text="$2"
  shift 2
  dialog --title "$title" --menu "$text" 20 90 10 "$@" 3>&1 1>&2 2>&3
}

ui_checklist() {
  local title="$1"
  local text="$2"
  shift 2
  dialog --title "$title" --checklist "$text" 20 90 10 "$@" 3>&1 1>&2 2>&3
}

urlencode() {
  local raw="$1"
  local length="${#raw}"
  local i c

  for ((i = 0; i < length; i++)); do
    c="${raw:i:1}"
    case "$c" in
      [a-zA-Z0-9.~_-]) printf '%s' "$c" ;;
      *) printf '%%%02X' "'$c" ;;
    esac
  done
}

build_git_url() {
  local repo_path="$1"
  local host

  host="${GITLAB_URL#https://}"
  host="${host#http://}"
  host="${host%/}"

  printf 'https://%s/%s' "$host" "$repo_path"
}

detect_apache_owner() {
  # Debian/Ubuntu Standard
  if id www-data >/dev/null 2>&1 && getent group www-data >/dev/null 2>&1; then
    echo "www-data:www-data"
    return 0
  fi

  # openSUSE/SLES Standard
  if id wwwrun >/dev/null 2>&1 && getent group www >/dev/null 2>&1; then
    echo "wwwrun:www"
    return 0
  fi

  # Homebrew-Apache (macOS): hat Vorrang vor dem System-Apache, falls
  # beide installiert sind, da Homebrew-httpd das für lokale Installationen
  # vorgesehene ist. Wird über die Konfigurationsdatei erkannt, damit es
  # auch greift, wenn der Homebrew-Apache (noch) nicht läuft.
  if command -v brew >/dev/null 2>&1; then
    local brew_httpd_conf
    brew_httpd_conf="$(brew --prefix 2>/dev/null)/etc/httpd/httpd.conf"

    if [[ -f "$brew_httpd_conf" ]]; then
      local brew_user brew_group
      brew_user="$(awk '/^[[:space:]]*User[[:space:]]/ {print $2; exit}' "$brew_httpd_conf")"
      brew_group="$(awk '/^[[:space:]]*Group[[:space:]]/ {print $2; exit}' "$brew_httpd_conf")"

      if [[ -n "$brew_user" && -n "$brew_group" ]] && id "$brew_user" >/dev/null 2>&1; then
        echo "$brew_user:$brew_group"
        return 0
      fi
    fi
  fi

  # Versuch über laufenden Apache-Prozess
  local apache_user
  apache_user="$(ps -eo user,comm | awk '$2 ~ /^(apache2|httpd)$/ && $1 != "root" {print $1; exit}')"

  if [[ -n "$apache_user" ]]; then
    local apache_group
    apache_group="$(id -gn "$apache_user" 2>/dev/null || true)"

    if [[ -n "$apache_group" ]]; then
      echo "$apache_user:$apache_group"
      return 0
    fi
  fi

  return 1
}

clone_and_fetch() {
  local repo_path="$1"
  local target="$2"
  local cred_file host clone_url

  host="${GITLAB_URL#https://}"
  host="${host#http://}"
  host="${host%/}"

  cred_file="$(mktemp)"
  chmod 600 "$cred_file"
  printf 'https://%s:%s@%s\n' "$GIT_USER" "$GIT_TOKEN" "$host" > "$cred_file"

  clone_url="https://${host}/${repo_path}"

  git -c "credential.helper=store --file=${cred_file}" clone "$clone_url" "$target"
  git -C "$target" -c "credential.helper=store --file=${cred_file}" fetch

  rm -f "$cred_file"
}

# Gibt den HTTP-Statuscode auf stdout zurueck (per Caller via Command-Substitution
# auslesbar) und schreibt den Response-Body in die vom Aufrufer uebergebene Datei.
# Bewusst KEIN globales GITLAB_API_HTTP_CODE mehr: wird diese Funktion selbst per
# "x=$(gitlab_api_get ...)" aufgerufen, laeuft sie in einer Subshell - Aenderungen an
# globalen Variablen darin gehen beim Verlassen der Subshell verloren.
gitlab_api_get() {
  local api_path="$1"
  local body_file="$2"
  local host url http_code rc

  host="${GITLAB_URL#https://}"
  host="${host#http://}"
  host="${host%/}"
  url="https://${host}/api/v4${api_path}"

  http_code="$(curl -sS -w '%{http_code}' -o "$body_file" \
    --connect-timeout 10 -H "PRIVATE-TOKEN: ${GIT_TOKEN}" "$url" 2>/dev/null)"
  rc=$?

  if [[ $rc -ne 0 ]]; then
    printf '000'
    return 1
  fi

  printf '%s' "$http_code"

  [[ "$http_code" == "200" ]]
}

fetch_group_plugins() {
  local group_path="$1"
  local prefix page body_file http_code rc page_count

  # Die meisten Zugangsdaten sind nur auf einzelne Projekte innerhalb der
  # Gruppen freigegeben, nicht auf die Gruppen selbst - "/groups/:id/projects"
  # liefert dann faelschlich 404, obwohl einzelne Projekte sichtbar waeren.
  # Daher ueber die eigenen Projekt-Mitgliedschaften gehen und clientseitig
  # nach group_path filtern - inklusive beliebig tief verschachtelter
  # Untergruppen (reiner Praefixvergleich auf path_with_namespace).
  prefix="${group_path}/"
  page=1

  while true; do
    body_file="$(mktemp)"
    http_code="$(gitlab_api_get "/projects?membership=true&per_page=100&archived=false&order_by=name&sort=asc&page=${page}" "$body_file")"
    rc=$?

    if [[ $rc -ne 0 ]]; then
      echo "Warnung: GitLab-API-Fehler beim Abruf der Projekt-Mitgliedschaften (HTTP ${http_code})." >&2
      rm -f "$body_file"
      return 1
    fi

    page_count="$(jq 'length' "$body_file")"
    if [[ $? -ne 0 ]]; then
      echo "Warnung: Ungültige API-Antwort beim Abruf der Projekt-Mitgliedschaften." >&2
      rm -f "$body_file"
      return 1
    fi

    if [[ "$page_count" -eq 0 ]]; then
      rm -f "$body_file"
      break
    fi

    jq -r --arg prefix "$prefix" '
      .[] as $p |
      ($p.path_with_namespace) as $path |
      select($path | startswith($prefix)) |
      (($p.description // "") | if length == 0 then $p.name else . end) as $raw |
      ($raw | gsub("[|\r\n]"; "/")) as $plugin_label |
      "\($plugin_label)|\($path).git|\($p.path)"
    ' "$body_file"

    rm -f "$body_file"

    [[ "$page_count" -lt 100 ]] && break
    ((page++))
  done
}

check_duplicate_folders() {
  local group_label="$1"
  shift
  local plugin folder
  local -A seen=()

  for plugin in "$@"; do
    IFS='|' read -r _ _ folder <<< "$plugin"
    if [[ -n "${seen[$folder]:-}" ]]; then
      cleanleave "Mehrdeutiger Ordnername '${folder}' durch mehrere Projekte in Untergruppen von '${group_label}'. Installation abgebrochen."
    fi
    seen[$folder]=1
  done
}

select_application_plugin() {
  local options=()
  local i=1

  for plugin in "${APPLICATION_PLUGINS[@]}"; do
    IFS='|' read -r label repo folder <<< "$plugin"
    options+=("$i" "$label")
    ((i++))
  done

  local result
  result="$(ui_menu "Anwendung" "Welche Anwendung soll installiert werden?" "${options[@]}")" \
    || cleanleave "Es muss genau eine Anwendung ausgewählt werden."

  SELECTED_APPLICATION_PLUGIN="${APPLICATION_PLUGINS[$((result-1))]}"
}

select_addon_plugins() {
  SELECTED_ADDON_PLUGINS=()

  local options=()
  local i=1

  for plugin in "${ADDON_PLUGINS[@]}"; do
    IFS='|' read -r label repo folder <<< "$plugin"
    options+=("$i" "$label" "OFF")
    ((i++))
  done

  local result
  result="$(ui_checklist "Addons" "Welche Addons sollen zusätzlich installiert werden?" "${options[@]}")" \
    || cleanleave "Installation durch Benutzer abgebrochen."

  for n in $result; do
    n="${n//\"/}"
    [[ -n "$n" ]] || continue
    SELECTED_ADDON_PLUGINS+=("${ADDON_PLUGINS[$((n-1))]}")
  done
}

replace_placeholder() {
  local placeholder="$1"
  local value="$2"
  local file="$3"
  local escaped tmpfile
  escaped="$(printf '%s' "$value" | sed 's/[|\/&]/\\&/g')"
  tmpfile="$(mktemp)"
  sed "s|{$placeholder}|$escaped|g" "$file" > "$tmpfile"
  cat "$tmpfile" > "$file"
  rm -f "$tmpfile"
}

test_db_connection() {
  local cnf
  cnf="$(mktemp)"
  chmod 600 "$cnf"
  printf '[client]\nhost=%s\nuser=%s\npassword=%s\ndatabase=%s\n' \
    "$DB_HOST" "$DB_USER" "$DB_PASSWORD" "$DB_DATABASE" > "$cnf"

  mysql --defaults-file="$cnf" --execute="SELECT 1;" >/dev/null 2>&1
  local rc=$?
  rm -f "$cnf"
  return $rc
}

ui_git_credentials() {

  while true; do

    result="$(dialog --colors --title "Git-Zugang" --mixedform "Git-Zugangsdaten eingeben:${GIT_ERROR:-}" 18 80 7 \
      "Benutzername:" 2 1 "${GIT_USER:-}" 2 20 40 100 0 \
      "E-Mail-Adresse:" 4 1 "${GIT_USERMAIL:-}" 4 20 48 250 0 \
      "Token:"        6 1 "${GIT_TOKEN:-}" 6 20 53 512 0 \
    3>&1 1>&2 2>&3)"

    local rc=$?

    case $rc in
      1|255)
        cleanleave "Installation durch Benutzer abgebrochen."
        ;;
    esac

    GIT_USER="$(printf '%s\n' "$result" | sed -n '1p')"
    GIT_USERMAIL="$(printf '%s\n' "$result" | sed -n '2p')"
    GIT_TOKEN="$(printf '%s\n' "$result" | sed -n '3p')"

    if [[ -z "$GIT_USER" ]]; then
      GIT_ERROR=$'\n\n\Z1Fehler:\Zn Benutzername fehlt\n'
      continue
    fi

    if [[ -z "$GIT_USERMAIL" ]]; then
      GIT_ERROR=$'\n\n\Z1Fehler:\Zn E-Mail-Adresse fehlt\n'
      continue
    fi

    if [[ -z "$GIT_TOKEN" ]]; then
      GIT_ERROR=$'\n\n\Z1Fehler:\Zn Token fehlt\n'
      continue
    fi

    if ! curl -fsS --connect-timeout 10 "$GITLAB_URL" >/dev/null 2>&1; then
      GIT_ERROR=$'\n\n\Z1Fehler:\Zn GitLab ist nicht erreichbar.'
      continue
    fi

    local test_cred_file test_url host
    host="${GITLAB_URL#https://}"
    host="${host#http://}"
    host="${host%/}"
    test_cred_file="$(mktemp)"
    chmod 600 "$test_cred_file"
    printf 'https://%s:%s@%s\n' "$GIT_USER" "$GIT_TOKEN" "$host" > "$test_cred_file"
    test_url="https://${host}/${MAIN_REPO_PATH}"
    if ! git -c "credential.helper=store --file=${test_cred_file}" ls-remote "$test_url" >/dev/null 2>&1; then
      rm -f "$test_cred_file"
      GIT_ERROR=$'\n\n\Z1Fehler:\Zn Benutzername oder Token ungültig.'
      continue
    fi
    rm -f "$test_cred_file"

    # Prueft nur generellen API-Zugriff (Scope read_api/api). Ob konkret
    # Projekte in GITLAB_APPLICATIONS_GROUP sichtbar sind, wird erst beim
    # tatsaechlichen Laden der Plugin-Listen (fetch_group_plugins) geprueft,
    # da Zugangsdaten meist nur einzelne Projekte statt ganze Gruppen freigeben.
    local api_test_file api_http_code api_rc
    api_test_file="$(mktemp)"
    api_http_code="$(gitlab_api_get "/projects?membership=true&per_page=1" "$api_test_file")"
    api_rc=$?
    rm -f "$api_test_file"

    if [[ $api_rc -ne 0 ]]; then
      case "$api_http_code" in
        401|403)
          GIT_ERROR=$'\n\n\Z1Fehler:\Zn Token hat keinen ausreichenden API-Zugriff (Scope \x27read_api\x27 oder \x27api\x27 erforderlich).'
          ;;
        000)
          GIT_ERROR=$'\n\n\Z1Fehler:\Zn GitLab-API ist nicht erreichbar.'
          ;;
        *)
          GIT_ERROR=$'\n\n\Z1Fehler:\Zn GitLab-API antwortete mit HTTP '"$api_http_code"$'.'
          ;;
      esac
      continue
    fi

    ui_msg "Git-Zugang" "Der Git-Zugang kann verwendet werden."

    break

  done
}

ui_db_credentials() {
  local result

  while true; do

    result="$(dialog \
      --colors \
      --title "Datenbank" \
      --form "Datenbankdaten eingeben:${DB_ERROR:-}" \
      18 80 10 \
      "Host:"       2 1 "${DB_HOST:-localhost}"  2 20 50 0 \
      "Datenbank:"  4 1 "${DB_DATABASE:-}"      4 20 50 0 \
      "Benutzer:"   6 1 "${DB_USER:-}"          6 20 50 0 \
      "Passwort:"   8 1 "${DB_PASSWORD:-}"      8 20 50 0 \
      3>&1 1>&2 2>&3)"

    local rc=$?

    case $rc in
      1|255)
        cleanleave "Installation durch Benutzer abgebrochen."
        ;;
    esac

    DB_HOST="$(printf '%s\n' "$result" | sed -n '1p')"
    DB_DATABASE="$(printf '%s\n' "$result" | sed -n '2p')"
    DB_USER="$(printf '%s\n' "$result" | sed -n '3p')"
    DB_PASSWORD="$(printf '%s\n' "$result" | sed -n '4p')"

    if [[ -z "$DB_HOST" ]]; then
      DB_ERROR=$'\n\Z1Fehler:\Zn Host fehlt\n'
      continue
    fi
    if [[ -z "$DB_DATABASE" ]]; then
      DB_ERROR=$'\n\Z1Fehler:\Zn Datenbank fehlt\n'
      continue
    fi
    if [[ -z "$DB_USER" ]]; then
      DB_ERROR=$'\n\Z1Fehler:\Zn Benutzer fehlt\n'
      continue
    fi
    if [[ -z "$DB_PASSWORD" ]]; then
      DB_ERROR=$'\n\Z1Fehler:\Zn Passwort fehlt\n'
      continue
    fi

    if ! test_db_connection; then
      DB_ERROR=$'\n\Z1Fehler:\Zn Verbindung fehlgeschlagen oder Datenbank existiert nicht\n'
      continue
    fi

    ui_msg "Datenbank" "Verbindung wurde erfolgreich hergestellt."

    break

  done

}

run_install_php() {
  local install_php="$INSTALL_DIR/cli/install.php"

  if [[ ! -f "$install_php" ]]; then
    echo "Warnung: cli/install.php wurde nicht gefunden, überspringe Ausführung." >&2
    return
  fi

  echo
  echo "======================================================================"
  echo "Ausgabe von cli/install.php:"
  echo "======================================================================"
  echo

  php "$install_php"
  local install_rc=$?

  if [[ "$install_rc" != "0" ]]; then
    echo "Warnung: cli/install.php wurde mit Exitcode ${install_rc} beendet." >&2
  fi
}

# ------------------------------------------------------------
# Start
# ------------------------------------------------------------

if [[ "$(id -u)" -ne 0 ]]; then
  fail "Dieses Skript muss mit Root-Rechten ausgeführt werden (z. B. mit sudo)."
fi

if ((BASH_VERSINFO[0] < 4)); then
  fail "Dieses Skript benötigt Bash 4 oder neuer (aktuell: ${BASH_VERSION}). Unter sudo wird 'bash' oft auf eine ältere Systemversion aufgelöst - bitte mit vollständigem Pfad zu einer aktuellen Bash aufrufen, z. B. 'sudo /opt/homebrew/bin/bash yesinstall.sh' (macOS, nach 'brew install bash')."
fi

required_cmds=(git curl mysql dialog jq php)
if [[ "$(uname -s)" != "Darwin" ]]; then
  required_cmds+=(getent)
fi
check_prerequisites "${required_cmds[@]}"

INSTALL_DIR="$(pwd)"
SCRIPT_OWNER="$(id -un):$(id -gn)"
APACHE_OWNER="$(detect_apache_owner || true)"

if [[ -z "$APACHE_OWNER" ]]; then
  fail "Apache-Benutzer konnte nicht ermittelt werden. Die Installation wird abgebrochen. Geprüft wurden: die Standardkonten www-data (Debian/Ubuntu) und wwwrun (openSUSE/SLES), eine Homebrew-Apache-Konfiguration (httpd.conf mit User/Group) sowie ein laufender apache2-/httpd-Prozess. Bitte Apache installieren bzw. starten (z. B. 'brew services start httpd' oder 'apachectl start') und das Skript erneut ausführen."
fi

if [[ -n "$(ls -A "$INSTALL_DIR" 2>/dev/null)" ]]; then
    fail "Das Installationsverzeichnis ist nicht leer."
fi

ui_git_credentials

FETCH_APPS_ERROR_FILE="$(mktemp)"
FETCH_APPS_OUTPUT_FILE="$(mktemp)"
fetch_group_plugins "$GITLAB_APPLICATIONS_GROUP" >"$FETCH_APPS_OUTPUT_FILE" 2>"$FETCH_APPS_ERROR_FILE"
mapfile -t APPLICATION_PLUGINS < "$FETCH_APPS_OUTPUT_FILE"
rm -f "$FETCH_APPS_OUTPUT_FILE"
if [[ "${#APPLICATION_PLUGINS[@]}" -eq 0 ]]; then
  # fetch_group_plugins() schreibt Fehlerdetails (z. B. HTTP-Code) auf stderr;
  # ohne diese explizite Erfassung wuerden sie durch das "clear" in cleanleave()
  # unsichtbar vom Bildschirm verschwinden, bevor der Nutzer sie lesen kann.
  FETCH_APPS_ERROR="$(cat "$FETCH_APPS_ERROR_FILE")"
  rm -f "$FETCH_APPS_ERROR_FILE"
  ERROR_MSG="In der GitLab-Gruppe '${GITLAB_APPLICATIONS_GROUP}' wurden keine Anwendungs-Plugins gefunden, oder die Gruppe ist mit dem angegebenen Zugang nicht erreichbar. Die Installation kann ohne Auswahl einer Anwendung nicht fortgesetzt werden."
  [[ -n "$FETCH_APPS_ERROR" ]] && ERROR_MSG="${ERROR_MSG}

Details: ${FETCH_APPS_ERROR}"
  cleanleave "$ERROR_MSG"
fi
rm -f "$FETCH_APPS_ERROR_FILE"
check_duplicate_folders "$GITLAB_APPLICATIONS_GROUP" "${APPLICATION_PLUGINS[@]}"

FETCH_ADDONS_OUTPUT_FILE="$(mktemp)"
fetch_group_plugins "$GITLAB_EXTENSIONS_GROUP" >"$FETCH_ADDONS_OUTPUT_FILE"
mapfile -t ADDON_PLUGINS < "$FETCH_ADDONS_OUTPUT_FILE"
rm -f "$FETCH_ADDONS_OUTPUT_FILE"
# ADDON_PLUGINS darf leer bleiben - Addons sind optional.
check_duplicate_folders "$GITLAB_EXTENSIONS_GROUP" "${ADDON_PLUGINS[@]}"

ui_db_credentials

select_application_plugin
select_addon_plugins

IFS='|' read -r APP_LABEL APP_REPO APP_FOLDER <<< "$SELECTED_APPLICATION_PLUGIN"

SUMMARY="Hauptanwendung:
$MAIN_REPO_PATH

Anwendungs-Plugin:
$APP_LABEL

Addons:
"

if [[ "${#SELECTED_ADDON_PLUGINS[@]}" -gt 0 ]]; then
  for plugin in "${SELECTED_ADDON_PLUGINS[@]}"; do
    IFS='|' read -r label repo folder <<< "$plugin"
    SUMMARY+="- $label
"
  done
else
  SUMMARY+="Keine
"
fi

ui_msg "Zusammenfassung" "$SUMMARY"

# jetzt machen wir den Bildschirm sauber, sonst sieht das doof aus
clear

# Jetzt setzen wir erstmal den Eingentümer des Ordners auf den Scriptausführer.
# Sonst gibts ggf. Ärger mit git
chown -R "$SCRIPT_OWNER" "$INSTALL_DIR" \
  || fail "Konnte Eigentümer nicht auf ${SCRIPT_OWNER} setzen. Bitte Skript mit ausreichenden Rechten (root) erneut starten."

# Die Hauptanwendung holen
clone_and_fetch "$MAIN_REPO_PATH" "."

# Das Pluginverzeichnis anlegen und betreten
mkdir -p "$INSTALL_DIR/plugins"
cd "$INSTALL_DIR/plugins" || fail "Konnte nicht in $INSTALL_DIR/plugins wechseln."

# Das Application-Plugin installieren ... Das kann ja nur eins sein.
clone_and_fetch "$APP_REPO" "$APP_FOLDER"

# Die Addon-Plugins installieren ... Das sind durchaus mehrere bis alle
for plugin in "${SELECTED_ADDON_PLUGINS[@]}"; do
  IFS='|' read -r label repo folder <<< "$plugin"
  clone_and_fetch "$repo" "$folder"
done

# Zurück ins Installationsverzeichnis
cd "$INSTALL_DIR" || fail "Konnte nicht zurück in $INSTALL_DIR wechseln."

# config.sample.php nach config.inc.php kopieren
if [[ ! -f "./config.inc.php" ]]; then
  [[ -f "./config.sample.php" ]] \
    || fail "config.sample.php wurde nicht gefunden."
  cp "./config.sample.php" "./config.inc.php"
  chmod 640 "./config.inc.php"
fi

# Jetzt die Datenbank- und GIT-Parameter in der config.inc.php ersetzen
replace_placeholder "db_host" "$DB_HOST" "./config.inc.php"
replace_placeholder "db_database" "$DB_DATABASE" "./config.inc.php"
replace_placeholder "db_username" "$DB_USER" "./config.inc.php"
replace_placeholder "db_password" "$DB_PASSWORD" "./config.inc.php"
replace_placeholder "git_url" "$GITLAB_URL" "./config.inc.php"
replace_placeholder "git_token" "$GIT_TOKEN" "./config.inc.php"
replace_placeholder "git_username" "$GIT_USER" "./config.inc.php"
replace_placeholder "git_usermail" "$GIT_USERMAIL" "./config.inc.php"

echo "Setze Eigentümer der Installation"
chown -R "$APACHE_OWNER" "$INSTALL_DIR" \
  || fail "Konnte Eigentümer nicht auf ${APACHE_OWNER} setzen. Bitte Skript mit ausreichenden Rechten (root) erneut starten."

run_install_php

echo
echo "Installation ist abgeschlossen."
echo 