#!/bin/bash

# Wekan Log Rotation Setup Script
# This script sets up log rotation for Wekan snap installation

set -e

# Configuration
SNAP_NAME="wekan"
SNAP_COMMON="/var/snap/${SNAP_NAME}/common"
LOGROTATE_DIR="/etc/logrotate.d"
WEKAN_LOGROTATE_CONF="${LOGROTATE_DIR}/${SNAP_NAME}"

# Log file paths
MONGODB_LOG="${SNAP_COMMON}/mongodb.log"
WEKAN_APP_LOG="${SNAP_COMMON}/wekan-app.log"
WEKAN_ERROR_LOG="${SNAP_COMMON}/wekan-error.log"

# Log rotation configuration
ROTATE_SIZE="100M"
KEEP_DAYS="30"
KEEP_COPIES="10"

log_message() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1"
}

log_error() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] ERROR: $1" >&2
}

# Check if running as root
if [ "$EUID" -ne 0 ]; then
    log_error "This script must be run as root"
    exit 1
fi

# Check if snap is installed
if ! snap list | grep -q "^${SNAP_NAME} "; then
    log_error "Snap ${SNAP_NAME} is not installed"
    exit 1
fi

log_message "Setting up log rotation for Wekan snap..."

# Create logrotate configuration
cat > "${WEKAN_LOGROTATE_CONF}" << EOF
# Wekan Snap Log Rotation Configuration
# Generated by wekan logrotate-setup script

# MongoDB logs
${MONGODB_LOG} {
    daily
    missingok
    rotate ${KEEP_COPIES}
    compress
    delaycompress
    notifempty
    create 644 root root
    postrotate
        # Send SIGUSR1 to MongoDB to reopen log file
        if [ -f "${SNAP_COMMON}/mongodb.pid" ]; then
            kill -USR1 \$(cat "${SNAP_COMMON}/mongodb.pid") 2>/dev/null || true
        fi
        # Alternative: restart MongoDB service if PID file doesn't exist - DISABLED
        # if [ ! -f "${SNAP_COMMON}/mongodb.pid" ]; then
        #     snap restart ${SNAP_NAME}.mongodb 2>/dev/null || true
        # fi
    endscript
}

# Wekan application logs
${WEKAN_APP_LOG} {
    daily
    missingok
    rotate ${KEEP_COPIES}
    compress
    delaycompress
    notifempty
    create 644 root root
    postrotate
        # Send SIGUSR1 to Wekan application to reopen log file
        if [ -f "${SNAP_COMMON}/wekan.pid" ]; then
            kill -USR1 \$(cat "${SNAP_COMMON}/wekan.pid") 2>/dev/null || true
        fi
        # Alternative: restart Wekan service if PID file doesn't exist
        if [ ! -f "${SNAP_COMMON}/wekan.pid" ]; then
            # snap restart ${SNAP_NAME}.wekan 2>/dev/null || true
        fi
    endscript
}

# Wekan error logs
${WEKAN_ERROR_LOG} {
    daily
    missingok
    rotate ${KEEP_COPIES}
    compress
    delaycompress
    notifempty
    create 644 root root
    postrotate
        # Send SIGUSR1 to Wekan application to reopen log file
        if [ -f "${SNAP_COMMON}/wekan.pid" ]; then
            kill -USR1 \$(cat "${SNAP_COMMON}/wekan.pid") 2>/dev/null || true
        fi
        # Alternative: restart Wekan service if PID file doesn't exist
        if [ ! -f "${SNAP_COMMON}/wekan.pid" ]; then
            # snap restart ${SNAP_NAME}.wekan 2>/dev/null || true
        fi
    endscript
}

# Size-based rotation for large log files
${SNAP_COMMON}/*.log {
    size ${ROTATE_SIZE}
    missingok
    rotate ${KEEP_COPIES}
    compress
    delaycompress
    notifempty
    create 644 root root
    sharedscripts
    postrotate
        # Generic postrotate for all log files
        # Try to signal processes to reopen log files
        for pidfile in "${SNAP_COMMON}"/*.pid; do
            if [ -f "\$pidfile" ]; then
                kill -USR1 \$(cat "\$pidfile") 2>/dev/null || true
            fi
        done
        # Restart services if no PID files found
        if [ ! -f "${SNAP_COMMON}/mongodb.pid" ] && [ ! -f "${SNAP_COMMON}/wekan.pid" ]; then
            # snap restart ${SNAP_NAME}.mongodb 2>/dev/null || true
            # snap restart ${SNAP_NAME}.wekan 2>/dev/null || true
        fi
    endscript
}
EOF

log_message "Created logrotate configuration: ${WEKAN_LOGROTATE_CONF}"

# Test logrotate configuration
if logrotate -d "${WEKAN_LOGROTATE_CONF}" >/dev/null 2>&1; then
    log_message "Logrotate configuration test passed"
else
    log_error "Logrotate configuration test failed"
    exit 1
fi

# Create log directory if it doesn't exist
mkdir -p "${SNAP_COMMON}"

# Set proper permissions
chown root:root "${WEKAN_LOGROTATE_CONF}"
chmod 644 "${WEKAN_LOGROTATE_CONF}"

# Create initial log files if they don't exist
touch "${MONGODB_LOG}" "${WEKAN_APP_LOG}" "${WEKAN_ERROR_LOG}"
chown root:root "${SNAP_COMMON}"/*.log
chmod 644 "${SNAP_COMMON}"/*.log

log_message "Log rotation setup completed successfully"
log_message "Configuration file: ${WEKAN_LOGROTATE_CONF}"
log_message "Log files will be rotated daily and when they exceed ${ROTATE_SIZE}"
log_message "Log files will be kept for ${KEEP_DAYS} days (${KEEP_COPIES} copies)"
log_message "To test log rotation manually: sudo logrotate -f ${WEKAN_LOGROTATE_CONF}"
log_message "To view logrotate status: sudo logrotate -d ${WEKAN_LOGROTATE_CONF}"

echo ""
echo "Next steps:"
echo "1. Configure MongoDB to log to file: sudo snap set ${SNAP_NAME} mongo-log-destination=snapcommon"
echo "2. Configure Wekan to log to file (if not already done)"
echo "3. Test log rotation: sudo logrotate -f ${WEKAN_LOGROTATE_CONF}"
echo "4. Monitor log files: ls -la ${SNAP_COMMON}/*.log*"
