#!/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 os net;
include log;

DESCRIPTION="Manipulate SLB configuration";
VERSION="1.0"
DEFAULT_ACTION="Usage";

SLB_ZONES_CONFIG_PATH='/etc/pdns-recursor/internal.zones';
REGION_RESOLVERS_CONF="/etc/jelastic/region_resolvers.conf"
[ -f $REGION_RESOLVERS_CONF ] && . $REGION_RESOLVERS_CONF

#ZONE_TYPE parameter specifies type of zone to Add
#Valid values: internal, external, both
ZONE_TYPE='both';

$PROGRAM 'grep'
$PROGRAM 'curl'
$PROGRAM 'sed'
$PROGRAM 'pdns_control'

function checkParams() {
    local params=($*)
    local result=""
    for p in "${params[*]}" ; do
        eval "[[ -z \"\$$p\" ]] && { result=\"$p $result\";}"
    done
    [[ -z "$result" ]] && return 0;
    return 1;
}

function onModLoadCallback() {
    log "Preload callback";

    local temp=`getopt -o n:,t:: -l name:,type:: -- "$@" 2>/dev/null`;
    [[ $? != 0 ]] && die -q "Terminating...";
    eval set -- "$temp";

    while true ; do
        case "$1" in
            -n | --name)
                shift;
                ZONE_NAME=$1;
                shift;
                ;;
            -t | --type)
                shift;
                ZONE_TYPE=$1;
                shift;
                ;;
            --)
                shift;
                break;
                ;;
        esac;
    done;
    for arg do UNKNOWN_ARG+=($arg) ; done
    log "${UNKNOWN_ARG[*]}"
    return 0
}

function reload_zones(){
    if rec_control ping &>/dev/null; then
        rec_control reload-zones;
        result=$?;
    else
        echo "WARNING: Loks like pdns-recursor is not running"
        result=0;
    fi
    return $result;
}


function doAddZone() {
    if [ -z "${region_resolvers_internal_ips}" ]; then
        local INTERNALIPS="$(internalip)"
    else
        local INTERNALIPS="${region_resolvers_internal_ips}"
    fi
    local requiredParqams=("ZONE_NAME" "INTERNALIP")
    local msg=$(checkParams ${requiredParqams[@]})
    [[ ! -z "${msg}" ]] && { writeJSONResponseErr "result=>4099" "message=>Missing param $msg" ; return 99; }
    [[ ! -e "$SLB_ZONES_CONFIG_PATH" ]] && {
        writeJSONResponseErr "result=>4099" "message=>SLB zones configuration file not found $SLB_ZONES_CONFIG_PATH" ;
        return 99;
    }
    #is Zone exists in main config?
    if $GREP -wE "^${ZONE_NAME}[[:blank:]]*=[[:blank:]]*${INTERNALIPS}" "$SLB_ZONES_CONFIG_PATH" ; then
        writeJSONResponseErr "result=>4099" "message=>Zone ${ZONE_NAME} already exists in $SLB_NAMED_MAIN_CONFIG" ;
        return 99;
    fi
    $SED -i "/^${ZONE_NAME}[[:blank:]]*=/d" $SLB_ZONES_CONFIG_PATH
    echo "${ZONE_NAME} = ${INTERNALIPS}" >> $SLB_ZONES_CONFIG_PATH
    reload_zones;
    return $?;
}

function doFixZones() {
    $PROGRAM 'mysql'
    $PROGRAM 'awk'
    _QUERY='select DISTINCT(name) from hivext_jelastic.dns_internal where rdtype="SOA";'
    OLD_IFS=$IFS; IFS=$'\n';
    ZONES_DB=($(${MYSQL} -uroot -BNse "${_QUERY}")) || return $?
    if ! diff <(for z in ${ZONES_DB[*]}; do echo $z; done | sort) <($AWK '{print $1}' $SLB_ZONES_CONFIG_PATH 2>/dev/null | sort) &>/dev/null; then
        > $SLB_ZONES_CONFIG_PATH
        for zone in ${ZONES_DB[*]} ; do
            ZONE_NAME=$zone
            echo "Adding zone ${ZONE_NAME}"
            out=$(doAddZone)
            log $out
        done
        reload_zones;
        return $?
    else
        return 0
    fi
}

function doRemoveZone() {
    local requiredParqams=("ZONE_NAME")
    local msg=$(checkParams ${requiredParqams[@]})
    [[ ! -z "${msg}" ]] && { writeJSONResponseErr "result=>4099" "message=>Missing param $msg" ; return 99; }
    [[ ! -e "$SLB_ZONES_CONFIG_PATH" ]] && {
        writeJSONResponseErr "result=>4099" "message=>SLB zones configuration file not found $SLB_ZONES_CONFIG_PATH" ;
        return 99;
    }
    $SED -ri "/^${ZONE_NAME}([[:blank:]]|=)/d" $( readlink -f $SLB_ZONES_CONFIG_PATH)
    reload_zones;
    return $?;
}

function doDelUpstream() {
    local requiredParqams=("ZONE_NAME")
    local msg=$(checkParams ${requiredParqams[@]})

    msg=$($CURL -X DELETE "http://127.0.0.1:8666/upstream/${ZONE_NAME}")
    return 0
}

function doRediscover() {
    local msg=$($PDNS_CONTROL rediscover)
    log "Rediscovered: response=$msg}"

    msg=$($PDNS_CONTROL --config-name=external rediscover)
    log "Rediscovered external: response=$msg}"
 return 0;
}
