#!/bin/bash
# postinst script for test
#
# 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>
#        * <postinst> `abort-remove'
#        * <deconfigured's-postinst> `abort-deconfigure' `in-favour'
#          <failed-install-package> <version> `removing'
#          <conflicting-package> <version>
# for details, see http://www.debian.org/doc/debian-policy/ or
# the debian-policy package

configure()
{
DATE=$(date --rfc-3339='date')
CONFIG_BACKUP=/etc/OpenBTS/OpenBTS.dump-$DATE


if [ ! -e $CONFIG_BACKUP ]; then
        sqlite3 /etc/OpenBTS/OpenBTS.db ".dump" > $CONFIG_BACKUP
fi

sqlite3 /etc/OpenBTS/OpenBTS.db ".read /etc/OpenBTS/subscriberRegistry.example.sql" > /dev/null 2>&1

if [ ! -d /var/lib/asterisk/sqlite3dir ]; then
	mkdir -p /var/lib/asterisk/sqlite3dir
fi

SRPATH=/var/lib/asterisk/sqlite3dir/sqlite3.db

DATE=$(date --rfc-3339='date')
SR_CONFIG_BACKUP=$SRPATH.dump-$DATE


if [[ -e $SRPATH && "`sqlite3 $SRPATH "PRAGMA table_info(sip_buddies)" || true`" != "" ]]; then
	if [ ! -e $SR_CONFIG_BACKUP ]; then
		sqlite3 $SRPATH ".dump" > $SR_CONFIG_BACKUP
	fi

	HASPREPAID=`sqlite3 $SRPATH "PRAGMA table_info(sip_buddies)" | grep prepaid || true`
	if [ "$HASPREPAID" = "" ]; then
		sqlite3 $SRPATH "alter table sip_buddies add prepaid int(1) DEFAULT 0 not null"
	fi

	HASBALANCE=`sqlite3 $SRPATH "PRAGMA table_info(sip_buddies)" | grep account_balance || true`
	if [ "$HASBALANCE" = "" ]; then
		sqlite3 $SRPATH "alter table sip_buddies add column account_balance int(9) default 0"
	fi

	sqlite3 $SRPATH "create table if not exists rates (service varchar(30) unique not null, rate integer not null)"
	sqlite3 $SRPATH "insert or ignore into 'rates' values ('in-network-SMS', 10)"
	sqlite3 $SRPATH "insert or ignore into 'rates' values ('out-of-network-SMS', 20)"
	sqlite3 $SRPATH "insert or ignore into 'rates' values ('in-network-call', 1)"
	sqlite3 $SRPATH "insert or ignore into 'rates' values ('out-of-network-call', 1)"
fi


# set up permissions for webui, temporary fix until ui is replumbed to use json
# directory permissions
chown -R root:www-data /var/lib/asterisk/sqlite3dir
chmod 775 /var/lib/asterisk/sqlite3dir/
if [ -e /var/lib/asterisk/sqlite3dir/sqlite3.db ]; then
	chmod 664 /var/lib/asterisk/sqlite3dir/sqlite3*
fi

}

case "$1" in
    configure)
	configure
    ;;

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

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

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

#DEBHELPER#

exit 0
