#!/bin/sh

# postinst script for pilot-link and other libpisock8 related packages
#
# see: dh_installdeb(1)

set -e

# summary of how this script can be called:
#        * <postinst> `configure' <most-recently-configured-version>
#        * <old-postinst> `abort-upgrade' <new version>
#        * <conflictor's-postinst> `abort-remove' `in-favour' <package>
#          <new-version>
#        * <deconfigured's-postinst> `abort-deconfigure' `in-favour'
#          <failed-install-package> <version> `removing'
#          <conflicting-package> <version>
# for details, see /usr/doc/packaging-manual/
#
# quoting from the policy:
#     Any necessary prompting should almost always be confined to the
#     post-installation script, and should be protected with a
#     conditional
#     so that unnecessary prompting doesn't happen if a package's
#     installation fails and the `postinst' is called with
#     `abort-upgrade',
#     `abort-remove' or `abort-deconfigure'.

devfs_cfg=/etc/devfs/conf.d/libpisock8

case "$1" in
    configure|reconfigure)
		# Source debconf library.
		. /usr/share/debconf/confmodule

		# which port?
		db_get 'shared/pilot/port'

		port="$RET"

		# if port is not defined we don't do anything
		if [ "$port" ]
		then
			# if port is not set to None
			if [ "$port" != "None" ]
			then
				rm -f /dev/pilot
				ln -s "$port" /dev/pilot
				chmod -f 0666 /dev/"$port" || true

				# remove old devfs stuff (from before 0.11.3-5)
				if [ -f /etc/devfs/symlinks.d/pilot-link ]; then
					rm /etc/devfs/symlinks.d/pilot-link
				fi
				if [ -f /etc/devfs/conf.d/pilot-link ]; then
					rm /etc/devfs/conf.d/pilot-link
				fi
				
				if [ ! -d /etc/devfs/conf.d ]
				then
					mkdir -p /etc/devfs/conf.d
				fi

				# convert ttyS? -> tts/? (devfs name)
				port_devfs=$(echo $port | sed -e 's/ttyS/tts\//')

				# convert ttyUSB? -> usb/tts/? (devfs name)
				port_devfs=$(echo $port | sed -e 's/ttyUSB/usb\/tts\//')

				echo "REGISTER  ^$port_devfs$ CFUNCTION GLOBAL symlink \$devname pilot" > $devfs_cfg
				echo "REGISTER	^$port_devfs$	PERMISSIONS	root.root	0666" >> $devfs_cfg
				echo "UNREGISTER ^$port_devfs$ CFUNCTION GLOBAL unlink pilot" >> $devfs_cfg
			else
				# the admin chooses to manage the link himself
				rm -f /dev/pilot /etc/devfs/conf.d/libpisock8
			fi
		fi

		# ends debconf
		db_stop
    ;;

    abort-upgrade|abort-remove|abort-deconfigure)

    ;;

    *)
        echo "postinst called with unknown argument \`$1'" >&2
        exit 0
    ;;
esac

# dh_installdeb will replace this with shell code automatically
# generated by other debhelper scripts.

#DEBHELPER#

exit 0

