#!/usr/bin/env bash

check_root () {
  if [[ $UID != 0 ]]; then
    echo "Error: This script must be run as root."
    exit 1
  fi
}

check_if_not_already_running() {
  if ps ax | grep $0 | grep -v $$ | grep bash | grep -v grep
  then
    echo "backup monitor is already running"
    exit 1
  fi
}

check_dependencies () {
  for cmd in "$@"; do
    if ! command -v $cmd >/dev/null 2>&1; then
      echo "This script requires \"${cmd}\" to be installed"
      exit 1
    fi
  done
}

check_root

check_if_not_already_running

check_dependencies fswatch readlink dirname

UMBREL_ROOT="$(dirname $(readlink -f "${BASH_SOURCE[0]}"))/../.."

monitor_file () {
  local file_path="${1}"
  echo "Monitoring $file_path"
  echo

  if [[ ! -e "${file_path}" ]]; then
    echo "$file_path doesn't exist, waiting for it to be created..."
    echo
    until [[ -e "${file_path}" ]]; do
      echo "Nope, $file_path still doesn't exist..."
      sleep 1
    done
    touch "${UMBREL_ROOT}/events/signals/backup"
  fi

  fswatch -0 --event Updated $file_path | xargs -0 -n 1 -I {} touch "${UMBREL_ROOT}/events/signals/backup"
}

if [[ ! -d "${UMBREL_ROOT}" ]]; then
  echo "Root dir does not exist '$UMBREL_ROOT'"
  exit 1
fi

[[ -f "${UMBREL_ROOT}/.env" ]] && source "${UMBREL_ROOT}/.env"
BITCOIN_NETWORK=${BITCOIN_NETWORK:-mainnet}

# Monitor LND channel.backup
monitor_file "${UMBREL_ROOT}/lnd/data/chain/bitcoin/${BITCOIN_NETWORK}/channel.backup" &

# Monitor db/user.json
# We want to back up user settings too, however we currently store the encrypted
# mnemonic in this file which is not safe to backup remotely.
# Uncomment this in the future once we've ensured there's no critical data in
# this file.
# monitor_file "${UMBREL_ROOT}/db/user.json" &