#!/bin/bash
#
# MCU Factory Reset Script v1.1.0
# Created by Enrico Buttignol (ebuttignol@messana.tech)
# Copyright by Messana Hydronic Technologies
# Modified by Sevan v1.1.0

set -e

# Log file
LOG_DIR="/usr/share/messana/logs"
LOG_FILE="$LOG_DIR/mcu-factory-reset.log"
mkdir -p "$LOG_DIR"
touch "$LOG_FILE"
chmod 0644 "$LOG_FILE"

log() {
  echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*" >> "$LOG_FILE"
}

log "=== MCU Factory Reset started (user=$(id -un) uid=$(id -u) script=$(readlink -f "$0")) ==="

# Define variables
OPENVPN_DIR="/etc/openvpn"
LOGIC_DB_DIR="/usr/share/logic/db"
LOGS_DIR="/usr/share/messana/logs"
VPN_SOURCE="/usr/share/messana/vpn/9999-9999.conf"
VPN_TARGET="$OPENVPN_DIR/9999-9999.conf"

# Step 1: Remove old VPN config files
log "[1] Removing old VPN configuration files..."
find "$OPENVPN_DIR" -maxdepth 1 -type f -regextype posix-extended \
  -regex ".*/[0-9]{4}-[0-9]{3,4}(-[0-9]{2})?\.conf" -exec rm -f {} \; >>"$LOG_FILE" 2>&1

# Step 2: Copy new VPN config
log "[2] Copying new VPN configuration file..."
cp "$VPN_SOURCE" "$VPN_TARGET" >>"$LOG_FILE" 2>&1

# Step 3: Apply correct permissions
log "[3] Setting permissions on VPN config..."
chmod 0600 "$VPN_TARGET" >>"$LOG_FILE" 2>&1

# Step 4: Stop services
log "[4] Stopping services..."
systemctl stop mrccomm >>"$LOG_FILE" 2>&1 || true
systemctl stop mrchistory >>"$LOG_FILE" 2>&1 || true
systemctl stop mrclogic >>"$LOG_FILE" 2>&1 || true
systemctl stop mrcalert >>"$LOG_FILE" 2>&1 || true
systemctl stop redis >>"$LOG_FILE" 2>&1 || true
systemctl stop redis-server >>"$LOG_FILE" 2>&1 || true

# Step 5: Clear logic DB
log "[5] Clearing logic DB directory..."
rm -f "$LOGIC_DB_DIR"/* >>"$LOG_FILE" 2>&1 || true

# Step 6: Remove Redis RDB files
log "[6] Removing Redis RDB files..."
rm -f /var/lib/redis/*.rdb >>"$LOG_FILE" 2>&1 || true

# Step 7: Remove log files (comment this line if you want to keep logs)
log "[7] Removing log files..."
rm -f "$LOGS_DIR"/*

# Step 8: Shutdown system
# log "[8] Powering off the system..."
sync
systemctl poweroff >>"$LOG_FILE" 2>&1