#!/bin/bash

# Default-Werte für Parameter
SKIP_CLIENT=false
SKIP_MIGRATION=false
INIT_MODE=false

# Projekt-Name
PROJECT_NAME="Imaq"

# Konfigurierbare Pfade
BASE_DIR="/var/www/vhosts/app-imaq-pilot.de"
GIT_REPO_PATH="${BASE_DIR}/git_repo/imaq"
ANGULAR_PATH="${BASE_DIR}/angular"
HTTPDOCS_PATH="${BASE_DIR}/httpdocs"
PUBLIC_PATH="${HTTPDOCS_PATH}/public"
CLIENT_PATH="${PUBLIC_PATH}/client"
PHP_PATH="/opt/plesk/php/8.3/bin"
ANGULAR_ENVIRONMENT="production"

# Angular Analytics Abfrage disablen
export NG_CLI_ANALYTICS=false

# Funktion zum Überprüfen der Pfade
check_paths() {
    local error=false

    # Prüfe ob alle erforderlichen Pfade existieren
    if [ ! -d "$GIT_REPO_PATH" ]; then
        echo "$(tput setab 1)ERROR: Git repository path does not exist: ${GIT_REPO_PATH}$(tput sgr 0)"
        error=true
    fi

    if [ ! -d "$BASE_DIR" ]; then
        echo "$(tput setab 1)ERROR: Base directory does not exist: ${BASE_DIR}$(tput sgr 0)"
        error=true
    fi

    # Im Init-Mode müssen nicht alle Verzeichnisse existieren
    if [ "$INIT_MODE" = false ]; then
        if [ ! -d "$ANGULAR_PATH" ]; then
            echo "$(tput setab 1)ERROR: Angular path does not exist: ${ANGULAR_PATH}$(tput sgr 0)"
            error=true
        fi

        if [ ! -d "$HTTPDOCS_PATH" ]; then
            echo "$(tput setab 1)ERROR: Httpdocs path does not exist: ${HTTPDOCS_PATH}$(tput sgr 0)"
            error=true
        fi

        if [ ! -d "$PUBLIC_PATH" ]; then
            echo "$(tput setab 1)ERROR: Public path does not exist: ${PUBLIC_PATH}$(tput sgr 0)"
            error=true
        fi
    fi

    # Prüfe ob PHP im angegebenen Pfad existiert
    if [ ! -d "$PHP_PATH" ]; then
        echo "$(tput setab 1)ERROR: PHP path does not exist: ${PHP_PATH}$(tput sgr 0)"
        error=true
    fi

    # Wenn Fehler gefunden wurden, beende das Skript
    if [ "$error" = true ]; then
        echo "$(tput setab 1)Critical errors found. Please check your path configuration at the top of the script.$(tput sgr 0)"
        exit 1
    fi
}

# Parameter verarbeiten
while getopts ":cmi" opt; do
  case $opt in
    c) SKIP_CLIENT=true ;;
    m) SKIP_MIGRATION=true ;;
    i) INIT_MODE=true ;;
    \?) echo "Unknown option: -$OPTARG" >&2; exit 1 ;;
  esac
done

# Pfade überprüfen bevor irgendwelche Operationen durchgeführt werden
check_paths

export PATH=${PHP_PATH}:$PATH

# Git Pull durchführen
cd "${GIT_REPO_PATH}" || { echo "$(tput setab 1)Failed to change to repository directory$(tput sgr 0)"; exit 1; }
sudo git pull
echo "$(tput setab 2)${PROJECT_NAME} has been PULLED$(tput sgr 0)"

