#!/bin/bash
# Privacy auto-cleanup script
# Automatically cleans up logs and temporary files for enhanced privacy
# Generated by Algo VPN privacy role

set -euo pipefail

# Configuration
LOG_MAX_AGE={{ privacy_auto_cleanup.temp_files_max_age }}
SCRIPT_LOG="/var/log/privacy-cleanup.log"

# Logging function
log_message() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" >> "$SCRIPT_LOG"
}

log_message "Starting privacy cleanup"

{% if privacy_auto_cleanup.enabled %}
# Rotate log files to prevent the cleanup log from growing
if [ -f "$SCRIPT_LOG" ] && [ $(wc -l < "$SCRIPT_LOG") -gt 1000 ]; then
    tail -n 500 "$SCRIPT_LOG" > "$SCRIPT_LOG.tmp"
    mv "$SCRIPT_LOG.tmp" "$SCRIPT_LOG"
fi

# Clean temporary files
log_message "Cleaning temporary files older than ${LOG_MAX_AGE} days"
find /tmp -type f -mtime +${LOG_MAX_AGE} -delete 2>/dev/null || true
find /var/tmp -type f -mtime +${LOG_MAX_AGE} -delete 2>/dev/null || true

# Clean old log files that may have escaped rotation
log_message "Cleaning old rotated logs"
find /var/log -name "*.log.*" -type f -mtime +{{ privacy_log_rotation.max_age }} -delete 2>/dev/null || true
find /var/log -name "*.gz" -type f -mtime +{{ privacy_log_rotation.max_age }} -delete 2>/dev/null || true

# Clean systemd journal if it exists
if [ -d /var/log/journal ]; then
    log_message "Cleaning systemd journal files"
    journalctl --vacuum-time={{ privacy_log_rotation.max_age }}d 2>/dev/null || true
    journalctl --vacuum-size=50M 2>/dev/null || true
fi

{% if privacy_auto_cleanup.clean_package_cache %}
# Clean package cache
log_message "Cleaning package cache"
apt-get clean 2>/dev/null || true
apt-get autoclean 2>/dev/null || true
{% endif %}

# Clean bash history files
log_message "Cleaning bash history files"
for user_home in /home/* /root; do
    if [ -d "$user_home" ]; then
        rm -f "$user_home/.bash_history" 2>/dev/null || true
        rm -f "$user_home/.zsh_history" 2>/dev/null || true
        rm -f "$user_home/.lesshst" 2>/dev/null || true
        rm -f "$user_home/.viminfo" 2>/dev/null || true
    fi
done

# Clean core dumps
log_message "Cleaning core dumps"
find /var/crash -type f -name "*.crash" -mtime +1 -delete 2>/dev/null || true

# Force log rotation
log_message "Forcing log rotation"
/usr/sbin/logrotate -f /etc/logrotate.conf 2>/dev/null || true

log_message "Privacy cleanup completed successfully"
{% else %}
log_message "Privacy cleanup is disabled"
{% endif %}

# Clean up old privacy cleanup logs
find /var/log -name "privacy-cleanup.log.*" -type f -mtime +7 -delete 2>/dev/null || true
