#!/usr/bin/env bash
# Installs the supplied files, creates exact-content sentinels, verifies CIFS
# hard-link support, disables the old cron entries, and enables the timer.
# It deliberately does not create a first baseline: authority requires the
# separate, explicit promotion command after you inspect a completed snapshot.
set -Eeuo pipefail
[[ $EUID -eq 0 ]] || { echo "Run with sudo" >&2; exit 1; }
HERE=$(cd "$(dirname "$0")" && pwd)
apt-get update
apt-get install -y rsync cifs-utils util-linux uuid-runtime timeshift
install -d -m 700 /etc/brain-backup /var/lib/brain-backup /mnt/data/backup /mnt/data_NAS /mnt/bart_NAS
install -m 700 "$HERE/brain-backup" /usr/local/sbin/brain-backup
install -m 700 "$HERE/brain-backup-promote" /usr/local/sbin/brain-backup-promote
install -m 644 "$HERE/brain-backup.service" /etc/systemd/system/brain-backup.service
install -m 644 "$HERE/brain-backup.timer" /etc/systemd/system/brain-backup.timer
for job in data home; do
  token="brain-$job-$(uuidgen)"
  sed "s/REPLACED_BY_INSTALLER/$token/" "$HERE/$job.conf.example" > "/etc/brain-backup/$job.conf"
  chmod 600 "/etc/brain-backup/$job.conf"
  source "/etc/brain-backup/$job.conf"
  chmod 000 "$MOUNT" || true
  timeout 45 mount -t cifs "$REMOTE" "$MOUNT" -o "credentials=$CREDENTIALS,vers=3.0,uid=0,gid=0,file_mode=0600,dir_mode=0700,noserverino"
  [[ "$(findmnt -n -o SOURCE --target "$MOUNT")" == "$REMOTE" ]]
  printf '%s\n' "$SENTINEL_VALUE" > "$MOUNT/$SENTINEL_NAME"
  mkdir -p "$MOUNT/_brain_backup/probe"
  printf x > "$MOUNT/_brain_backup/probe/install-a"; ln "$MOUNT/_brain_backup/probe/install-a" "$MOUNT/_brain_backup/probe/install-b"
  rm -f "$MOUNT/_brain_backup/probe/install-a" "$MOUNT/_brain_backup/probe/install-b"
  sync; umount "$MOUNT"; chmod 000 "$MOUNT"
done
# Preserve old crontab before removing only the two obsolete backup lines.
crontab -l > /root/root-crontab.before-brain-backup 2>/dev/null || true
(crontab -l 2>/dev/null || true) | grep -vE 'backup_(data|bart)_nas\.sh' | crontab -
touch /mnt/data/backup/events.log /mnt/data/backup/promotions.log
# ext4 append-only flags reinforce the policy. Root can remove them deliberately,
# but neither supplied program truncates or rewrites these files.
chattr +a /mnt/data/backup/events.log /mnt/data/backup/promotions.log 2>/dev/null || true
systemctl daemon-reload
systemd-analyze verify /etc/systemd/system/brain-backup.service /etc/systemd/system/brain-backup.timer
systemctl enable --now brain-backup.timer
echo "INSTALL COMPLETE"
