#!/bin/bash

# Copyright (c) Cloud Linux GmbH & Cloud Linux Software, Inc 2010-2018 All Rights Reserved
#
# Licensed under CLOUD LINUX LICENSE AGREEMENT
# http://cloudlinux.com/docs/LICENSE.TXT

PACKED_LSAPI_VER="1.1-93"

USE_DA_MOD_LSAPI_RPM="no"

CONF="$(dirname "$0")/da_cb_install.conf"
[ -f "$CONF" ] && . "$CONF"

if [ "$USE_DA_MOD_LSAPI_RPM" != "yes" ]
then
    USE_DA_MOD_LSAPI_RPM="no"
fi


function do_exit() {
    # In order to forcefully fail current build even when custom_build script ignores exit code
    [ -f CMakeLists.txt ] && rm CMakeLists.txt
    exit $1
}


SOCKPATH="/var/mod_lsapi"
DA_LSAPI_DIR="/usr/share/lve/da_lsapi/"
DA_LSAPI_LOG="$DA_LSAPI_DIR/da_cb_install.log"
mkdir -p "$DA_LSAPI_DIR"

function getRPM() {
    local PARAM="$1"
    local RESULT=""
    local n
    pushd "$DA_LSAPI_DIR" >/dev/null
    n=`ls "$PARAM"*.rpm 2>/dev/null | wc -l`
    if [ "$n" -gt 1 ]
    then
        echo "$(date): getRPM: more than 1 ($n) files of ${PARAM}*.rpm found, delete them">>"$DA_LSAPI_LOG"
        rm -f "$PARAM"*.rpm
    elif [ "$n" -eq 1 ]
    then
        RESULT=`ls "$PARAM"*.rpm 2>/dev/null`
        echo "$(date): getRPM: one file of ${PARAM}*.rpm found: $RESULT">>"$DA_LSAPI_LOG"
        if ! /usr/bin/file "$RESULT" | grep -q RPM
        then
            rm -f "$RESULT"
            echo "$(date): getRPM: this file is not an RPM, delete it">>"$DA_LSAPI_LOG"
            RESULT=""
        fi
    else
        echo "$(date): getRPM: not found files of ${PARAM}*.rpm">>"$DA_LSAPI_LOG"
    fi
    popd >/dev/null
    echo "$RESULT"
}

function deleteRPM() {
    local PARAM="$1"
    pushd "$DA_LSAPI_DIR" >/dev/null
    rm -f "$PARAM" 2>/dev/null
    popd >/dev/null
}


function downloadRPM() {
    local rpm
    local repo
    rpm=$1
    repo=$2
    pushd "$DA_LSAPI_DIR" >/dev/null
    if [ -z "$repo" ]
    then
        yumdownloader "${rpm}*" --disableexcludes=all "--downloaddir=$DA_LSAPI_DIR"
    else
        yumdownloader "${rpm}*" --disableexcludes=all "--downloaddir=$DA_LSAPI_DIR" "$repo"
    fi
    popd >/dev/null
}


case "$#" in
    "0")
        REPO="stable"
        VER="${PACKED_LSAPI_VER}"
    ;;

    "1")
        REPO="$1"
        VER="${PACKED_LSAPI_VER}"
    ;;

    "2")
        REPO="$1"
        VER="$2"
    ;;

    *)
        echo "*** mod_lsapi.da_cb_install params error: 2 params should be provided (LSAPI_RELEASE and LSAPI_VERSION), $# is provided instead ***"
        echo "$(date): *** mod_lsapi.da_cb_install params error: 2 params should be provided (LSAPI_RELEASE and LSAPI_VERSION), $# is provided instead ***">>"$DA_LSAPI_LOG"
        do_exit 1
    ;;
esac


if [ "$REPO" != "beta" -a "$REPO" != "stable" ]
then
    echo "*** mod_lsapi.da_cb_install params error: LSAPI_RELEASE param should be beta or stable, $REPO is provided instead ***"
    echo "$(date): *** mod_lsapi.da_cb_install params error: LSAPI_RELEASE param should be beta or stable, $REPO is provided instead ***">>"$DA_LSAPI_LOG"
    do_exit 1
