#!/usr/bin/env bash
set -euo pipefail

SERENITY_NFS_EXPORT="${SERENITY_NFS_EXPORT:-10.5.30.5:/mnt/user/data}"
SERENITY_MOUNT_POINT="${SERENITY_MOUNT_POINT:-/mnt/serenity-data}"
SCHOOLHOUSE_DATA_ROOT="${SCHOOLHOUSE_DATA_ROOT:-/opt/doris-schoolhouse/data}"
SERENITY_BACKUP_SUBDIR="${SERENITY_BACKUP_SUBDIR:-backups/nomad/doris-schoolhouse}"
RSYNC_BIN="${RSYNC_BIN:-/usr/bin/rsync}"
SUDO_BIN="${SUDO_BIN:-/usr/bin/sudo}"
MOUNT_BIN="${MOUNT_BIN:-/usr/bin/mount}"
DATE_BIN="${DATE_BIN:-/usr/bin/date}"
HOSTNAME_BIN="${HOSTNAME_BIN:-/usr/bin/hostname}"

if [[ ! -d "$SCHOOLHOUSE_DATA_ROOT" ]]; then
  echo "Schoolhouse data root missing: $SCHOOLHOUSE_DATA_ROOT" >&2
  exit 1
fi

"$SUDO_BIN" mkdir -p "$SERENITY_MOUNT_POINT"
if ! mountpoint -q "$SERENITY_MOUNT_POINT"; then
  "$SUDO_BIN" "$MOUNT_BIN" -t nfs -o rw,nfsvers=4 "$SERENITY_NFS_EXPORT" "$SERENITY_MOUNT_POINT"
fi

dest_root="$SERENITY_MOUNT_POINT/$SERENITY_BACKUP_SUBDIR"
mkdir -p "$dest_root/data"

"$RSYNC_BIN" -rlt --delete --omit-dir-times --no-perms --no-owner --no-group "$SCHOOLHOUSE_DATA_ROOT/" "$dest_root/data/"

stamp="$("$DATE_BIN" -u +%Y-%m-%dT%H:%M:%SZ)"
host_name="$("$HOSTNAME_BIN")"
printf '%s\n' "$stamp" > "$dest_root/last_success_utc.txt"
printf '%s\n' "$host_name" > "$dest_root/source_host.txt"

echo "Schoolhouse backup synced to $dest_root at $stamp"
