#!/bin/bash -e
#
# bondingadmin-setup - Perform Bondingadmin install/update tasks
#

export PATH="/bin:/sbin:/usr/bin:/usr/sbin"

VERSION_CACHE='/var/lib/bondingadmin/version'


function service_start_time() {
    start_timestamp=$(systemctl show bondingadmin | grep ExecMainStartTimestamp= | cut -d '=' -f 2)
    if [ -n "$start_timestamp" ] ; then
        date -d "$start_timestamp" +%s
    else
        echo 0
    fi
}


function service_upgraded() {
    install_time=$(stat -c %Z /usr/lib/systemd/system/bondingadmin.service)

    if [[ $install_time > $(service_start_time) ]] ; then
        return 0
    fi

    return 1
}


function get_last_version() {
    if [ -f $VERSION_CACHE ] ; then
        cat $VERSION_CACHE
    fi
}

function test_postgresql_state() {
    version=$1
    desired_state=$2

    state=$(systemctl show postgresql@${version}-main.service | grep 'SubState=' | cut -d '=' -f 2)

    test "$state" = "$desired_state"
}


function wait_for_postgresql_state() {
    version=$1
    desired_state=$2

    echo "Waiting for postgresql ${version} to be ${desired_state}."
    while ! test_postgresql_state $version $desired_state ; do
        sleep 1
    done
}


function postgresql_upgrade() {
    # Check for 9.6 cluster and upgrade to 11
    pg_lsclusters | tail -n+2 | grep -qe '^9.6' && {
        pg_dropcluster --stop 11 main
        wait_for_postgresql_state 11 dead
        systemctl stop postgresql
        wait_for_postgresql_state 9.6 dead
        pg_upgradecluster -v 11 9.6 main
        pg_dropcluster 9.6 main
        systemctl start postgresql
        wait_for_postgresql_state 11 running
    } ||:
}


#
# Main
#
service_upgraded && upgrade=1 || upgrade=0
last_version=$(get_last_version)
new_version=$(ba bondingadmin_version)
test "$last_version" != "$new_version" && major_upgrade=1 || major_upgrade=0

if [ "$upgrade" = "1" ] ; then
    # Ensure the locale is en_US.UTF-8
    echo "Checking for valid locale"
    if ! grep -q 'LANG=en_US.UTF-8' /etc/default/locale; then
        echo 'Setting default local to en_US.UTF-8...'
        sed -i 's/# en_US.UTF-8 UTF-8/en_US.UTF-8 UTF-8/' /etc/locale.gen
        locale-gen
        update-locale LANG="en_US.UTF-8" LANGUAGE="en_US:en"
        echo 'You MUST run locale and ensure your current settings are a UTF-8 locale, and if not, restart your session.'
        exit 1
    fi

    systemctl daemon-reload

    echo "Stop bondingadmin services"
    systemctl stop bondingadmin bondingadmin-salt-master bondingadmin-salt-minion salt-master salt-minion

    test ! -f /etc/bondingadmin/salt-config/states/node/root_unauthorized_keys && touch /etc/bondingadmin/salt-config/states/node/root_unauthorized_keys
    test ! -f /etc/bondingadmin/salt-config/states/node/root_authorized_keys && touch /etc/bondingadmin/salt-config/states/node/root_authorized_keys
fi

if [ "$major_upgrade" = 1 ] ; then
    echo "Check and upgrade PostgreSQL"
    postgresql_upgrade
fi

if [ "$upgrade" = "1" ] ; then
    echo "Perform database migrations"
    /usr/share/bondingadmin/initdb.sh

    echo "Initialize needed database objects"
    ba initialize_objects

    echo "Save persistent object configurations"
    ba update_configs

    echo "Updating salt pillars"
    ba update_salt_pillars

    echo "Ensuring salt-master.service is disabled and masked"
    systemctl disable salt-master.service
    systemctl mask salt-master.service

    echo "Ensure depreciated files have been removed"
    if [ -f /etc/bondingadmin/collectd/bondingadmin.conf ] ; then
        rm -f /etc/bondingadmin/collectd/bondingadmin.conf
        rm -f /etc/collectd/bondingadmin.conf
        rm -f /etc/collectd/collectd.conf.d/bondingadmin.conf
        rm -f /etc/collectd/collectd.conf.d/hostname.conf
        rm -f /etc/collectd/collectd.conf.d/postgresql.conf
    fi

    echo "Start bondingadmin services"
    systemctl enable bondingadmin-salt-access
    systemctl start bondingadmin bondingadmin-salt-master bondingadmin-salt-minion bondingadmin-salt-access

    echo "Configuring salt-master"
    /usr/share/bondingadmin/initsalt.sh

    echo "Set up Influx"
    /usr/lib/bondingadmin/influxconfig

    echo "Sync pricing labels"
    ba sync_pricing_labels
fi

if [ "$major_upgrade" = "1" ] ; then

    if [ "$new_version" = "6.6" ] ; then
        echo "Generating node-specific salt configurations"
        ba generate_salt_configs

        echo "Import salt resolv.conf configurations"
        ba import_salt_resolv_conf

        echo "Migrating known-ips to nftables trusted networks"
        migrate-known-ips

        echo "Restarting bondingadmin-salt-master for configuration changes"
        systemctl restart bondingadmin-salt-master
    fi

    # Version was upgraded. Ensure the update message is seen by users
    ba reset_seen_update_message

    # Remember that this version was installed
    ba bondingadmin_version > $VERSION_CACHE
fi

if [ "$upgrade" = "1" ] ; then
    echo "Sync release"
    ba sync_bonding_release

    echo "Update the version if desired"
    ba update_bonding_version

    echo "Grab the base ISO images"
    sync-base-isos

    echo "Regenerate the bonding ISO images"
    ba regenerate_isos
fi
