#!/usr/bin/env bash

set -euo pipefail

REPO=
ACTION=

if [[ $# -lt 2 ]]; then
	echo "Command not specified"
	echo
	echo "clerie-backup REPO ACTION"
	echo
	echo "ACTION: restic,backup"
	echo
	echo "Available REPOs (/etc/clerie-backup/):"
	echo
	if [[ -d "/etc/clerie-backup" ]]; then
		find "/etc/clerie-backup/" -mindepth 1 -maxdepth 1 -type d -printf "%f\n" | sort -d
	fi
	exit 1
fi

REPO="$1"
shift

ACTION="$1"
shift

CONFIG_DIR="/etc/clerie-backup/${REPO}"
if [[ ! -d "${CONFIG_DIR}" ]]; then
	echo "Config dir ${CONFIG_DIR} for ${REPO} does not exist"
	exit 1
fi

ISSUE_EXIST=
if [[ ! -f "${CONFIG_DIR}/repo_password" ]]; then
	echo "File ${CONFIG_DIR}/repo_password not found"
	ISSUE_EXIST=1
fi
if [[ ! -f "${CONFIG_DIR}/repo_url" ]]; then
	echo "File ${CONFIG_DIR}/repo_url not found"
	ISSUE_EXIST=1
fi
if [[ ! -f "${CONFIG_DIR}/auth_username" ]]; then
	echo "File ${CONFIG_DIR}/auth_username not found"
	ISSUE_EXIST=1
fi
if [[ ! -f "${CONFIG_DIR}/auth_password" ]]; then
	echo "File ${CONFIG_DIR}/auth_password not found"
	ISSUE_EXIST=1
fi
if [[ -n "${ISSUE_EXIST}" ]]; then
	exit 1
fi

RESTIC_PASSWORD_FILE="${CONFIG_DIR}/repo_password"
export RESTIC_PASSWORD_FILE
RESTIC_REPOSITORY="rest:$(cat "${CONFIG_DIR}/repo_url")"
export RESTIC_REPOSITORY
RESTIC_REST_USERNAME="$(cat "${CONFIG_DIR}/auth_username")"
export RESTIC_REST_USERNAME
RESTIC_REST_PASSWORD="$(cat "${CONFIG_DIR}/auth_password")"
export RESTIC_REST_PASSWORD
RESTIC_PROGRESS_FPS="0.1"
export RESTIC_PROGRESS_FPS
RESTIC_CACHE_DIR="/var/cache/restic"
export RESTIC_CACHE_DIR

case "${ACTION}" in
restic)
	restic "$@"
	;;
backup)
	ISSUE_EXIST=
	if [[ ! -f "${CONFIG_DIR}/excludes" ]]; then
		echo "File ${CONFIG_DIR}/excludes not found"
		ISSUE_EXIST=1
	fi
	if [[ ! -f "${CONFIG_DIR}/files" ]]; then
		echo "File ${CONFIG_DIR}/files not found"
		ISSUE_EXIST=1
	fi
	if [[ -n "${ISSUE_EXIST}" ]]; then
		exit 1
	fi

        restic snapshots --latest 1 || restic init

        restic backup --exclude-file "${CONFIG_DIR}/excludes" --files-from "${CONFIG_DIR}/files"
	;;
*)
	echo "Unsupported ACTION: ${ACTION}"
	exit 1
	;;
esac