#!/usr/bin/env bash set -euo pipefail usage() { echo "Использование: $0 --dest <папка> [--system] [--dry-run]" } dest="" include_system=0 dry_run=0 while [[ $# -gt 0 ]]; do case "$1" in --dest) dest="${2:-}"; shift 2 ;; --system) include_system=1; shift ;; --dry-run) dry_run=1; shift ;; -h|--help) usage; exit 0 ;; *) echo "Неизвестный аргумент: $1" >&2; usage >&2; exit 2 ;; esac done if [[ -z "$dest" ]]; then usage >&2 exit 2 fi if ! command -v crontab >/dev/null 2>&1; then echo "crontab не найден. Установите cron." >&2 exit 3 fi if [[ "$dry_run" -eq 0 ]]; then mkdir -p -- "$dest" fi if [[ -d "$dest" ]]; then dest_abs="$(cd "$dest" && pwd -P)" else dest_abs="$dest" fi timestamp="$(date +%Y%m%d-%H%M%S)" target="$dest_abs/crontab-user-$timestamp.txt" if [[ -e "$target" ]]; then echo "Файл уже существует: $target" >&2 exit 2 fi if [[ "$dry_run" -eq 1 ]]; then echo "Будет сохранён: $target" lines="$(crontab -l 2>/dev/null | wc -l || true)" echo "Строк в crontab: ${lines:-0}" if [[ "$include_system" -eq 1 ]]; then echo "Будут проверены /etc/crontab и /etc/cron.d." fi exit 0 fi umask 077 { echo "# crontab for $(id -un), saved $(date -u +%Y-%m-%dT%H:%M:%SZ)" crontab -l 2>/dev/null || echo "# crontab is empty or unavailable" } > "$target" files=("$target") if [[ "$include_system" -eq 1 ]]; then for source_file in /etc/crontab /etc/anacrontab; do if [[ -r "$source_file" ]]; then copy_target="$dest_abs/$(basename "$source_file")-$timestamp.txt" cp "$source_file" "$copy_target" chmod 600 "$copy_target" files+=("$copy_target") fi done if [[ -d /etc/cron.d && -r /etc/cron.d ]]; then cron_archive="$dest_abs/cron-d-$timestamp.tar.gz" tar -czf "$cron_archive" -C /etc cron.d chmod 600 "$cron_archive" files+=("$cron_archive") fi fi checksum="$dest_abs/crontab-$timestamp.sha256" : > "$checksum" for file in "${files[@]}"; do if command -v sha256sum >/dev/null 2>&1; then sha256sum "$file" >> "$checksum" else shasum -a 256 "$file" >> "$checksum" fi done echo "Crontab сохранён: $target" echo "Контрольные суммы: $checksum"