#!/bin/bash
# Script to copy crash investigation logs to user directory
# Run on remote server: bash copy_crash_logs.sh

set -e  # Exit on error

echo "Creating investigation directory..."
mkdir -p ~/crash_investigation

echo "Copying nginx logs..."
sudo cp /var/log/nginx/posterg_error.log ~/crash_investigation/
sudo cp /var/log/nginx/posterg_error.log.1 ~/crash_investigation/ 2>/dev/null || true
sudo cp /var/log/nginx/posterg_access.log ~/crash_investigation/
sudo cp /var/log/nginx/posterg_access.log.1 ~/crash_investigation/ 2>/dev/null || true
sudo cp /var/log/nginx/posterg_error.log.2.gz ~/crash_investigation/ 2>/dev/null || true
sudo cp /var/log/nginx/posterg_access.log.2.gz ~/crash_investigation/ 2>/dev/null || true

echo "Exporting journal from previous boot..."
sudo journalctl -b -1 --no-pager > ~/crash_investigation/journal_previous_boot.log 2>&1

echo "Exporting journal around crash time..."
sudo journalctl -b -1 --since "2026-03-24 11:00" --until "2026-03-24 14:00" --no-pager > ~/crash_investigation/journal_crash_time.log 2>&1

echo "Exporting kernel messages..."
sudo journalctl -b -1 -k --no-pager > ~/crash_investigation/kernel_messages.log 2>&1

echo "Copying PHP-FPM logs..."
sudo cp /var/log/php8.4-fpm.log ~/crash_investigation/ 2>/dev/null || true
sudo cp /var/log/php8.4-fpm.log.1 ~/crash_investigation/ 2>/dev/null || true

echo "Exporting PHP-FPM service logs..."
sudo journalctl -u php8.4-fpm -b -1 --no-pager > ~/crash_investigation/php-fpm_service.log 2>&1

echo "Exporting nginx service logs..."
sudo journalctl -u nginx -b -1 --no-pager > ~/crash_investigation/nginx_service.log 2>&1

echo "Exporting dmesg..."
sudo dmesg -T > ~/crash_investigation/dmesg.log 2>&1 || true

echo "Fixing permissions..."
sudo chown -R theophile:theophile ~/crash_investigation/

echo ""
echo "✓ Files copied successfully!"
echo ""
echo "Contents of ~/crash_investigation/:"
ls -lh ~/crash_investigation/
echo ""
echo "Total size:"
du -sh ~/crash_investigation/
echo ""
echo "To download to your local machine, run:"
echo "  scp -P 3274 -r theophile@posterg.erg.be:~/crash_investigation/ ."
