#!/bin/bash

# Copyright: 2023 Virtuozzo International GmbH

# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at

# http://www.apache.org/licenses/LICENSE-2.0

# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

inherit default;
include os output virtuozzo vzexec;

DESCRIPTION="Jelastic hooks module"
VERSION="1"
DEFAULT_ACTION="usage"

CURRENT_TAG=""
TARGET_TAG=""
VZ_CTID_ROOT=""

function dousage() {
    showUsageMessage;
}


function onModLoadCallback() {
    log "Preload callback"
    local shortopts="c:,t:"
    local longopts="ctid:,currentTag:,targetTag:"

    local temp=`getopt -o $shortopts -l $longopts -- "$@" 2>/dev/null`
    [[ $? != 0 ]] && die -q "Terminating..."
    eval set -- "$temp"

    while true ; do
        case "$1" in
            -c   | --currentTag )
                shift
                CURRENT_TAG=$1
                shift
                ;;
            -t   | --targetTag )
                shift
                TARGET_TAG=$1
                shift
                ;;
            --ctid )
                shift;
                CTID=$1;
                vzexecSetCTID $CTID
                shift;
                ;;
            --)
                shift
                break
                ;;
        esac
    done
    if [[ ! -z "$CTID" ]] ; then
        VZ_CTID_ROOT=$(vzlist -Ho root $CTID )
        eval $(sed -rne "/COMPUTE_TYPE=/{s/(COMPUTE_TYPE=)([a-zA-Z_\-]+).*/\1\2/g;s/-/_/g;p}" $VZ_CTID_ROOT/etc/jelastic/metainf.conf)
    fi

    for arg do UNKNOWN_ARG+=("$arg") ; done
}

function apache_phpPreUpdate() {
    #save additional php.ini and put it to redeploy.conf
    if [ -f "$(vzctPath $VZ_CTID_ROOT /etc/php.ini)" ] ; then
        cp -f "$(vzctPath $VZ_CTID_ROOT /etc/php.ini)" "$VZ_CTID_ROOT/etc/php.ini_redeploy"
        [ -f "$(vzctPath $VZ_CTID_ROOT /etc/jelastic/redeploy.conf)" ] && echo "/etc/php.ini_redeploy" >> "$(vzctPath $VZ_CTID_ROOT /etc/jelastic/redeploy.conf)"
    fi
}

function apache_phpPostUpdate() {
    [ -f "$(vzctPath $VZ_CTID_ROOT /etc/jelastic/redeploy.conf)" ] && sed -i -re '/\/etc\/php.ini_redeploy/d' "$(vzctPath $VZ_CTID_ROOT /etc/jelastic/redeploy.conf)"

    if [ -f "$(vzctPath $VZ_CTID_ROOT /etc/php.ini_redeploy)" ] ; then
        if [ "x$CURRENT_TAG" = "x$TARGET_TAG" ] ; then
            mv -f "$(vzctPath $VZ_CTID_ROOT /etc/php.ini_redeploy)" "$VZ_CTID_ROOT/etc/php.ini"
        else
            _suffix="$(date +%d-%m-%Y.%H:%M:%S.%N)"
            mv -f "$(vzctPath $VZ_CTID_ROOT /etc/php.ini_redeploy)" "$VZ_CTID_ROOT/etc/php.ini.$_suffix"
            #add backup to redeploy.conf. Is it really neccesary?
            #echo "/etc/php.ini.$_suffix" >> "/etc/jelastic/redeploy.conf"
        fi
    fi
}

function proxysqlPreUpdate() {
    echo "`date +%D.%k:%M:%S.%N`:   $action:$subaction CTID:$CTID - current tag:$CURRENT_TAG, target tag:$TARGET_TAG" >> ${JEM_CALLS_LOG}
    if [[ ! $CURRENT_TAG =~ almalinux-9 && $TARGET_TAG =~ almalinux-9 ]]; then
        vzexecRun "mysqld -V 2>/dev/null | sed -re '/mysqld/s/.*Ver ([0-9])\.([0-9]).*/\1\2/'"
        local mysqlVersion=$(vzexecGetLastStdOut)
        echo "`date +%D.%k:%M:%S.%N`:   $action:$subaction CTID:$CTID - MySQL version: $mysqlVersion" >> ${JEM_CALLS_LOG}
        if [[ ! -z "$mysqlVersion" && $mysqlVersion -lt 57 ]]; then
            vzexecRun "rpm --import http://repo.mysql.com/RPM-GPG-KEY-mysql-2022 && yum update mysql --enablerepo=mysql57-community-dmr -y"
            echo "`date +%D.%k:%M:%S.%N`:   $action:$subaction CTID:$CTID - $(vzexecGetLastStdOut)" >> ${JEM_CALLS_LOG}
            vzexecRun "grep -E 'user\s*=\s*mysql' /etc/my.cnf || sed -i -re '/\[mysqld\]/auser = mysql' /etc/my.cnf ; \
            grep -E 'authentication_policy\s*=\s*caching_sha2_password' /etc/my.cnf || sed -i -re '/\[mysqld\]/aauthentication_policy = caching_sha2_password' /etc/my.cnf; \
            sed -n '/mysqld\]/{:a;n;/\[mysqld_safe/q;p;ba}' /etc/my.cnf | grep ^log_error || sed -i -re '/\[mysqld\]/alog_error = /var/log/mysqld.log' /etc/my.cnf"
        fi
    fi
    return 0
}

function describePreUpdate() {
    echo "Pre Update hook"
}

function describePreUpdateParameters() {
    echo "--currentTag The name of curent tag --targetTag The name of target tag"
}

function describePreUpdateOptions() {
    echo "currentTag    : The name of the currently installed tag"
    echo "targetTag     : The name of the tag which will be installed"
}

function doPreUpdate() {
    [ -z "$CURRENT_TAG" -o -z "$TARGET_TAG" ] && return 1

    if [ ! -z "$COMPUTE_TYPE" ] ; then
        isFunction "${COMPUTE_TYPE,,}PreUpdate" && "${COMPUTE_TYPE,,}PreUpdate"
    fi

    return 0
}

function describePostUpdate() {
    echo "Post Update hook"
}

function describePostUpdateParameters() {
    echo "--currentTag The name of curent tag --targetTag The name of target tag"
}

function describePostUpdateOptions() {
    echo "currentTag    : The name of the currently installed tag"
    echo "targetTag     : The name of the tag which will be installed"
}

function doPostUpdate() {
    [ -z "$COMPUTE_TYPE" ] && return 1
    [ -z "$CURRENT_TAG" -o -z "$TARGET_TAG" ] && return 1

    if [ ! -z "$COMPUTE_TYPE" ] ; then
        isFunction "${COMPUTE_TYPE,,}PostUpdate" && "${COMPUTE_TYPE,,}PostUpdate"
    fi

    return 0
}

