#!/bin/bash

[ "$EUID" -ne 0 ] && echo "Please run as root." && exit

DPTFXTRACT=/usr/bin/dptfxtract-static
CONF=/etc/thermald/thermal-conf.xml.auto
BIOS_INFO=/var/lib/dptfxtract/bios-version
DUMP=acpidump
AUTO_UPDATE=""

TMPDIR=`mktemp -d`
cd $TMPDIR

finish()
{
    rm -rf $TMPDIR
    exit $1
}

update_conf()
{
    # XXX: Ideally we can run dptfxtract with a non-root user (need
    # upstream fix), like:
    #   su _dptfxtract -c dptfxtract $TMPDIR/*.dat -o $TMPDIR
    $DPTFXTRACT -o $TMPDIR > /dev/null

    if [ ! -f $TMPDIR/thermal-conf.xml.auto ]; then
        echo "Your machine does not support DPTF."
        finish
    fi

    if [ -f $CONF ]; then
        mv --backup $CONF $CONF.bak
    cat << _EOF

An existing config file is found in $CONF,
which has been backed up to $CONF.bak. 
If you have made any changes to it, please update the new config file,
otherwise, you can remove $CONF.bak.

_EOF
    fi

    $DPTFXTRACT

    (echo -e "thermal-conf.xml.auto was generated with the following BIOS on "`date`":\n"; \
        dmidecode -t 0 | sed '/^BIOS Information/,$!d' ) > $BIOS_INFO
}

restart_thermald()
{
    if [ -f $CONF ]; then
        if `systemctl is-active thermald > /dev/null 2>&1`; then
            systemctl --no-block reload-or-restart thermald
        fi
    fi
}

OPTS=`getopt -o u: --long auto-update: -n 'dptfxtract' -- "$@"`
eval set -- "$OPTS"
while true; do
    case "$1" in
        -u | --auto-update) AUTO_UPDATE=$2; shift 2 ;;
        --) shift; break ;;
        *)  break ;;
    esac
done

if [ -n "$AUTO_UPDATE" ]; then
    case "$AUTO_UPDATE" in
        yes)
            if [ -f $BIOS_INFO ]; then
                dmidecode -t 0 | sed '/^BIOS Information/,$!d' > $TMPDIR/curr_bios_info
                tail -n +3 $BIOS_INFO > $TMPDIR/last_bios_info

                if ! `diff -q $TMPDIR/{curr,last}_bios_info > /dev/null 2>&1`; then
                    update_conf
                fi
            fi ;;
        *) ;;
    esac
else
    # Call without any options
    update_conf
fi

restart_thermald
finish
