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

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

BONDINGADMIN_VERSION_CACHE='/var/lib/bondingadmin/version'
INFLUX_EPOCH=1      # increment by 1 on change to influxdb config
INFLUX_EPOCH_CACHE='/var/lib/bondingadmin/influx-epoch'
BONDINGADMIN_LOCAL_REPOS='/var/lib/bondingadmin/repos/'


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 upgrading() {
    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 $BONDINGADMIN_VERSION_CACHE ] ; then
        cat $BONDINGADMIN_VERSION_CACHE
    fi
}


function get_last_influx_epoch() {
    if [ -f $INFLUX_EPOCH_CACHE ] ; then
        cat $INFLUX_EPOCH_CACHE
    fi
}


function influx_config_updated() {
    cache=$(get_last_influx_epoch)

    if [[ $cache < $INFLUX_EPOCH ]] || [ -z $cache ] ; then
        return 0
    fi

    return 1
}


function api_token_exists() {
    token=$(ba get multapplied_api_token)

    if [ -z $token ] ; then
        return 1
    fi

    return 0
}


#
# Main
#

# 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 locale 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.'
    echo 'Once your locale is confirmed to be UTF-8, run bondingadmin-setup again.'
    exit 1
fi

# Create salt node key files if necessary
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

# Remove the local repo if it exists
if [ -d $BONDINGADMIN_LOCAL_REPOS ] ; then
    rm -rf $BONDINGADMIN_LOCAL_REPOS
fi

# Set the Nginx resolver address if not set
if [ ! -f /etc/bondingadmin/nginx/resolver.conf ]; then
        echo 'resolver 1.1.1.1;' > /etc/bondingadmin/nginx/resolver.conf
fi

# Run major db and salt operations on upgrade or install
if upgrading ; then
    # Stop bondingadmin services if they are already running
    echo "Stopping bondingadmin services"
    systemctl daemon-reload
    systemctl stop bondingadmin bondingadmin-salt-master bondingadmin-salt-minion bondingadmin-salt-access bondingadmin-flowcollector-dnat bondingadmin-fetch-latest-bonding-version bondingadmin-fetch-latest-bonding-version.timer

    echo "Performing database migrations"
    /usr/share/bondingadmin/initdb.sh

    echo "Initializing needed database objects"
    ba initialize_objects

    echo "Saving persistent object configurations"
    ba update_configs

    echo "Updating salt pillars"
    ba update_salt_pillars

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

    last_version=$(get_last_version)
    new_version=$(ba bondingadmin_version)
    if [ "$last_version" != "$new_version" ] ; then
        # Major version upgrade. Ensure the update message is seen by users
        echo "Major upgrade"
        echo "Resetting update message"
        ba reset_seen_update_message

        # Remember that this version was installed
        echo "Caching bondingadmin version"
        ba bondingadmin_version > $BONDINGADMIN_VERSION_CACHE
    fi

    # Restart bondingadmin services
    echo "Starting bondingadmin services"
    systemctl start bondingadmin bondingadmin-salt-minion bondingadmin-salt-access bondingadmin-flowcollector-dnat bondingadmin-fetch-latest-bonding-version bondingadmin-fetch-latest-bonding-version.timer
fi

# Check if influx needs config updates
if influx_config_updated ; then
    echo "Setting up influxdb"
    /usr/lib/bondingadmin/influxconfig

    echo "Caching influxdb epoch"
    echo $INFLUX_EPOCH > $INFLUX_EPOCH_CACHE
fi

if api_token_exists ; then
    # Sync pricing labels from julius
    echo "Syncing pricing labels"
    ba sync_pricing_labels

else
    echo "Cannot sync pricing labels."
    echo "Please set the API token (ba set multapplied_api_token) and try again."
fi

# Update bonding version to match bondingadmin if set to automatically update
echo "Updating the version if desired"
ba update_bonding_version

# Clear ISOs for old spaces and regenerate new ones for valid spaces
echo "Regenerating the bonding ISO images"
ba regenerate_isos

# Enable timer for daily sync-base-isos task
systemctl enable --now sync-base-isos.timer