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

# make sure Backend has all file permissions in order
sudo vbupd

sudo Chromium_unlock_profile.sh

RESET_FLAG="/opt/Backend/Inbox/FACTORYRESET"
INBOX_DIR="/opt/Backend/Inbox"
BACKEND_DIR="/opt/Backend"
DEFAULTS_DIR="/opt/Backend/Defaults"
APPS_DIR="/opt/Backend/Apps"
SYS_BACKUP_DIR="$BACKEND_DIR/SysBackup"
RUNUPDATE_FLAG="$INBOX_DIR/RUNUPDATE"
UPDATE_META="$INBOX_DIR/UPDATE"

SD_MOUNT_SCRIPT="/usr/local/sbin/mount_sdcard.sh"
SD_MOUNT_POINT="/mnt/sdcard"
RESTORE_FLAG="$INBOX_DIR/RESTORE_BACKUP"

SET_IP_SCRIPT="/usr/local/sbin/set_ip_settings.sh"
CONFIGURE_DHCP_SERVER_SCRIPT="/usr/local/sbin/configure_dhcp_server.sh"

# FDC factory default network settings:
# - LAN1 is eth1
# - LAN2 is eth0
LAN1_IFACE="eth1"
LAN1_DEFAULT_IP="192.168.100.1"
LAN1_DEFAULT_SUBNET="255.255.240.0"
LAN1_DEFAULT_GATEWAY="0.0.0.0"
LAN1_DEFAULT_DNS1="0.0.0.0"
LAN1_DEFAULT_DNS2="0.0.0.0"
LAN1_DEFAULT_DHCP_SERVER_STATE="on"

LAN2_IFACE="eth0"

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
}

restore_network_defaults() {
    log "Restoring ethernet settings to factory defaults..."

    if [ ! -x "$SET_IP_SCRIPT" ]; then
        log "ERROR: Missing or non-executable script: $SET_IP_SCRIPT"
        return 1
    fi

    if [ ! -x "$CONFIGURE_DHCP_SERVER_SCRIPT" ]; then
        log "ERROR: Missing or non-executable script: $CONFIGURE_DHCP_SERVER_SCRIPT"
        return 1
    fi

    if ! sudo "$SET_IP_SCRIPT" "$LAN1_IFACE" "static" \
        "$LAN1_DEFAULT_IP" "$LAN1_DEFAULT_SUBNET" "$LAN1_DEFAULT_GATEWAY" "$LAN1_DEFAULT_DNS1" "$LAN1_DEFAULT_DNS2"; then
        log "ERROR: Failed to set LAN1 ($LAN1_IFACE) static defaults."
        return 1
    fi

    if ! sudo "$CONFIGURE_DHCP_SERVER_SCRIPT" "$LAN1_IFACE" "$LAN1_DEFAULT_DHCP_SERVER_STATE"; then
        log "ERROR: Failed to configure LAN1 DHCP server state."
        return 1
    fi

    if ! sudo "$SET_IP_SCRIPT" "$LAN2_IFACE" "dhcp"; then
        log "ERROR: Failed to set LAN2 ($LAN2_IFACE) to DHCP."
        return 1
    fi

    log "Ethernet settings restored successfully."
    return 0
}

cleanup_restore_flag() {
    log "Cleaning up RESTORE_BACKUP flag..."
    rm -f "$RESTORE_FLAG"
}

# ================================
# 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

    if ! restore_network_defaults; then
        log "Factory reset failed while restoring network defaults — rebooting..."
        sudo /sbin/reboot
        exit 1
    fi

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

    log "Factory reset completed successfully."
    exit 0
fi

# ================================
# RESTORE_BACKUP: Restore app from SD backup
# ================================
if [ -f "$RESTORE_FLAG" ]; then
        log "RESTORE_Backup flag detected. Starting restore from SD card..."
    
        # Ensure flag is always removed on failure or exit
        trap cleanup_restore_flag EXIT

    BACKUP_FILE_NAME=$(tr -d '\r\n' < "$RESTORE_FLAG")

    APPS_CONFIG="$APPS_DIR/config.json"
    
    if [ ! -f "$APPS_CONFIG" ]; then
        log "ERROR: Apps config not found: $APPS_CONFIG"
        cleanup_restore_flag
        exit 1
    fi
    
    TARGET_APP=$(grep -o '"defaultApp"[[:space:]]*:[[:space:]]*"[^"]*"' "$APPS_CONFIG" \
        | sed 's/.*"defaultApp"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/')
    
    if [ -z "$TARGET_APP" ]; then
        log "ERROR: defaultApp not found in $APPS_CONFIG"
        cleanup_restore_flag
        exit 1
    fi
    
    TARGET_APP_DIR="$APPS_DIR/$TARGET_APP"

    log "Resolved active app from config.json: $TARGET_APP"


    if [ -z "$BACKUP_FILE_NAME" ]; then
        log "ERROR: RESTORE_BACKUP file is empty."
        exit 1
    fi

    if [ ! -x "$SD_MOUNT_SCRIPT" ]; then
        log "ERROR: mount_sdcard.sh not found or not executable."
        exit 1
    fi

    log "Mounting SD card..."
    if ! sudo "$SD_MOUNT_SCRIPT"; then
        log "ERROR: Failed to mount SD card."
        exit 1
    fi

    BACKUP_PATH="$SD_MOUNT_POINT/$BACKUP_FILE_NAME"

    if [ ! -f "$BACKUP_PATH" ]; then
        log "ERROR: Backup file not found on SD card: $BACKUP_PATH"
        exit 1
    fi

    if [ ! -d "$TARGET_APP_DIR" ]; then
        log "ERROR: Target app directory does not exist: $TARGET_APP_DIR"
        exit 1
    fi

    log "Clearing existing app in $TARGET_APP_DIR"
    find "$TARGET_APP_DIR" -maxdepth 1 -type f -exec rm -f {} +

    log "Extracting backup into $TARGET_APP_DIR..."
    
    if ! command -v unzip >/dev/null 2>&1; then
        log "ERROR: unzip is not installed."
        exit 1
    fi
    
    if ! unzip -o "$BACKUP_PATH" -d "$TARGET_APP_DIR"; then
        log "ERROR: Failed to extract backup."
        exit 1
    fi

    log "Restore completed successfully."

    log "Removing RESTORE_Backup flag..."
    rm -f "$RESTORE_FLAG"

    exit 0
