#!/bin/bash
rclocation="/etc/bash.bashrc"
if cat $rclocation |grep -Fq "crontab_protect"; then
    echo "cron保护已存在，跳过添加到$rclocation"
else
cat <<'EOF' >> $rclocation
alias crontab='crontab_protect'

crontab_protect() {
  if [[ "$1" == "-r" ]]; then
    echo "禁止使用 crontab -r！"
    return 1
  fi
  command crontab "$@"
}
EOF
echo "cron保护已添加到$rclocation"
fi

backup_cron='0 3 * * 1 crontab -l > /var/backups/crontab-$(date +\%F).bak'
existing_cron=$(crontab -l 2>/dev/null || true)
if echo "$existing_cron" | grep -Fxq "$backup_cron"; then
  echo "备份任务已存在，跳过添加"
else
  {
    echo "$existing_cron"
    echo "$backup_cron"
  } | crontab -
  echo "备份任务已添加到crontab"
fi


crontab -l > /var/backups/crontab-$(date +\%F).bak
echo "备份存储到了/var/backups/crontab-date.bak"