fi

if [ -z "$VER" ]
then
    echo "*** mod_lsapi.da_cb_install params error: void string is provided as LSAPI_VERSION ***"
    echo "$(date): *** mod_lsapi.da_cb_install params error: void string is provided as LSAPI_VERSION ***">>"$DA_LSAPI_LOG"
    do_exit 1
fi

RESULT=""
RESULT_DEVEL=""
RESULT_SRC=""

echo "$(date): mod_lsapi.da_cb_install is invoked: LSAPI_RELEASE:$REPO; LSAPI_VERSION:$VER; USE_DA_MOD_LSAPI_RPM:$USE_DA_MOD_LSAPI_RPM" >>"$DA_LSAPI_LOG"

# The custombuild script adds liblsapi* exclude into /etc/yum.conf
#
# In CL8 yum is symlink to dnf, and always uses settings from /etc/dnf/dnf.conf only.
# /etc/yum.conf is provided by rpm packages as symlink to /etc/dnf/dnf.conf for compatibility.
#
# But in real system this symlink, due to some erronous actions, can be
# converted into real file - as a copy of /etc/dnf/dnf.conf
#
# This can lead to effective absence of liblsapi exclude,
# and then simple `yum update' command leads to broken Apache.
#
# So it would be wise to add the exclusion into dnf.conf also, if it is absent
DNF_CONF="/etc/dnf/dnf.conf"
if [ -e "$DNF_CONF" ]; then
    # This snippet is got from the custombuild script as is, except config file name
    if ! grep -m1 -q 'exclude=.*liblsapi' "$DNF_CONF"; then
        perl -pi -e 's|exclude\=|exclude=liblsapi* |g' "$DNF_CONF"
    fi
fi

yum install -y yum-utils file
REPOSIT=""
if [ "$REPO" == "beta" ];then
    REPOSIT="--enablerepo=cloudlinux-updates-testing"
fi

IS_CL6=$(uname -r | grep '\.el6')
if [ -z "$IS_CL6" ]
then
    if [ -z "$REPOSIT" ]
    then
        yum install -y criu-lve criu-lve-devel crit-lve --disableexcludes=all
    else
        yum install -y criu-lve criu-lve-devel crit-lve --disableexcludes=all "$REPOSIT"
    fi
fi


# Let's try to assure that the proper version of liblsapi pkg is already downloaded
RESULT=$(getRPM liblsapi-"$VER")
if [ -z "$RESULT" ]
then
    downloadRPM "liblsapi-$VER" "$REPOSIT"
fi
RESULT=$(getRPM liblsapi-"$VER")
for (( i=1; i <= 5; i++ ))
do
    if [ -n "$RESULT" ]
    then
        break
    fi
    # delay before every repetive download
    sleep 5
    downloadRPM "liblsapi-$VER" "$REPOSIT"
    RESULT=$(getRPM liblsapi-"$VER")
done
if [ -z "$RESULT" ]
then
    echo "*** mod_lsapi.da_cb_install error: cannot download liblsapi $VER version ***"
    echo "$(date): *** mod_lsapi.da_cb_install error: cannot download liblsapi $VER version  ***">>"$DA_LSAPI_LOG"
    do_exit 1
fi

# Let's try to assure that the proper version of liblsapi pkg is already downloaded
RESULT_DEVEL=$(getRPM liblsapi-devel-"$VER")
if [ -z "$RESULT_DEVEL" ]
then
    downloadRPM "liblsapi-devel-$VER" "$REPOSIT"
fi
RESULT_DEVEL=$(getRPM liblsapi-devel-"$VER")
for (( i=1; i <= 5; i++ ))
do
    if [ -n "$RESULT_DEVEL" ]
    then
        break
    fi
    # delay before every repetive download
    sleep 5
    downloadRPM "liblsapi-devel-$VER" "$REPOSIT"
    RESULT_DEVEL=$(getRPM liblsapi-devel-"$VER")
