#!/bin/sh
set -eu

script_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
root_dir=$(dirname -- "$script_dir")
timestamp=$(date -u +%Y%m%d-%H%M%S)
destination=${1:-"$root_dir/backups/headscale-$timestamp.tar.gz"}

mkdir -p "$root_dir/backups"

headscale_restart_required=false
headplane_restart_required=false
if docker stop headplane >/dev/null 2>&1; then
  headplane_restart_required=true
fi
if docker stop headscale >/dev/null 2>&1; then
  headscale_restart_required=true
fi

cleanup() {
  if [ "$headscale_restart_required" = true ]; then
    docker start headscale >/dev/null
  fi
  if [ "$headplane_restart_required" = true ]; then
    docker start headplane >/dev/null
  fi
}
trap cleanup EXIT INT TERM

if [ ! -f "$root_dir/data/db.sqlite" ]; then
  echo "No Headscale database found under $root_dir/data" >&2
  exit 1
fi

tar -C "$root_dir" -czf "$destination" data headplane/data
echo "Backup created: $destination"
