#!/usr/bin/env bash
set -euo pipefail

RESET_FLAG="/opt/Backend/Inbox/FACTORYRESET"
DEFAULTS_DIR="/opt/Backend/Defaults"
APPS_DIR="/opt/Backend/Apps"

log() {
    echo "$(date) $1"
}

# ================================
# Helper: Restore Apps from Defaults
# ================================
restore_apps() {
    log "Restoring Apps folder from Defaults..."

    rm -rf "$APPS_DIR"
    cp -r "$DEFAULTS_DIR" "$APPS_DIR"

    # Verify
    if [ ! -d "$APPS_DIR" ] || [ -z "$(ls -A "$APPS_DIR")" ]; then
        log "ERROR: Apps folder restoration failed!"
        # Used only when called from factory-reset, see below.
        return 1
    fi

    log "Apps folder restored successfully."
    return 0
}

# ================================
# Factory Reset Trigger
# ================================
if [ -f "$RESET_FLAG" ]; then
    log "FACTORYRESET flag detected. Starting factory reset..."
    
    if ! restore_apps; then
        log "Factory reset failed — rebooting..."
        sudo /sbin/reboot
        exit 1
    fi

    log "Removing reset flag..."
    rm -f "$RESET_FLAG"

    log "Factory reset completed successfully."
    exit 0
fi

# ================================
# Apps folder missing or empty → Auto-repair
# ================================
if [ ! -d "$APPS_DIR" ] || [ -z "$(ls -A "$APPS_DIR" 2>/dev/null)" ]; then
    log "Apps folder is missing or empty. Repairing from Defaults..."
    restore_apps
    exit 0
fi

exit 0