#!/usr/bin/env bash
set -Eeuo pipefail

SOURCE="${BASH_SOURCE[0]}"
while [ -L "$SOURCE" ]; do
  SOURCE_DIR="$(cd -P "$(dirname "$SOURCE")" && pwd)"
  SOURCE_TARGET="$(readlink "$SOURCE")"
  case "$SOURCE_TARGET" in
    /*) SOURCE="$SOURCE_TARGET" ;;
    *) SOURCE="$SOURCE_DIR/$SOURCE_TARGET" ;;
  esac
done
HELPER_DIR="$(cd "$(dirname "$SOURCE")/.." && pwd)"

# shellcheck source=../lib/common.sh
. "$HELPER_DIR/lib/common.sh"
# shellcheck source=../lib/safety.sh
. "$HELPER_DIR/lib/safety.sh"
# shellcheck source=../lib/backup.sh
. "$HELPER_DIR/lib/backup.sh"
# shellcheck source=../lib/docker.sh
. "$HELPER_DIR/lib/docker.sh"
# shellcheck source=../lib/diagnostics.sh
. "$HELPER_DIR/lib/diagnostics.sh"
# shellcheck source=../lib/operations.sh
. "$HELPER_DIR/lib/operations.sh"

usage() {
  cat <<'EOF'
DeFCoN masternode/fullnode VPS helper

Usage:
  defcon-helper install-new [--dry-run] [--image IMAGE] [--external-ip IP] [--masternode --bls-key KEY]
  defcon-helper upgrade-existing --dry-run [--image IMAGE]
  defcon-helper upgrade-existing [--image IMAGE] [--yes]
  defcon-helper doctor
  defcon-helper backup [--include-chain] [--reason TEXT]
  defcon-helper rollback BACKUP_DIR [--yes]
  defcon-helper logs --errors [--tail N]
  defcon-helper peers
  defcon-helper pose
  defcon-helper report [--output FILE]

Environment:
  DEFCON_ROOT        Default: /opt/defcon
  DEFCON_IMAGE       Docker image used by compose.
  DEFCON_DATA_DIR    Default: /opt/defcon/data
  DEFCON_CONFIG_DIR  Default: /opt/defcon/config
EOF
}

main() {
  local cmd="${1:-help}"
  if [ "$#" -gt 0 ]; then
    shift
  fi

  case "$cmd" in
    install-new)
      install_new "$@"
      ;;
    upgrade-existing)
      upgrade_existing "$@"
      ;;
    doctor)
      doctor_command "$@"
      ;;
    backup)
      backup_command "$@"
      ;;
    rollback)
      rollback_command "$@"
      ;;
    logs)
      logs_command "$@"
      ;;
    peers)
      peers_command "$@"
      ;;
    pose)
      pose_command "$@"
      ;;
    report)
      report_command "$@"
      ;;
    help|-h|--help)
      usage
      ;;
    *)
      die "Unknown command: $cmd"
      ;;
  esac
}

main "$@"
