#!/bin/sh
set -eu

is_btrfs() {
    [ "$(df --output=fstype "$1" | tail +2)" = 'btrfs' ]
}

is_subvolume() {
    btrfs subvolume show "$1" >/dev/null 2>&1
}

root_subvolume() {
    path="$1"
    until is_subvolume "$path" || [ "$path" = '/' ]
    do
        path="$(dirname "$path")"
    done
    echo "$path"
}

cleanup() {
    exit_code="$?"
    if [ -n "${snapshot:-}" ]
    then
        btrfs subvolume delete "$snapshot"
    fi
    sync --file-system "$destination"
    if [ "$exit_code" -eq 0 ]
    then
        curl -so /dev/null "https://notify.shore.co.il/send?message=Backup%20finished%20successfully%20on%20$(hostname -s)."
    else
        curl -so /dev/null  "https://notify.shore.co.il/send?message=Backup%20failed%20on%20$(hostname -s)."
    fi
}

if [ "$#" -ne 1 ]
then
    echo "Usage: $0 destination" >&2
    exit 1
fi

if ! is_btrfs /var/backups
then
    echo '/var/backups is not on btrfs filesystem. Exiting.' >&2
    exit 1
fi

trap 'cleanup' INT QUIT EXIT TERM

destination="$1"
volume="$(root_subvolume /var/backups)"
snapshot="$(mktemp --dry-run "--tmpdir=$volume")"
btrfs subvolume snapshot -r "$volume" "$snapshot"
source="/var/backups"
source="${snapshot}${source#"$volume"}/"

sync --file-system /var/backups
rsync --archive \
      --delete \
      --info=progress2 \
      "$source" \
      "$destination"
