#!/usr/bin/env bash
#rbt

function upd_hosts() {
    local hosts_path='/etc/hosts'
    local ip=${ip:-$(hostname -I 2>/dev/null | cut -d' ' -f1)}
          ip=${ip:-$(ip -4 address show scope global up 2>/dev/null | awk '/inet / { gsub(/\/[^\/]+$/, "", $2); print $2; exit}')}
    local domain=$1; local server_fqdn=$2; local server_ip=$3; local host_name=$4
    local server_hn=`echo $server_fqdn | sed "s/.${domain}$//"`
    local check_def=`grep "127.0.1.1" ${hosts_path}`
    local check_hosts=(`awk '{if($1 == "'${ip}'" || $2 =="'${host_name}'.'${domain}'" || $3 == "'${host_name}'" ) print $1" "$2" "$3 }' ${hosts_path}`)
    local check_server=(`awk '{if($1 == "'${server_ip}'" || $2 =="'${server_fqdn}'" ) print $1" "$2}' ${hosts_path}`)
    if [[ -n "$check_def" ]];then
        sed -ie "/\<${check_server[0]}\>/d; /\<${check_hosts[0]}\>/d
                /\<127.0.1.1\>/c  ${server_ip}\t${server_fqdn}\t${server_hn}\n${ip}\t${host_name}.${domain}\t${host_name}" ${hosts_path}
    else
        if [[ -z "$check_hosts" && -n "${check_server}" ]];then
            sed -i "/\<${check_server[0]}\>/c ${server_ip}\t${server_fqdn}\t${server_hn}\n${ip}\t${host_name}.${domain}\t${host_name}" ${hosts_path}
        elif [[ -n "$check_hosts" && -z "${check_server}" ]];then
            sed -i "/\<${check_hosts[0]}\>/c ${server_ip}\t${server_fqdn}\t${server_hn}\n${ip}\t${host_name}.${domain}\t${host_name}" ${hosts_path}
        elif [[ -n "$check_hosts" && -n "${check_server}" ]];then
            if [[ "${server_ip}" != "${check_server[0]}" || "${server_fqdn}" != "${check_server[1]}" || "${ip}" != "${check_hosts[0]}" || \
                "${host_name}.${domain}" != "${check_hosts[1]}" || "${host_name}" != "${check_hosts[2]}" ]];then
                sed -ie "/\<${check_hosts[0]}\>/d
                        /${check_server[0]}/c ${server_ip}\t${server_fqdn}\t${server_hn}\n${ip}\t${host_name}.${domain}\t${host_name}" ${hosts_path}
            fi
        elif [[ -z "$check_hosts" && -z "${check_server}" ]];then
            echo -e "\n${server_ip}\t${server_fqdn}\t${server_hn}\n${ip}\t${host_name}.${domain}\t${host_name}" >> ${hosts_path}
        fi
    fi
    awk -i inplace '! a[$0]++'  ${hosts_path}  #remove duplicates
}

#rbt: ald ipa
if [[ -n "$DOMAIN_CONTROLLER" && -n "${DOMAIN_NAME}" && -n "${DOMAIN_SERVER_FQDN}" && -n "${DOMAIN_SERVER_IP}" && -n "${DOMAIN_SERVER_ADMIN}" && -n "${DOMAIN_SERVER_PASSWORD}" && -n "$VMID" ]];then
    if [[ "$DOMAIN_CONTROLLER" == "ALD" ]];then
        ALD_DOMAIN="${DOMAIN_NAME}"
        ALD_SERVER_FQDN="${DOMAIN_SERVER_FQDN}"
        ALD_SERVER_IP="${DOMAIN_SERVER_IP}"
        ALD_ADMIN="${DOMAIN_SERVER_ADMIN}"
        ALD_ADMIN_PASSWORD="$(echo "${DOMAIN_SERVER_PASSWORD}" | base64 -d)"
        [ -n "${DOMAIN_SET_NTP}" ] && ALD_NTP="${DOMAIN_SET_NTP}"
        ald_freeipa='ald'
    elif [[ "$DOMAIN_CONTROLLER" == "FreeIPA" ]];then
        FREEIPA_DOMAIN="${DOMAIN_NAME}"
        FREEIPA_SERVER_FQDN="${DOMAIN_SERVER_FQDN}"
        FREEIPA_SERVER_IP="${DOMAIN_SERVER_IP}"
        FREEIPA_ADMIN="${DOMAIN_SERVER_ADMIN}"
        FREEIPA_ADMIN_PASSWORD="$(echo "${DOMAIN_SERVER_PASSWORD}" | base64 -d)"
        ald_freeipa='freeipa'
    fi
    [ -n "${DOMAIN_SET_VMHN_PREFIX}" ] && SET_HOSTNAME="${DOMAIN_SET_VMHN_PREFIX}"
