#!/bin/sh

#
# Configuration reset script for spxsysconf
#

reset() {
    # Erase failsafe stored data
    mtd="$(sed -e '/"failsafe-data"$/{s,:.*,,;p};d' /proc/mtd)"
    if [ -n "$mtd" ]; then
	flash_eraseall -q /dev/"$mtd"
    fi
    # Erase the fwconfig variable from U-Boot env if present to avoid
    # resets on future boots
    fwconfig="$(fw_printenv -n fwconfig 2>/dev/null)"
    if [ -n "$fwconfig" ]; then
	fw_setenv fwconfig
    fi
    # Erase the mainexargs variable from U-Boot env if present since
    # it contains the non-default kernel settings
    mainexargs="$(fw_printenv -n mainexargs 2>/dev/null)"
    if [ -n "$mainexargs" ]; then
	fw_setenv mainexargs
    fi
    # Erase the maxtemp variable from U-Boot env to revert to default
    maxtemp="$(fw_printenv -n maxtemp 2>/dev/null)"
    if [ -n "$maxtemp" ]; then
	fw_setenv maxtemp
    fi
    rm -f /etc/hostname /etc/apache/conf.d/30-spxserial.conf \
	/etc/network/spxproxy.conf /etc/network/modem.conf \
	/etc/chatscripts/modem /etc/ppp/peers/modem \
	/etc/spinetix/licenses /etc/spinetix/configured /var/lib/spx-ntp/drift \
	/var/lib/spinetix/recovery-splash-set
    for f in /etc/spinetix/spx-ntp.conf /etc/snmp/snmpd.local.conf \
	/etc/default/media-mount /etc/default/ntpdate \
	/etc/default/bootpause /etc/network/interfaces; do
        cp -a $f.spxsave $f
    done
    cat /dev/null > /etc/network/resolv.conf.static
    cat /dev/null > /etc/ppp/modem-password
    cat /dev/null > /etc/chatscripts/modem-pin
    /etc/spinetix/spxsysconf restore
    /etc/spinetix/spxsysconf config
    # Clear state of some system daemons
    rm -rf /var/lib/dhcpc
    # Clear ssh host keys
    rm -f /etc/ssh/ssh_host*key*

    # NOTE: we do not clear logs any longer since it prevents diagnosing
    # problems after which the user did a "reset to factory defaults".
    #find /var/log -mindepth 1 -depth -type f -exec cp /dev/null \{\} \;
    #rm -f /var/lib/logrotate.status

    # Remove cache files
    find /var/cache -mindepth 1 -depth -type f -print0 | xargs -0r rm -f --
}

#
# Main
#

case "$1" in
    reset)
        reset
    ;;
    *)
        echo "Usage $0 {reset}" >&2
	exit 1
    ;;
esac
