#!/bin/sh
set -eu

error() {
    echo "$@" >&2
    exit 1
}

usage() {
    error "Usage: $0 <start|status|cleanup> <source> <destination>"
}

start() {
    [ "$#" -eq 2 ] || usage
    source="$1"
    destination="$2"
    [ -d "$source" ] || error 'Source is not a btrfs volume.'
    [ "$(df --output=fstype "$source" | tail +1)" = 'btrfs' ] || \
        error 'Source is not a btrfs volume.'
    [ -b "$destination" ] || error 'Destination is not a block device.'
    echo "This will delete all data on $destination !" >&2
    echo 'You have 5 seconds to abort with ctrl+c.' >&2
    sleep 6
    btrfs device add -f "$destination" "$source"
    btrfs balance start -f --bg -dconvert=dup -mconvert=dup -sconvert=dup "$source"
    echo 'Backup has started.'
    echo 'You can check if it has finished by running:'
    echo "$0 status $source"
}

status() {
    # Ignore the destination, if passed.
    [ "$#" -eq 2 ] || [ "$#" -eq 1 ] || usage
    source="$1"
    [ -d "$source" ] || error 'Source is not a btrfs volume.'
    [ "$(df --output=fstype "$source" | tail +1)" = 'btrfs' ] || \
        error 'Source is not a btrfs volume.'
    if btrfs balance status "$source" | grep -q '^No balance found'
    then
        echo 'Backup has finished.'
    else
        echo 'Backup is still running.'
        exit 2
    fi
}

cleanup() {
    # Ignore the destination, if passed.
    [ "$#" -eq 2 ] || [ "$#" -eq 1 ] || usage
    source="$1"
    [ -d "$source" ] || error 'Source is not a btrfs volume.'
    [ "$(df --output=fstype "$source" | tail +1)" = 'btrfs' ] || \
        error 'Source is not a btrfs volume.'
    btrfs device remove "$destination" "$source"
    btrfs balance start --force -dconvert=single -mconvert=single -sconvert=single"$source"
}

[ "$#" -gt 1 ] || usage
case "$1" in
    start) shift; start "$@";;
    status) shift; status "$@";;
    cleanup) shift; cleanup "$@";;
    *) usage;;
esac