fi

# ================================
# RUNUPDATE: Apply system update
# ================================
if [ -f "$RUNUPDATE_FLAG" ]; then
    log "RUNUPDATE flag detected. Starting update..."

    if [ ! -f "$UPDATE_META" ]; then
        log "ERROR: UPDATE metadata file not found in Inbox. Aborting update."
        exit 1
    fi

    # For now we just look for a FUN1500*.zip file in the Inbox
    UPDATE_ZIP=$(find "$INBOX_DIR" -maxdepth 1 -type f -name 'FUN1500_*.zip' | sort | tail -n 1 || true)

    if [ -z "$UPDATE_ZIP" ]; then
        log "ERROR: No FUN1500_*.zip file found in Inbox. Aborting update."
        exit 1
    fi

    if ! command -v unzip >/dev/null 2>&1; then
        log "ERROR: 'unzip' is not installed. Cannot apply update."
        exit 1
    fi

    log "Using update archive: $UPDATE_ZIP"

    # Prepare backup directory
    mkdir -p "$SYS_BACKUP_DIR"

    if [ -d "$SYS_BACKUP_DIR/Bin" ] || [ -d "$SYS_BACKUP_DIR/Defaults" ]; then
        log "Cleaning previous backup in $SYS_BACKUP_DIR..."
        rm -rf "$SYS_BACKUP_DIR/Bin" "$SYS_BACKUP_DIR/Defaults"
    fi

    # Move current Bin and Defaults to backup (if they exist)
    if [ -d "$BACKEND_DIR/Bin" ]; then
        log "Moving Bin to SysBackup..."
        mv "$BACKEND_DIR/Bin" "$SYS_BACKUP_DIR/"
    else
        log "No existing Bin folder to back up."
    fi

    if [ -d "$BACKEND_DIR/Defaults" ]; then
        log "Moving Defaults to SysBackup..."
        mv "$BACKEND_DIR/Defaults" "$SYS_BACKUP_DIR/"
    else
        log "No existing Defaults folder to back up."
    fi

    # Extract new version into /opt/Backend (flat structure: Bin + Defaults)
    log "Extracting update archive into $BACKEND_DIR..."
    if ! unzip -o "$UPDATE_ZIP" -d "$BACKEND_DIR"; then
        log "ERROR: Failed to extract update archive. Backup remains in $SYS_BACKUP_DIR."
        exit 1
    fi

    # Remove RUNUPDATE flag so we don't reapply on next boot
    rm -f "$RUNUPDATE_FLAG"

    # Remove updates
     rm -f "$UPDATE_META"
     rm -f "$UPDATE_ZIP"
     
     # ================================
     # Update UI folders in Apps/
     # ================================
     log "Updating UI folders in Apps..."
 
     for APP_PATH in "$DEFAULTS_DIR"/* ; do
         [ -d "$APP_PATH" ] || continue   # skip non-directories
 
         APP_NAME=$(basename "$APP_PATH")
         SRC_UI="$DEFAULTS_DIR/$APP_NAME/UI"
         DEST_UI="$APPS_DIR/$APP_NAME/UI"
 
         # Only copy if UI exists in Defaults
         if [ -d "$SRC_UI" ]; then
             log "Updating UI for $APP_NAME..."
 
             # Remove existing UI folder if present
             if [ -d "$DEST_UI" ]; then
                 rm -rf "$DEST_UI"
             fi
 
             # Copy new UI
             mkdir -p "$APPS_DIR/$APP_NAME"
             cp -r "$SRC_UI" "$DEST_UI"
         fi
     done
 
     log "Update completed successfully."
     
     # Set ownership, permissions, execution rights and port rights below 1024
     sudo vbupd
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