done
if [ -z "$RESULT_DEVEL" ]
then
    echo "*** mod_lsapi.da_cb_install error: cannot download liblsapi-devel $VER version ***"
    echo "$(date): *** mod_lsapi.da_cb_install error: cannot download liblsapi-devel $VER version  ***">>"$DA_LSAPI_LOG"
    do_exit 1
fi

if [ "$USE_DA_MOD_LSAPI_RPM" == "yes" ]
then
    # Let's try to assure that the proper version of liblsapi pkg is already downloaded
    RESULT_SRC=$(getRPM da-mod_lsapi-"$VER")
    if [ -z "$RESULT_SRC" ]
    then
        downloadRPM "da-mod_lsapi-$VER" "$REPOSIT"
    fi
    RESULT_SRC=$(getRPM da-mod_lsapi-"$VER")
    for (( i=1; i <= 5; i++ ))
    do
        if [ -n "$RESULT_SRC" ]
        then
            break
        fi
        # delay before every repetive download
        sleep 5
        downloadRPM "da-mod_lsapi-$VER" "$REPOSIT"
        RESULT_SRC=$(getRPM da-mod_lsapi-"$VER")
    done
    if [ -z "$RESULT_SRC" ]
    then
        echo "*** mod_lsapi.da_cb_install error: cannot download da-mod_lsapi $VER version ***"
        echo "$(date): *** mod_lsapi.da_cb_install error: cannot download da-mod_lsapi $VER version  ***">>"$DA_LSAPI_LOG"
        do_exit 1
    fi
fi

