#!/bin/bash

## Description: gambio helper scripts
## Usage: gambio [flags] [args]
## ProjectTypes: php

needs_cleanup=false

# Funktion, die aufgerufen wird, wenn Strg+C gedrückt wird
cleanup()
{
  error=$?

  if [ "$needs_cleanup" == false ] ; then
    exit 0
  fi

  case $error in
    0)
       echo "Das Skript wurde erfolgreich beendet."
    ;;
#             1)
#                 echo "Ein allgemeiner Fehler ist aufgetreten."
#                 ;;
#             255)
#                 echo "Das Skript wurde mit Fehler 255 (unbekannter schwerer Fehler) beendet."
#                 ;;
    *)
      echo "Das Skript wurde mit Exit-Code $error beendet."
      echo "Beende das Teilen und konfiguriere auf lokalen Betrieb."
      ddev gambio unshare
      ;;
  esac

  exit 0
}

# "trap" fängt EXIT ab und ruft die Funktion "cleanup" auf
trap cleanup  EXIT

set_shop_domain()
{
  if [ "$1" = ngrok ] ; then
    echo "${DDEV_APPROOT}"
    # Lese die ngrok_args aus der .ddev/config.yaml
    NGROK_ARGS=$(grep 'ngrok_args' "${DDEV_APPROOT}"/.ddev/config.yaml)
    # Extrahiere das Argument --domain aus ngrok_args
    SHOP_URL="https://$(echo "$NGROK_ARGS" | grep -oP '(?<=--domain )\S+')"
  elif [ "$1" = devtn ] ; then
    echo "${DDEV_APPROOT}"
    SHOP_URL="https://share.hq.lenk.gmbh"
  elif [ "$1" = share ] ; then
    echo "${DDEV_APPROOT}"
    SHOP_URL="https://${DDEV_SITENAME,,}.d.lenk.gmbh"
  elif [ "$1" = expose ] ; then
    echo "${DDEV_APPROOT}"
    SHOP_URL="https://${DDEV_SITENAME,,}.dev.lenk.gmbh"
  elif [ "$1" = unshare ] ; then
    SHOP_URL=${DDEV_PRIMARY_URL}
  fi

  echo "Konfiguriere den Shop auf folgende Domain: $SHOP_URL"

  # Liste der Konfigurationsdateien
  files="includes/configure.php admin/includes/configure.php"

  # Durchlaufe jede Datei in dem Array
  for file_path in $files
  do
    # sed Befehle zum Setzen der Shop-Domain
    sed -i "s|define('HTTP_SERVER', '.*')|define('HTTP_SERVER', '${SHOP_URL}')|g" "${DDEV_APPROOT}/$file_path"
    sed -i "s|define('HTTPS_SERVER', '.*')|define('HTTPS_SERVER', '${SHOP_URL}')|g" "${DDEV_APPROOT}/$file_path"

    sed -i "s|define('HTTP_CATALOG_SERVER', '.*')|define('HTTP_CATALOG_SERVER', '${SHOP_URL}')|g" "${DDEV_APPROOT}/$file_path"
    sed -i "s|define('HTTPS_CATALOG_SERVER', '.*')|define('HTTPS_CATALOG_SERVER', '${SHOP_URL}')|g" "${DDEV_APPROOT}/$file_path"

    if [ "$1" = expose ] ; then
      sed -i "s|define('HTTP_SERVER', '.*')|define('HTTP_SERVER', '')|g" "${DDEV_APPROOT}/$file_path"
      sed -i "s|define('ENABLE_SSL', true)|define('ENABLE_SSL', false)|g" "${DDEV_APPROOT}/$file_path"

    elif [ "$1" = unshare ] ; then
      sed -i "s|define('ENABLE_SSL', false)|define('ENABLE_SSL', true)|g" "${DDEV_APPROOT}/$file_path"
    fi

  done
}

clear_caches()
{
  echo "Leere die Caches"

  if [ "$(ls -A "${DDEV_APPROOT}"/cache)" ]; then
      rm -r "${DDEV_APPROOT}"/cache/*
  else
      echo "Verzeichnis 'cache' bereits geleert..."
  fi

  if [ "$(ls -A "${DDEV_APPROOT}"/public/theme)" ]; then
      rm -r "${DDEV_APPROOT}"/public/theme/*
  else
      echo "Verzeichnis 'public/theme' bereits geleert..."
  fi
}

get_gambio_version()
{
  local application_file="${DDEV_APPROOT}/GambioCore/Application/Application.php"

  if [ ! -f "$application_file" ]; then
    echo "unknown"
    return 1
  fi

  grep -E "public const VERSION[[:space:]]*=" "$application_file" \
    | head -n 1 \
    | sed -E "s/.*public const VERSION[[:space:]]*=[[:space:]]*['\"]([^'\"]+)['\"].*/\1/"
}

normalize_gambio_version()
{
  echo "$1" \
    | sed -E 's/^v//' \
    | sed -E 's/[^0-9.].*$//'
}

