65 lines
2.4 KiB
Bash
65 lines
2.4 KiB
Bash
#!/bin/bash
|
|
|
|
# Function to output text in color
|
|
color_echo() {
|
|
local color_code=$1
|
|
local text=$2
|
|
echo -e "\e[${color_code}m${text}\e[0m"
|
|
}
|
|
|
|
# Ask the user for the number of days to keep logs
|
|
color_echo "36" "How many days of logs would you like to keep?"
|
|
read -p "Enter the number of days (e.g., 10): " days_to_keep
|
|
|
|
# Validate input with default value and range check
|
|
if [[ -z "$days_to_keep" ]]; then
|
|
days_to_keep=10
|
|
color_echo "33" "No input provided. Defaulting to 10 days."
|
|
elif ! [[ "$days_to_keep" =~ ^[0-9]+$ ]]; then
|
|
color_echo "31" "Invalid input. Please enter a positive integer."
|
|
exit 1
|
|
elif [[ "$days_to_keep" -lt 1 || "$days_to_keep" -gt 365 ]]; then
|
|
color_echo "31" "Please enter a value between 1 and 365 days."
|
|
exit 1
|
|
fi
|
|
|
|
# Confirm the operation
|
|
color_echo "36" "You chose to keep logs for $days_to_keep days. A cron job will be created to clean logs older than this."
|
|
read -p "Are you sure you want to proceed? (y/n): " confirm
|
|
|
|
if [[ "$confirm" != "y" && "$confirm" != "Y" ]]; then
|
|
color_echo "33" "Operation canceled."
|
|
exit 0
|
|
fi
|
|
|
|
# Define the cron job with logging
|
|
log_directory="/var/log/proxmox-backup"
|
|
backup_directory="/var/log/proxmox-backup-backup"
|
|
mkdir -p "$backup_directory"
|
|
cron_command="/usr/bin/find $log_directory -mtime +$days_to_keep -type f -exec mv {} $backup_directory/ \; && /usr/bin/fin $backup_directory -mtime +30 -type f -exec rm {} +"
|
|
cron_job="0 3 * * * $cron_command"
|
|
|
|
# Check if the cron job already exists
|
|
existing_cron=$(crontab -l 2>/dev/null | grep -F "$cron_command")
|
|
if [[ -n "$existing_cron" ]]; then
|
|
color_echo "33" "A cron job for this command already exists. No new cron job will be added."
|
|
exit 0
|
|
fi
|
|
|
|
# Preserve existing crontab and add the new job
|
|
current_crontab=$(crontab -l 2>/dev/null)
|
|
echo -e "$current_crontab\n$cron_job" | awk 'NF' | sort -u | crontab -
|
|
|
|
# Check if the cron job was added successfully
|
|
if [[ $? -eq 0 ]]; then
|
|
color_echo "32" "Cron job created successfully to move logs older than $days_to_keep days to $backup_directory. Logs in the backup directory older than 30 days will be deleted."
|
|
else
|
|
color_echo "31" "Failed to create the cron job. Please check if crontab is installed and accessible, and verify the syntax of the command."
|
|
color_echo "33" "Debugging Information:"
|
|
color_echo "33" "Cron Command: $cron_command"
|
|
color_echo "33" "Backup Directory: $backup_directory"
|
|
exit 1
|
|
fi
|
|
|
|
exit 0
|