#!/usr/bin/env bash

. /usr/share/dosis2/bin/shell-support-functions

systemtype="$1"
serial="$2"
OS="`getos`"

dafetype="`/opt/dosis2/etc/personality/common-scripts/system-to-dafe-type \"${systemtype}\"`"
dafetag="`/opt/dosis2/etc/personality/common-scripts/system-to-dafe-tag \"${systemtype}\" \"${serial}\"`"
siteserverip="`/opt/dosis2/etc/personality/common-scripts/siteserver-ip-from-config`"

if [ "${siteserverip}" != "" ] && [ "${siteserverip}" != "127.0.0.1" ]; then
    while [ true ]; do
        answer="`/opt/dosis2/etc/personality/common-scripts/ask \
            \"Export Dafe Settings? \" \
            '^(yes|no)?$'`"

        [ $? = 0 ] && break

        echo -e "\033[31mType yes or no\033[0m"
    done

    if [ "${answer}" = "yes" ]; then
        for servicename in `/opt/dosis2/etc/personality/common-scripts/service-data ${OS} postgresql`; do
            /opt/dosis2/bin/os-support-service start ${servicename}
        done

        tmpfile="`mktemp`"
        psql -At -U dpg -d dosis2 -c "select * from equipment.export_dafe_specifics('${dafetag}')" \
            -o "${tmpfile}" 2>&1 | tee -a /tmp/step5dbg.log

        fnname="equipment.add_dafe_`echo ${dafetype} | tr '[[:upper:]]' '[[:lower:]]'`"
        psql -At -U dpg -d dosis2 -h "${siteserverip}" -c "select ${fnname}(${serial})" 2>&1 | tee -a /tmp/step5dbg.log
        psql -Aqt -U dpg -d dosis2 -h "${siteserverip}" -f "${tmpfile}" 2>&1 | tee -a /tmp/step5dbg.log
        psql -At -U dpg -d dosis2 -h "${siteserverip}" -c "SELECT equipment.dafe_init_all()" 2>&1 | tee -a /tmp/step5dbg.log
        cp "${tmpfile}" /tmp/setting-export-dbg.sql
        rm -f "${tmpfile}"
    fi
fi
