#!/bin/sh

#
# Configuration reset script for spxmanage
#

. /etc/spxmanage/init-functions

init_dirs

reset() {
    # Make sure that the shadow dir is mounted
    mount_shadow_dir
    # Clean all generated files
    clean "$CONTENTDIR" "$SHADOWCONTENTDIR" \
        "$SPOOLDIR" \
        "$PUBLICINTERFACEDIR" "$PROTECTEDINTERFACEDIR" "$TMPINTERFACEDIR" \
        "$UIVARDIR"
    # Put back the default content
    copy_default_content
    # Zap all locks from the dav lock database 
    clean_davlockdb
    # remove the SSL/TLS certificates added by the web admin interface
    # they are the *.pem files and hash links to them.
    # This is the legacy location (they are now under /etc/pki/spxmanage/certs/)
    # and some distros may make /usr/lib/ssl/certs a symlink to /etc/ssl/certs,
    # in which case it should not be touched.
    if [ -e /usr/lib/ssl/certs -a ! -L /usr/lib/ssl/certs ]; then
        find /usr/lib/ssl/certs/ -maxdepth 1 \
            \( -regex ".*/[a-f0-9]+\.[0-9]+" -o -name "*.pem" \) -delete
    fi
    # Remove the passwords / admin / content / log access restriction /
    # activated certificates / configured indicator / ARYA mode indicator
    rm -f /etc/apache2/conf.d/95-raperca-cont-prot.conf \
        /etc/apache2/conf.d/95-raperca-adm-prot.conf \
        /etc/apache2/conf.d/95-raperca-log-prot.conf \
        /etc/apache2/conf.d/95-raperca-ro.conf \
        /etc/apache2/server.crt /etc/apache2/server.key \
        /etc/spxmanage/htpasswd /etc/spxmanage/htgroup \
        /etc/spxmanage/configured /etc/spxmanage/arya-settings \
        /etc/modprobe.d/fukiran-audio.conf
    # Remove the local SSL/TLS certificate data (keep dir structure)
    find /etc/pki/spxmanage/ \! -type d -delete
    # Remove all SRP secret files, keeping TAG file
    find /etc/spxmanage/srpsecrets -mindepth 1 \! -name "*.TAG" -delete
    # Remove config data applied via media-mount
    find /var/cache/spxmanage/media-mount-config -mindepth 1 -delete
    # Remove other cache files
    rm -f /var/cache/spxmanage/wifi-cfg-hw-address /var/cache/spxmanage/wifi-cfg-passphrase
    # Remove directories and files created via tmpfiles.d
    rm -rf /var/lib/spxmanage/api-keys /etc/spxmanage/htsecrets
    # Redo the certificate database from scratch to remove local certs
    update-ca-certificates -f
    # Restore configuration files to default
    for f in /etc/default/spxmanage-spxupnpd \
            /etc/default/spxmanage-mdns \
            /etc/apache2/conf.d/01-spxmanage-defs.conf; do
        cp -a $f.spxsave $f
    done
    # Remove configuration files which do not exist by default, are not
    # owned by any package, but are managed by this package.
    rm -f /etc/default/avahi-daemon /etc/default/llmnrd

    # Clean SNMP configuration
    rm -f /etc/default/snmpd
}

#
# Main
#

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