#!/bin/sh
# Factory Reset - resets configuration to defaults

log() {
    echo "$1"
    logger -t $0 "$1"
}

APP_RESET_FLAG="/tmp/factory_reset"
UCI_DEFAULTS_BACKUP_DIR="/etc/uci-defaults-backups"
UCI_DEFAULTS_DIR="/etc/uci-defaults"
GATEWAY_CONFIG_BACKUP="/rom/etc/config/gateway"
GATEWAY_CONFIG="/etc/config/gateway"

log "Resetting configuration to defaults..."

# restore uci-defaults scripts from backup
if [ -d $UCI_DEFAULTS_BACKUP_DIR ]; then
    cp $UCI_DEFAULTS_BACKUP_DIR/* $UCI_DEFAULTS_DIR/
    if [ $? -ne 0 ]; then
        log "Failed to restore uci-defaults scripts from backup"
    fi
else
    log "UCI defaults backup directory not found: $UCI_DEFAULTS_BACKUP_DIR"
fi

# restore default gateway config file
if [ -f $GATEWAY_CONFIG_BACKUP ]; then
    cp $GATEWAY_CONFIG_BACKUP $GATEWAY_CONFIG
    if [ $? -ne 0 ]; then
        log "Failed to restore default gateway configuration file"
    fi
else
    log "Default gateway configuration file not found: $GATEWAY_CONFIG_BACKUP"
fi

# set '1' to trigger application factory reset
echo '1' > $APP_RESET_FLAG
if [ $? -ne 0 ]; then
    log "Failed to create application reset flag file: $APP_RESET_FLAG"
    exit 1
fi

# spawn a background process to check for app reset complete ($APP_RESET_FLAG = 0)
# application sends factory reset event on completion, but we add a timeout to ensure
# the system reset continues even if the application does not respond
(
    TIMEOUT=120  # seconds
    INTERVAL=1  # seconds
    ELAPSED=0

    while [ $ELAPSED -lt $TIMEOUT ]; do
        sleep $INTERVAL
        ELAPSED=$((ELAPSED + INTERVAL))

        if [ -f $APP_RESET_FLAG ]; then
            FLAG_VALUE=$(cat $APP_RESET_FLAG)
            if [ "$FLAG_VALUE" = "0" ]; then
                log "Application reset completed successfully."
                exit 0
            fi
        fi
    done

    if [ $ELAPSED -ge $TIMEOUT ]; then
        log "Timeout waiting for application reset to complete."
        log "Continue to apply factory reset..."
        ubus send gateway.config '{"changes":[["reset"]]}'
    fi
) &