# Client Update nur wenn nicht übersprungen
if [ "$SKIP_CLIENT" = false ]; then
    echo "$(tput setab 2)Client update$(tput sgr 0)"

    # Im Init-Mode keine Dateien löschen
    if [ "$INIT_MODE" = false ]; then
        echo "$(tput setab 2)delete angular files$(tput sgr 0)"
        cd "${ANGULAR_PATH}" || { echo "$(tput setab 1)Failed to change to angular directory$(tput sgr 0)"; exit 1; }
        find . -maxdepth 1 ! -name 'node_modules' ! -name '.' -exec rm -rf {} +
    fi

    # Kopiere normale Dateien
    cp -r "${GIT_REPO_PATH}/angular/"* "${ANGULAR_PATH}" 2>/dev/null || true

    # Kopiere versteckte Dateien nur wenn sie existieren
    HIDDEN_FILES=$(find "${GIT_REPO_PATH}/angular" -maxdepth 1 -name ".*" -not -name "." -not -name "..")
    if [ ! -z "$HIDDEN_FILES" ]; then
        cp -r ${HIDDEN_FILES} "${ANGULAR_PATH}"
    fi

    cd "${ANGULAR_PATH}" || { echo "$(tput setab 1)Failed to change to angular directory$(tput sgr 0)"; exit 1; }
    npm install
    npx ng analytics off
    npx ng build --configuration ${ANGULAR_ENVIRONMENT}

    if [ -d "${CLIENT_PATH}/browser" ]; then
        mv "${CLIENT_PATH}/browser/"* "${CLIENT_PATH}/"
        rm -rf "${CLIENT_PATH}/browser"
    fi
    echo "$(tput setab 2)Client files have been updated$(tput sgr 0)"
else
    echo "$(tput setab 3)Skip client update$(tput sgr 0)"
fi

# Arrays mit Dateien und Verzeichnissen die kopiert werden sollen
COPY_ITEMS="composer.lock composer.json config migrations src templates"
PUBLIC_FILES="index.php .htaccess .htpasswd"

# Dateien und Verzeichnisse kopieren
for item in $COPY_ITEMS; do
    if [ -e "${GIT_REPO_PATH}/httpdocs/${item}" ]; then
        # Im Init-Mode keine Dateien löschen
        if [ "$INIT_MODE" = false ]; then
            rm -rf "${HTTPDOCS_PATH}/${item}"
        fi
        cp -rf "${GIT_REPO_PATH}/httpdocs/${item}" "${HTTPDOCS_PATH}"
    else
        echo "$(tput setab 3)Warning: Source item does not exist: ${GIT_REPO_PATH}/httpdocs/${item}$(tput sgr 0)"
    fi
done

# Spezielle Dateien im public Verzeichnis kopieren
for file in $PUBLIC_FILES; do
    if [ -e "${GIT_REPO_PATH}/httpdocs/public/${file}" ]; then
        # Im Init-Mode keine Dateien löschen
        if [ "$INIT_MODE" = false ]; then
            rm -rf "${PUBLIC_PATH}/${file}"
        fi
        cp -rf "${GIT_REPO_PATH}/httpdocs/public/${file}" "${PUBLIC_PATH}"
    else
        echo "$(tput setab 3)Warning: Source file does not exist: ${GIT_REPO_PATH}/httpdocs/public/${file}$(tput sgr 0)"
    fi
done

echo "$(tput setab 2)Files have been copied$(tput sgr 0)"

cd "${HTTPDOCS_PATH}" || { echo "$(tput setab 1)Failed to change to httpdocs directory$(tput sgr 0)"; exit 1; }
export COMPOSER_ALLOW_SUPERUSER=1
composer update --no-interaction

echo "$(tput setab 2)COMPOSER UPDATED updated$(tput sgr 0)"

# Migration nur wenn nicht übersprungen
if [ "$SKIP_MIGRATION" = false ]; then
    php "${HTTPDOCS_PATH}/bin/console" doctrine:migration:migrate --no-interaction
    echo "$(tput setab 2)DATABASE SCHEMA updated$(tput sgr 0)"
else
    echo "$(tput setab 3)Skip migrations$(tput sgr 0)"
fi

# Cache leeren
if [ -d "${HTTPDOCS_PATH}/var/cache" ]; then
    cd "${HTTPDOCS_PATH}/var/cache/" || { echo "$(tput setab 1)Failed to change to cache directory$(tput sgr 0)"; exit 1; }
    rm -R *

    php "${HTTPDOCS_PATH}/bin/console" cache:clear
    php "${HTTPDOCS_PATH}/bin/console" cache:warmup

    echo "$(tput setab 2)CACHE HAS BEEN CLEARED$(tput sgr 0)"
else
    echo "$(tput setab 3)Warning: Cache directory does not exist$(tput sgr 0)"
fi

cd "${HTTPDOCS_PATH}" || { echo "$(tput setab 1)Failed to change to httpdocs directory$(tput sgr 0)"; exit 1; }
chmod 777 -R var/

echo "$(tput setab 7)$(tput setaf 1)THINK ABOUT POSSIBLE PATCHES!"
echo "You have updated ${PROJECT_NAME}!$(tput sgr 0)"