#!/bin/bash
# usbserial-support/src/scripts/purge-USB-serial.sh
# 
#  Copyright: ©2012, Güralp Systems Ltd.
#  Author: Laurence Withers <lwithers@guralp.com>
#  License: GPLv3
#

UDEV_RULES="/etc/udev/rules.d/12-USBserial.rules.local"
SERIAL_CF_DIR="/etc/conf.d/serial.local"
INITSCRIPT_DIR="/etc/init.local"
INITSCRIPT_AUTOSTART="${INITSCRIPT_DIR}/autostart"

# we'll put the important stuff into a backup directory, just in case
# (needs manual restore but easier than recreating everything from
# scratch).
BACKUP_DIR="`mktemp -d /root/USBserial.backup.XXXXXX`"
if [ -z "${BACKUP_DIR}" ]
then
	echo "Could not create backup directory." >&2
	exit 1
fi

echo "Backing up old configuration to ${BACKUP_DIR}"
mkdir -p "${BACKUP_DIR}/init" "${BACKUP_DIR}/config"

# purge the udev rules. We used a single file specifically for
# USB to serial converters so no problem removing the whole file.
if [ -e "${UDEV_RULES}" ]
then
	mv "${UDEV_RULES}" "${BACKUP_DIR}"
fi

# purge list of 'seen' NSP-RMxx devices, so that next time one is plugged in
# it will repopulate the serial ports
rm -f /var/lib/nsp-hotplug/*

# scan for configuration files referencing USB to serial devices
for CONFIG_FILE in "${SERIAL_CF_DIR}"/*.cf
do
	[ -r "${CONFIG_FILE}" ] || continue

	grep -q "^device[ 	]*=[ 	]*/dev/USBserial/" "${CONFIG_FILE}" || continue
	echo "Purging ${CONFIG_FILE}"
	TAG="`basename "${CONFIG_FILE}" ".cf"`"

	# stop the service, ignoring failures
	svc "${TAG}" stop >& /dev/null

	# remove from autostart
	T="`mktemp /etc/init.local/.autostart.XXXXXX`"
	grep -v "^${TAG}$" < "${INITSCRIPT_AUTOSTART}" > "${T}"
	mv "${T}" "${INITSCRIPT_AUTOSTART}"

	# save the initscript
	mv "${INITSCRIPT_DIR}/${TAG}" "${BACKUP_DIR}/init/"

	# purge the main port configuration
	mv "${CONFIG_FILE}" "${BACKUP_DIR}/config/"

	# purge the application-specific configuration
	for SUB_CF in "${SERIAL_CF_DIR}/"*"/${TAG}"
	do
		[ -r "${SUB_CF}" ] || continue

		T="`dirname ${SUB_CF}`"
		T="`basename ${T}`"
		mkdir -p "${BACKUP_DIR}/config/${T}"
		mv "${SUB_CF}" "${BACKUP_DIR}/config/${T}/"
	done
done

echo "Complete."
