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

SCRIPT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
TARGET=${DEPLOY_TARGET:-daniel@10.0.0.33}
SSH_KEY=${DEPLOY_SSH_KEY:-$HOME/.ssh/harbor_deploy}
ssh_opts=(-i "$SSH_KEY" -o IdentitiesOnly=yes -o StrictHostKeyChecking=yes)

skip_backup=0
yes_flag=0
for a in "$@"; do
  case "$a" in
    --yes) yes_flag=1 ;;
    --skip-backup) skip_backup=1 ;;
    *)
      printf '%s\n' "unknown argument: $a" >&2
      exit 1
      ;;
  esac
done

if [[ "$yes_flag" != 1 ]]; then
  printf '%s\n' "usage: reset-data.sh --yes [--skip-backup]" >&2
  printf '%s\n' "this permanently deletes all Mongo, Redis, and MinIO data on $TARGET" >&2
  printf '%s\n' "(a fresh backup is taken first unless --skip-backup is given)" >&2
  exit 1
fi

# Second confirmation: require the operator to type the exact target so a
# muscle-memory "--yes" (or a copy-pasted command) can't wipe the wrong host.
if [[ -t 0 ]]; then
  printf '%s\n' "About to permanently delete ALL Mongo, Redis, and MinIO data on: $TARGET"
  printf '%s' "Type the target above to confirm: "
  read -r confirm_target
  if [[ "$confirm_target" != "$TARGET" ]]; then
    printf '%s\n' "confirmation did not match \"$TARGET\" — aborted" >&2
    exit 1
  fi
else
  printf '%s\n' "refusing to run non-interactively: no TTY to type the confirmation" >&2
  exit 1
fi

printf '%s\n' "uploading reset-data.sh"
rsync -az -e "ssh -i $SSH_KEY -o IdentitiesOnly=yes -o StrictHostKeyChecking=yes" \
  "$SCRIPT_DIR/remote/reset-data.sh" "$TARGET:/tmp/harbor-reset-data.sh"

remote_args=(--yes)
if [[ "$skip_backup" == 1 ]]; then
  remote_args+=(--skip-backup)
fi

printf '%s\n' "The remote host may request the sudo password once."
ssh -t "${ssh_opts[@]}" "$TARGET" \
  "sudo install -o root -g root -m 0755 /tmp/harbor-reset-data.sh /opt/harbor/deploy/remote/reset-data.sh && rm -f /tmp/harbor-reset-data.sh && sudo /opt/harbor/deploy/remote/reset-data.sh ${remote_args[*]}"
