#! /bin/bash

help() {
    echo "Usage: $(basename "$0") <restic_repository> <cmd>"
    echo ""
    echo "cmd can be:"
    echo "	backup-fast: backup with big chunk size"
    echo "	backup-slow: backup with small chunk size"
    echo "	backup-custom: backup with restic's default options"
    echo "	<restic_command>: any other restic command (except backup)"
    echo "	help: see restic's help menu"
    echo ""
    echo "To save your password, run:"
    echo "	security add-generic-password -T '$(realpath "$0")' -s Restic -a <RESTIC_REPOSITORY> -w"
}

get_pw() {
    security find-generic-password -w -s 'Restic' -a "$REPO"
}

copy_if_different() {
    if ! cmp -s "$1" "$2"; then
        cp -f "$1" "$2"
    fi
}

REPO="$1"
CMD="$2"
shift 2

# CMD cannot start with - or be "backup"
if [[ "$REPO" = "" || "$CMD" = "" || "$CMD" == -* || "$CMD" == "backup" ]]; then
    help
    exit 0
fi

copy_if_different ~/.nix-profile/manifest.json ~/Documents/nix-backup/manifest.json

if [[ "$CMD" = "backup-fast" ]]; then
    CHUNK_SIZE="8M"
    echo "Running in ${MODE} mode (chunk size: $CHUNK_SIZE)"
elif [[ "$CMD" = "backup-slow" ]]; then
    CHUNK_SIZE="256K"
    echo "Running in ${MODE} mode (chunk size: $CHUNK_SIZE)"
elif [[ "$CMD" = "backup-custom" ]]; then
    RESTIC_ARGS=("$@")
    RESTIC_REPOSITORY="$REPO" RESTIC_PASSWORD="$(get_pw)" restic backup "$@"
    exit 0
else
    RESTIC_REPOSITORY="$REPO" RESTIC_PASSWORD="$(get_pw)" restic "$CMD" "$@"
    exit 0
fi

echo "$@"

# RCLONE_BWLIMIT=100M \
(
  RESTIC_REPOSITORY="$REPO" \
  RESTIC_PASSWORD="$(get_pw)" \
	GOMAXPROCS=5 \
	RESTIC_PROGRESS_FPS=1 \
	RCLONE_VERBOSE=1 \
	RCLONE_DRIVE_CHUNK_SIZE=$CHUNK_SIZE \
	restic backup \
	-o rclone.connections=1 --stuck-request-timeout 5s \
	--files-from "$HOME/Documents/restic/include.txt" \
	--exclude-file "$HOME/Documents/restic/exclude.txt" \
	--exclude-caches \
	"$@"
)
