sync-vpn-status.sh 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. #!/bin/bash
  2. # Script per sincronizzare lo stato VPN con il database
  3. # Salva come: storage/scripts/sync-vpn-status.sh
  4. # Aggiungi al cron: */5 * * * * /var/www/polizia/storage/scripts/sync-vpn-status.sh
  5. SCRIPT_DIR="$(dirname "$0")"
  6. LARAVEL_DIR="$(dirname "$(dirname "$SCRIPT_DIR")")"
  7. LOG_FILE="$SCRIPT_DIR/../logs/vpn-status-sync.log"
  8. # Funzione di logging
  9. log_message() {
  10. echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" >> "$LOG_FILE"
  11. }
  12. # Controlla se AnyConnect è installato
  13. if [[ ! -f "/opt/cisco/anyconnect/bin/vpn" ]]; then
  14. log_message "ERROR: Cisco AnyConnect not found"
  15. exit 1
  16. fi
  17. # Ottieni lo stato reale del sistema
  18. VPN_OUTPUT=$(/opt/cisco/anyconnect/bin/vpn state 2>/dev/null)
  19. SYSTEM_STATUS="unknown"
  20. if echo "$VPN_OUTPUT" | grep -q "state: Connected"; then
  21. SYSTEM_STATUS="connected"
  22. elif echo "$VPN_OUTPUT" | grep -q "Disconnected"; then
  23. SYSTEM_STATUS="disconnected"
  24. fi
  25. log_message "INFO: System VPN status detected: $SYSTEM_STATUS"
  26. # Ottieni lo stato dal database
  27. cd "$LARAVEL_DIR"
  28. DB_STATUS=$(php artisan tinker --execute="echo \DB::table('vpn_status')->first()->status ?? 'no_record';" 2>/dev/null | tail -1)
  29. log_message "INFO: Database VPN status: $DB_STATUS"
  30. # Aggiorna il database se necessario
  31. if [[ "$SYSTEM_STATUS" != "$DB_STATUS" && "$SYSTEM_STATUS" != "unknown" ]]; then
  32. log_message "INFO: Status mismatch detected. Updating database from '$DB_STATUS' to '$SYSTEM_STATUS'"
  33. php artisan tinker --execute="
  34. \DB::table('vpn_status')->updateOrInsert(
  35. ['id' => 1],
  36. [
  37. 'status' => '$SYSTEM_STATUS',
  38. 'last_update' => now(),
  39. 'updated_at' => now(),
  40. ]
  41. );
  42. echo 'Database updated successfully';
  43. " >> "$LOG_FILE" 2>&1
  44. log_message "SUCCESS: Database status updated to: $SYSTEM_STATUS"
  45. else
  46. log_message "INFO: Status already in sync: $SYSTEM_STATUS"
  47. fi