#!/bin/bash

# 4038-convert-gdi-link-tx-to-user-service.sh
# Copyright (c) 2022 Guralp Systems Ltd
# Author: fish <support@guralp.com>
 
# This script converts gdi-link-tx from a system service to a user service.
# It disables the service unless there are any push-destinations configured or
# evidence of recent use - connections or disconnections - in the messages files

CFG_DIR=/etc/gdi-link-tx
MSG_DIR=/var/log
SYS_AUTOSTART=/etc/init.d/autostart
USR_AUTOSTART=/etc/init.local/autostart

cd $CFG_DIR

################################################################################
# This renames the default instance to instance 'n', given as an argument
function move_default_instance_to() {
    local dest_num=$1
    for ext in local ctl.local peers.local ; do
        [[ -e default.$ext ]] && mv default.$ext ${dest_num}.$ext
    done
    # Remove the default template
    [[ -e default.tpl ]] && rm default.tpl
}

################################################################################
# This checks messages files for connect/disconnect notices and checks
# peer directories for push-configs.  Both of these suggest that the
# service is in use.
function service_in_use() {
    grep -iq "gdi-link-tx.*connect" ${MSG_DIR}/messages* \
    || !( echo *.peers.local/* | grep -q '\*' )
}

################################################################################
# This adds gdi-link-tx to the user autostart file, if it's not there already
function add_to_user_autostart() {
    grep -wq gdi-link-tx $USR_AUTOSTART \
    || echo gdi-link-tx >> $USR_AUTOSTART
}

################################################################################
# Only run once
[[ -n "${POST_UPGRADE_CACHE}" ]] && touch "${POST_UPGRADE_CACHE}/`basename $0`"
# Check we've not been run, in case the post-upgrade-cache has been cleared
[[ -f default.local ]] || exit

################################################################################
# Main code starts here

# Stop the service.  This must be done before we move its configuration
svc gdi-link-tx stop >/dev/null

# Remove gdi-link-tx from the system autostart list
sed --in-place -e '/^gdi-link-tx/s/^/#/' $SYS_AUTOSTART

# Move the default service to be a numbered service, using the lowest free number
if [ ! -f 0.local ] ; then
    move_default_instance_to 0
else
    # Find highest numbered instance in use (assume <= 9) so that we can move
    # the original default service to be numbered one higher ($last_tried)
    last_tried=10
    for instance_number in `seq 0 9 | sort -r` ; do
        if [[ -f ${instance_number}.local ]] ; then
            move_default_instance_to ${last_tried}
            break
        else
            last_tried=$instance_number
        fi
    done
fi

# Restart and enable the service if we've evidence that it was being used
if service_in_use ; then
    svc gdi-link-tx start
    add_to_user_autostart
fi