if [ "$USE_DA_MOD_LSAPI_RPM" == "yes" ]
then
    echo "mod_lsapi.da_cb_install: mod_lsapi sources will be provided by da-mod_lsapi.rpm"
    echo "$(date): mod_lsapi.da_cb_install: mod_lsapi sources will be provided by da-mod_lsapi.rpm">>"$DA_LSAPI_LOG"

    # Update source package only if it is not installed or in case of version mismatch
    if ! rpm -q da-mod_lsapi | grep -qF "da-mod_lsapi-$VER.cloudlinux"
    then
        if ! rpm -Uhv "${DA_LSAPI_DIR}/$RESULT_SRC" --oldpackage
        then
            echo "*** mod_lsapi.da_cb_install error: cannot update mod_lsapi from ${DA_LSAPI_DIR}/$RESULT_SRC ***"
            echo "$(date): *** mod_lsapi.da_cb_install error: cannot update mod_lsapi from ${DA_LSAPI_DIR}/$RESULT_SRC  ***">>"$DA_LSAPI_LOG"
            do_exit 1
        fi
    fi
    SRCPKG="/usr/share/lve/modlscapi/DirectAdmin/mod_lsapi-${VER}.tar.gz"
    if [ ! -f "$SRCPKG" ]
    then
        echo "*** mod_lsapi.da_cb_install error: cannot find da_mod_lsapi sources $SRCPKG ***"
        echo "$(date): *** mod_lsapi.da_cb_install error: cannot find da_mod_lsapi sources $SRCPKG  ***">>"$DA_LSAPI_LOG"
        do_exit 1
    fi

    mkdir da-mod_lsapi-tmp
    cd da-mod_lsapi-tmp
    tar xf "$SRCPKG"

    if [ ! -d "mod_lsapi-${VER}" ]
    then
        cd ..
        rm -fr da-mod_lsapi-tmp
        echo "*** mod_lsapi.da_cb_install error: cannot find da_mod_lsapi sources root ***"
        echo "$(date): *** mod_lsapi.da_cb_install error: cannot find da_mod_lsapi sources root ***">>"$DA_LSAPI_LOG"
        do_exit 1
    fi
    cd ..

    # To prevent copiing them into working mod_lsapi directory of the custom build
    rm -f da-mod_lsapi-tmp/mod_lsapi-${VER}/install/da_cb_install*

    # Copy sources from the tarball provided by da_mod_lsapi into the working directory of the custom build
    cp -fr da-mod_lsapi-tmp/mod_lsapi-${VER}/* .
    rm -fr da-mod_lsapi-tmp
    deleteRPM "$RESULT_SRC"
fi

# Update liblsapi* packages only if liblsapi is not installed or in case of version mismatch
# liblsapi-devel contains dep from liblsapi with the same version, so check liblsapi only
if ! rpm -q liblsapi | grep -qF "liblsapi-$VER.el"
then
    if ! rpm -Uhv "${DA_LSAPI_DIR}/$RESULT" "${DA_LSAPI_DIR}/$RESULT_DEVEL" --oldpackage
    then
        echo "*** mod_lsapi.da_cb_install error: cannot update liblsapi from ${DA_LSAPI_DIR}/$RESULT and ${DA_LSAPI_DIR}/$RESULT_DEVEL ***"
        echo "$(date): *** mod_lsapi.da_cb_install error: cannot update liblsapi from ${DA_LSAPI_DIR}/$RESULT and ${DA_LSAPI_DIR}/$RESULT_DEVEL  ***">>"$DA_LSAPI_LOG"
        do_exit 1
    fi
fi
deleteRPM "$RESULT"
deleteRPM "$RESULT_DEVEL"

if [ ! -e /etc/cl.selector/lsphp -a -e /usr/sbin/cagefsctl -a -e /etc/cl.selector ]; then
    ln -s /usr/local/bin/lsphp /etc/cl.selector/lsphp
    /usr/sbin/cagefsctl --update-etc
    RES=`cat /etc/cl.selector/native.conf | grep lsphp=/usr/local/bin/lsphp `
    if [ -z "$RES" ]; then
        echo "lsphp=/usr/local/bin/lsphp" >> /etc/cl.selector/native.conf
    fi
    /usr/sbin/cagefsctl --setup-cl-selector

    echo "mod_lsapi.da_cb_install: reconfiguration completed"
    echo "$(date): mod_lsapi.da_cb_install: reconfiguration completed">>"$DA_LSAPI_LOG"
fi

if [ ! -e "$SOCKPATH" ]; then
    mkdir -p "$SOCKPATH"
fi

CSF_CONFIG="/etc/csf/csf.pignore"
CSF_MAIN_RULE="exe:/usr/local/bin/lsphp"
CSF_ALT_RULE="pexe:/opt/alt/php.*/usr/bin/lsphp"
CSF_SELECTOR_RULE="exe:/usr/selector/lsphp"

# Make sure that CSF rules contain exceptions for all lsphp
if [ -f "${CSF_CONFIG}" ]
then
    [ -e "${CSF_CONFIG}.bkp" ] || cp "${CSF_CONFIG}" "${CSF_CONFIG}.bkp"
    grep -v '^[[:space:]]*#' "${CSF_CONFIG}" | grep -Fq "${CSF_MAIN_RULE}" || echo "${CSF_MAIN_RULE}" >> "$CSF_CONFIG"
    grep -v '^[[:space:]]*#' "${CSF_CONFIG}" | grep -Fq "${CSF_SELECTOR_RULE}" || echo "${CSF_SELECTOR_RULE}" >> "$CSF_CONFIG"
    grep -v '^[[:space:]]*#' "${CSF_CONFIG}" | grep -Fq "${CSF_ALT_RULE}" || echo "${CSF_ALT_RULE}" >> "$CSF_CONFIG"
    service lfd restart 2>/dev/null >/dev/null
    echo "mod_lsapi.da_cb_install: CSF config found - exceptions for lsphp are added, lfd service restarted"
    echo "$(date): mod_lsapi.da_cb_install: CSF config found - exceptions for lsphp are added, lfd service restarted">>"$DA_LSAPI_LOG"
fi

chown apache:apache "$SOCKPATH"
chmod 755 "$SOCKPATH"
echo "$(date): mod_lsapi.da_cb_install: completed successfully, version $VER">>"$DA_LSAPI_LOG"
exit 0