else
    if [[ -n "$ALD_DOMAIN" && -n "$ALD_SERVER_FQDN" && -n "$ALD_SERVER_IP" && -n "$ALD_ADMIN_PASSWORD" && -n "$VMID" ]];then
        ald_freeipa='ald'
    fi
    if [[ -n "$FREEIPA_DOMAIN" && -n "$FREEIPA_SERVER_FQDN" && -n "$FREEIPA_SERVER_IP" && -n "$FREEIPA_ADMIN_PASSWORD" && -n "$VMID" ]];then
        if [ -z "$ald_freeipa" ];then
            ald_freeipa='freeipa'
        else
            exit 1
        fi
    fi
fi

case "${ald_freeipa}" in

    'ald')

        # check status ald
        ald-client status > /dev/null 2>&1 && \
        if [ -n "`ald-client status | awk -F'=' '{ if($1=="SERVER") print$2 }'`" ];then
             exit 0
        fi

        # defaults
        ALD_ADMIN=${ALD_ADMIN:-admin/admin}
        # ALD_NTP=${ALD_NTP:-$ALD_SERVER_FQDN}

        # hostname
        host_name="one-${VMID}"
        if [ -n "$SET_HOSTNAME" ];then
            host_name="${SET_HOSTNAME}-one-${VMID}"
        fi
        grep -xq "${host_name}" /etc/hostname || \
        hostnamectl set-hostname --static "${host_name}"

        # /etc/hosts
        upd_hosts "${ALD_DOMAIN}" "${ALD_SERVER_FQDN}" "${ALD_SERVER_IP}" "${host_name}"

        # ntp
        echo "*/2 * * * * root /usr/sbin/ntpdate $ALD_NTP" > /etc/cron.d/ntpdate

        # install ald-client-common, expect
        set -e
        sudo apt install -y ald-client-common > /dev/null 2>&1
        sudo apt install -y expect > /dev/null 2>&1
        set +e

        # ald client join
        expect -c 'spawn ald-client join '$ALD_SERVER_FQDN'; 
        expect "Продолжить?*"; send "yes\r";
        expect "Имя:*"; send "'$ALD_ADMIN'\r";
        expect "Введите пароль администратора ALD:*"; send "'$ALD_ADMIN_PASSWORD'\r";
        expect eof'  > /dev/null 2>&1

        # check ald-client join
        echo -e "$ALD_ADMIN_PASSWORD\n" | kinit $ALD_ADMIN > /dev/null 2>&1 || \
        echo -e "yes\n" | ald-client reset-config > /dev/null 2>&1
        ;;

    'freeipa')

        # check status freeipa
        astra-freeipa-client -i > /dev/null 2>&1 && exit 0

        # default
        FREEIPA_ADMIN=${FREEIPA_ADMIN:-admin}

        # hostname
        host_name="one-${VMID}"
        if [ -n "$SET_HOSTNAME" ];then
            host_name="${SET_HOSTNAME}-one-${VMID}"
        fi
        grep -xq "${host_name}.${FREEIPA_DOMAIN}" /etc/hostname || \
        hostnamectl set-hostname --static "${host_name}.${FREEIPA_DOMAIN}"

        # /etc/hosts
        upd_hosts "${FREEIPA_DOMAIN}" "${FREEIPA_SERVER_FQDN}" "${FREEIPA_SERVER_IP}" "${host_name}"


        # domainname
        echo "nameserver ${FREEIPA_SERVER_IP}" > /etc/resolv.conf

        # install astra-freeipa-client
        sudo apt install -y astra-freeipa-client > /dev/null 2>&1 || exit $?

        # freeipa client join
        astra-freeipa-client -u $FREEIPA_ADMIN -p $FREEIPA_ADMIN_PASSWORD -y > /dev/null 2>&1 || exit $?

        # check astra-freeipa-client
        astra-freeipa-client -i > /dev/null 2>&1 || \
        echo -e "y\n" | astra-freeipa-client -U > /dev/null 2>&1
        ;;
esac
