#!/bin/sh
set -e

#DEBHELPER#

. /usr/share/debconf/confmodule

# First, create a temporary configuration file before letting ucf handles the
# changes between the existing file (if any) and the new version
TEMP_CONFIG_FILE=`mktemp --tmpdir=/tmp slapos-client.cfg.XXXXXX.cfg`
chmod 0644 $TEMP_CONFIG_FILE

echo "# Never edit this file by hand as it has been automatically generated by
# debconf. You can change the settings at any time by running:
# ``dpkg-reconfigure -pmedium slapos-client''" > $TEMP_CONFIG_FILE

cat < /usr/share/slapos-client/slapos-client.cfg >> $TEMP_CONFIG_FILE

# Synchronize master_url, key_file and cert_file with slapos-client.cfg
SLAPOS_NODE_CONFIG_FILE=/etc/slapos/slapos-node-unofficial.cfg
if [ ! -f $SLAPOS_NODE_CONFIG_FILE ]; then
    SLAPOS_NODE_CONFIG_FILE=
fi

db_get shared/slapos/master_url
MASTER_URL="$RET"
WITH_HTTPS=$(echo "$MASTER_URL" | grep -q "^https://" && echo true || echo false)

sed -e "s#^\s*master_url\s*=.*#master_url = $MASTER_URL#" \
    -i $TEMP_CONFIG_FILE $SLAPOS_NODE_CONFIG_FILE

# Handle HTTPS URLs by just commenting/uncommenting the relevant lines
if $WITH_HTTPS; then
    sed -i 's/^\s*#\+\s*\(key_file\|cert_file\)/\1/' \
        $TEMP_CONFIG_FILE $SLAPOS_NODE_CONFIG_FILE
else
    sed -i 's/^\s*[^#]*\s*\(key_file\|cert_file\)/#\1/' \
        $TEMP_CONFIG_FILE $SLAPOS_NODE_CONFIG_FILE
fi

ucf --three-way --debconf-ok $TEMP_CONFIG_FILE /etc/slapos/slapos-client.cfg
db_go

rm -f $TEMP_CONFIG_FILE

exit 0
