From 267ed0401cd1c7d4664431416ce439ecb49974b1 Mon Sep 17 00:00:00 2001 From: NiceDevil Date: Sun, 26 Jan 2025 08:41:38 +0000 Subject: [PATCH] Add Proxmox/pbs_logrotate.sh --- Proxmox/pbs_logrotate.sh | 63 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 Proxmox/pbs_logrotate.sh diff --git a/Proxmox/pbs_logrotate.sh b/Proxmox/pbs_logrotate.sh new file mode 100644 index 0000000..e01deb3 --- /dev/null +++ b/Proxmox/pbs_logrotate.sh @@ -0,0 +1,63 @@ +#!/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="find $log_directory -mtime +$days_to_keep -type f -exec mv {} $backup_directory/ \; && find $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 + +# Add the cron job to the user's crontab +(crontab -l 2>/dev/null; echo "$cron_job") | 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