#!/bin/bash
# Pt-web/src/app-root/scripts/TriggerConfig/delete.sh
# 
#  Copyright: ©2012, Güralp Systems Ltd.
#  Author: Laurence Withers <lwithers@guralp.com>
#  License: GPLv3
#

# The instance ID
INSTANCE="$1"

#
# This script performs the following actions:
#
#  1. Stops any running services from the instance, and remove their
#     initscripts.
#
#  2. Removes the instance's services from autostart.
#
#  3. Removes the state directory for the instance.
#
#  4. Removes the configuration directory for the instance.
#

CONFIG_DIR="/etc/gdi-trigger"
INSTANCE_DIR="${CONFIG_DIR}/${INSTANCE}.local"
RECORD_CF="${INSTANCE_DIR}/record.cf"
INITSCRIPT_DIR="/etc/init.local"
INITSCRIPT_AUTOSTART="${INITSCRIPT_DIR}/autostart"
DIRECTORY_CLEANER_DIR="/etc/directory-cleaner"
DIRECTORY_CLEANER_SYMLINK="${DIRECTORY_CLEANER_DIR}/gdi-trigger.${INSTANCE}.local"
DIRECTORY_CLEANER_CF="${INSTANCE_DIR}/directory-cleaner.cf"



#
# Stop any running services from the instance
# (we also remove the initscript symlinks at this stage)
#
for SVC in "${INITSCRIPT_DIR}/gdi-trigger.${INSTANCE}."*
do
    [ -e "${SVC}" ] || continue
    "${SVC}" stop
    rm -f "${SVC}"
done



#
# Filter initscripts from autostart
#
if [ -e "${INITSCRIPT_AUTOSTART}" ]
then
    grep -v "^gdi-trigger\.${INSTANCE}\." \
        < "${INITSCRIPT_AUTOSTART}" \
        > "${INITSCRIPT_AUTOSTART}.new"
    if [ -e "${INITSCRIPT_AUTOSTART}.new" ]
    then
        mv "${INITSCRIPT_AUTOSTART}.new" "${INITSCRIPT_AUTOSTART}"
    fi
fi



#
# If recording is enabled, remove the state directory
#
if [ -e "${RECORD_CF}" ]
then
    STATE_DIR="`gcs_rwvar gcs_get_varcf event_directory "${RECORD_CF}"`"
    if [ -n "${STATE_DIR}" ]
    then
        rm -rf "${STATE_DIR}"
    fi
fi



#
# Remove the main configuration directory, and any other symlinks
# into it
#
rm -rf "${INSTANCE_DIR}"
rm -f "${DIRECTORY_CLEANER_SYMLINK}"


# Done
exit 0

# options for text editors:
# vim: expandtab:ts=4:sw=4