compare_gambio_versions()
{
  local version_a
  local version_b
  local a_major
  local a_minor
  local a_patch
  local b_major
  local b_minor
  local b_patch

  version_a=$(normalize_gambio_version "$1")
  version_b=$(normalize_gambio_version "$2")

  IFS='.' read -r a_major a_minor a_patch <<< "$version_a"
  IFS='.' read -r b_major b_minor b_patch <<< "$version_b"

  a_major=${a_major:-0}
  a_minor=${a_minor:-0}
  a_patch=${a_patch:-0}
  b_major=${b_major:-0}
  b_minor=${b_minor:-0}
  b_patch=${b_patch:-0}

  a_major=$((10#$a_major))
  a_minor=$((10#$a_minor))
  a_patch=$((10#$a_patch))
  b_major=$((10#$b_major))
  b_minor=$((10#$b_minor))
  b_patch=$((10#$b_patch))

  if [ "$a_major" -gt "$b_major" ]; then
    echo 1
    return 0
  elif [ "$a_major" -lt "$b_major" ]; then
    echo -1
    return 0
  fi

  if [ "$a_minor" -gt "$b_minor" ]; then
    echo 1
    return 0
  elif [ "$a_minor" -lt "$b_minor" ]; then
    echo -1
    return 0
  fi

  if [ "$a_patch" -gt "$b_patch" ]; then
    echo 1
    return 0
  elif [ "$a_patch" -lt "$b_patch" ]; then
    echo -1
    return 0
  fi

  echo 0
}

gambio_version_matches()
{
  local version_a="$1"
  local operator="$2"
  local version_b="$3"
  local comparison

  comparison=$(compare_gambio_versions "$version_a" "$version_b")

  case "$operator" in
    ">"|"-gt")
      [ "$comparison" -gt 0 ]
      ;;
    ">="|"-ge")
      [ "$comparison" -ge 0 ]
      ;;
    "<"|"-lt")
      [ "$comparison" -lt 0 ]
      ;;
    "<="|"-le")
      [ "$comparison" -le 0 ]
      ;;
    "="|"=="|"-eq")
      [ "$comparison" -eq 0 ]
      ;;
    "!="|"-ne")
      [ "$comparison" -ne 0 ]
      ;;
    *)
      echo "Ungültiger Versionsoperator: $operator" >&2
      return 2
      ;;
  esac
}

get_max_compatible_php_version()
{
  local gambio_version="$1"

  if [ -z "$gambio_version" ] || [ "$gambio_version" = "unknown" ]; then
    return 1
  fi

  if ! gambio_version_matches "$gambio_version" ">" "3.0.0"; then
    return 1
  fi

  if gambio_version_matches "$gambio_version" ">=" "26.03.0"; then
    echo "8.3"
  elif gambio_version_matches "$gambio_version" ">=" "4.9.0"; then
    echo "8.2"
  elif gambio_version_matches "$gambio_version" ">=" "4.8.0"; then
    echo "8.1"
  elif gambio_version_matches "$gambio_version" ">=" "4.7.0"; then
    echo "8.0"
  elif gambio_version_matches "$gambio_version" ">=" "4.1.0"; then
    echo "7.4"
  elif gambio_version_matches "$gambio_version" ">=" "3.13.0"; then
    echo "7.3"
  elif gambio_version_matches "$gambio_version" ">=" "3.10.0"; then
    echo "7.2"
  elif gambio_version_matches "$gambio_version" ">=" "3.8.0"; then
    echo "7.1"
  elif gambio_version_matches "$gambio_version" ">=" "3.4.0"; then
    echo "7.0"
  else
    echo "5.6"
  fi
}


case $1 in
  share|unshare|devtn|ngrok|expose)
    set_shop_domain "$@"
    clear_caches "$@"
    needs_cleanup=true

    if [ "$1" = ngrok ] ; then
      echo "teile Shop via ngrok..."
      ddev share
    elif [ "$1" = devtn ] ; then
      echo "teile Shop via share.hq.lenk.gmbh..."
      ssh -o ServerAliveInterval=30 -o ServerAliveCountMax=4 remotetunnel@monitor.hq.lenk.gmbh -p 2222 -R 65318:localhost:"$DDEV_HOST_WEBSERVER_PORT"
    elif [ "$1" = share ] ; then
      echo "teile Shop via d.lenk.gmbh..."
      ssh -p 2222 -R "${DDEV_SITENAME,,}":80:localhost:"$DDEV_HOST_WEBSERVER_PORT" dev.lenk.gmbh
    elif [ "$1" = expose ] ; then
      echo "teile Shop via dev.lenk.gmbh..."
      expose share "${DDEV_HOSTNAME}" --subdomain="${DDEV_SITENAME,,}"

    fi
    ;;

  init)

    GAMBIO_VERSION=$(get_gambio_version || true)
    PHP_VERSION=$(get_max_compatible_php_version "$GAMBIO_VERSION" || true)

    if [ -z "$PHP_VERSION" ]; then
      echo "Für Gambio-Version '$GAMBIO_VERSION' konnte keine kompatible PHP-Version ermittelt werden."
      echo "Die automatische DDEV-Konfiguration wird abgebrochen."
      exit 1
    fi

    echo "Erkannte Gambio-Version: $GAMBIO_VERSION"
    echo "Maximal kompatible PHP-Version: $PHP_VERSION"

    ddev config \
      --project-type=php \
      --docroot="" \
      --php-version="$PHP_VERSION"\
      --webserver-type=apache-fpm

    echo "DDEV wurde für Gambio $GAMBIO_VERSION mit PHP $PHP_VERSION konfiguriert."

    ;;

  version)

    GAMBIO_VERSION=$(get_gambio_version)
    echo "Erkannte Gambio-Version: $GAMBIO_VERSION"
    ;;

  *)
    echo "Invalid argument: $1"
    ;;
esac
