#!/bin/bash

TARGET_PATH="/var/www/crm-api/httpdocs"
GIT_PATH="/var/www/matsen-git-repository/matsen-tool-be"

create_directories() {
    # Erstelle notwendige Verzeichnisse falls sie nicht existieren
    mkdir -p ${TARGET_PATH}/config
    mkdir -p ${TARGET_PATH}/public
    mkdir -p ${TARGET_PATH}/var/cache
}

copy_files() {
    cd ${GIT_PATH}
    sudo GIT_SSH_COMMAND="ssh -i /home/service-spawntree/.ssh/id_rsa -p 1122" git pull
    echo "$(tput setab 2)matsen api has been PULLED$(tput sgr 0)"
    ROOT_DIRS="bin config migrations src"

    # Erstelle zuerst alle notwendigen Verzeichnisse
    create_directories

    rm -rf ${TARGET_PATH}/composer.lock
    rm -rf ${TARGET_PATH}/composer.json
    cp -rf ${GIT_PATH}/composer.json ${TARGET_PATH}

    for dir in $ROOT_DIRS; do
        rm -rf ${TARGET_PATH}/$dir
        cp -rf ${GIT_PATH}/$dir ${TARGET_PATH}/
    done

    # Stelle sicher, dass der public Ordner existiert
    mkdir -p ${TARGET_PATH}/public
    rm -rf ${TARGET_PATH}/public/index.php
    cp -rf ${GIT_PATH}/public/index.php ${TARGET_PATH}/public/

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

if [ "$1" = "init" ]; then
    copy_files
    echo "$(tput setab 2)Init completed - files copied$(tput sgr 0)"
else
    copy_files

    cd ${TARGET_PATH}
    composer update --no-scripts
    echo "$(tput setab 2)COMPOSER UPDATED updated$(tput sgr 0)"

    php ${TARGET_PATH}/bin/console doctrine:migrations:migrate
    echo "$(tput setab 2)DATABASE SCHEMA updated$(tput sgr 0)"

    cd ${TARGET_PATH}/var/cache/
    rm -R *

    php ${TARGET_PATH}/bin/console cache:clear
    php ${TARGET_PATH}/bin/console cache:warmup
    echo "$(tput setab 2)CACHE HAS BEEN CLEARED$(tput sgr 0)"

    cd ${TARGET_PATH}/var/
    sudo chmod 777 -R *
    sudo chmod 777 cache/ *
    sudo chmod 777 cache/

    echo "$(tput setab 7)$(tput setaf 1)THINK ABOUT POSSIBLE PATCHES!"
    echo "You have updated matsen api!$(tput sgr 0)"
fi