#! /bin/sh -e
#Chooses the appropriate lirc driver,
#lircrc, and lircd.conf for the options
#Chosen during installation
# Written by Mario Limonciello <superm1@ubuntu.com>
# Copyright (C) 2007 Mario Limonciello

. /usr/share/debconf/confmodule

if [ "$1" ]; then
    ROOT="$1"
    chroot=chroot
    log='log-output -t mythbuntu'
fi

db_get mythbuntu/en_lirc
EN_LIRC="$RET"
if [ "$EN_LIRC" = true ]; then

    db_get lirc/remote
    REMOTE="$RET"

    if [ "$REMOTE" != "None" ]; then
        db_get lirc/modules
        MODULES="$RET"
        db_get lirc/lircd_conf
        CONF="$RET"
        db_get lirc/driver
        DRIVER="$RET"

        if [ "$MODULES" = "none" ]; then
            MODULES=""
        fi

        SUPPORTED_DRIVERS=`lircd -H help 2>&1 | awk '$0!~/^S|^D/{print $1}' | tr '\n' '\ '`
        if echo "$SUPPORTED_DRIVERS" | grep -v "$DRIVER" > /dev/null; then
            DRIVER=""
        fi

        cat > $ROOT/tmp/lirc_setup <<EOF
#!/bin/sh
. /usr/share/debconf/confmodule
#Prefill lirc package settings
#and call maintainer scripts

db_set lirc/remote "$REMOTE"
db_set lirc/modules "$MODULES"
db_set lirc/lircd_conf "$CONF"
db_set lirc/driver "$DRIVER"
db_fset lirc/reconfigure config_changed true

mv /sbin/udevd /sbin/udevd.temp
/var/lib/dpkg/info/lirc.postinst configure
mv /sbin/udevd.temp /sbin/udevd
EOF
        chmod +x $ROOT/tmp/lirc_setup
        $log $chroot $ROOT /tmp/lirc_setup
        if [ -x /usr/bin/mythbuntu-lircrc-generator ]; then
            mythbuntu-lircrc-generator --lircd $ROOT/etc/lirc/lircd.conf --lircrc /tmp/lircrc

            db_get passwd/username
            USER=$RET
            cp /tmp/lircrc $ROOT/home/$USER/.lircrc
            cp /tmp/lircrc $ROOT/home/mythtv/.lircrc
            mkdir -p $ROOT/home/$USER/.mythtv
            mkdir -p $ROOT/home/mythtv/.mythtv
            ln -s /home/$USER/.lircrc $ROOT/home/$USER/.mythtv/lircrc
            ln -s /home/mythtv/.lircrc $ROOT/home/mythtv/.mythtv/lircrc
            chown mythtv:mythtv $ROOT/home/mythtv -R
            chown 1000:1000 $ROOT/home/$USER -R
        fi
    fi
fi

exit 0
