#!/bin/sh
# $Id$
# postinst script for weewx debian package
# Copyright 2013 Matthew Wall
#
# ways this script might be invoked:
#
# 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]

# abort if any command returns error
set -e

# get debconf stuff so we can set configuration defaults
. /usr/share/debconf/confmodule

if [ "$1" != configure ]; then
    exit 0
fi

# precompile the bytecode
#python -m compileall /usr/share/weewx

# configure for system startup but do not enable
update-rc.d weewx defaults > /dev/null

# insert any configuration variables into the configuration files
cfgfile=/etc/weewx/weewx.conf

db_get weewx/location
sed -i "s%location =.*%location = \"$RET\"%" $cfgfile

db_get weewx/latlon
lat=$(echo $RET | cut -d, -f1)
lon=$(echo $RET | cut -d, -f2)
sed -i "s%latitude[ ]*=.*%latitude = $lat%" $cfgfile
sed -i "s%longitude[ ]*=.*%longitude = $lon%" $cfgfile

db_get weewx/altitude
a=$(echo $RET | cut -d, -f1)
u=$(echo $RET | cut -d, -f2)
sed -i "s%altitude[ ]*=.*%altitude = $a, $u%" $cfgfile

# FIXME: generalize this so it does not have to be modified every time a
#        new station type is added or new station options are added.
# FIXME: figure out a mechanism to prevent modification of variables with
#        same name, e.g., [Vantage].host and [Databases][stats_mysql].host
db_get weewx/station_type
if [ "$RET" != "" ]; then
    sed -i "s%station_type[ ]*=.*%station_type = $RET%" $cfgfile
    if [ "$RET" = "Vantage" ]; then
        db_get weewx/vantage_type
        sed -i "s% type[ ]*=.*% type = $RET%" $cfgfile
        if [ "$RET" = "serial" ]; then
            db_get weewx/vantage_port
            sed -i "s% port[ ]*=.*% port = $RET%" $cfgfile
        else
            db_get weewx/vantage_host
            sed -i "s%host[ ]*=.*%host = $RET%" $cfgfile
        fi
    fi
    if [ "$RET" = "WMR-918" ]; then
        db_get weewx/wmr918_port
        sed -i "s% port[ ]*=.*% port = $RET%" $cfgfile
    fi
    if [ "$RET" = "FineOffsetUSB" ]; then
        db_get weewx/fousb_model
        sed -i "s%model[ ]*=.*%model = $RET%" $cfgfile
    fi
fi

# start the weewx daemon
invoke-rc.d weewx start

# let debconf know that we are finished
db_stop

exit 0
