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

REMOTE_USER="${REMOTE_USER:-06215350443}"
REMOTE_HOST="${REMOTE_HOST:-150.161.0.230}"
SSH_KEY_PATH="${SSH_KEY_PATH:-$HOME/.ssh/gitlab-deploy}"
REMOTE_SUPPORT_DIR="${REMOTE_SUPPORT_DIR:-~/deploy/portal-ru3/support}"

if [[ "$SSH_KEY_PATH" == "~/"* ]]; then
  SSH_KEY_PATH="$HOME/${SSH_KEY_PATH#~/}"
elif [[ "$SSH_KEY_PATH" == '$HOME/'* ]]; then
  SSH_KEY_PATH="$HOME/${SSH_KEY_PATH#\$HOME/}"
fi

if [[ ! -f "$SSH_KEY_PATH" ]]; then
  echo "SSH deploy key not found: $SSH_KEY_PATH" >&2
  exit 1
fi

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REMOTE_TARGET="${REMOTE_USER}@${REMOTE_HOST}"
SSH_BASE=(
  ssh
  -i "$SSH_KEY_PATH"
  -o BatchMode=yes
  -o IdentitiesOnly=yes
)

printf -v RSYNC_SSH '%q ' "${SSH_BASE[@]}"

"${SSH_BASE[@]}" "$REMOTE_TARGET" "mkdir -p '$REMOTE_SUPPORT_DIR'"
rsync -avz -e "$RSYNC_SSH" \
  "$SCRIPT_DIR/ru-homolog-deploy-plugin" \
  "$SCRIPT_DIR/ru-homolog-deploy-plugin.sudoers" \
  "$REMOTE_TARGET:$REMOTE_SUPPORT_DIR/"

cat <<EOF
Wrapper staged on $REMOTE_TARGET:$REMOTE_SUPPORT_DIR

Install on the remote host as root:
  install -o root -g root -m 0755 '$REMOTE_SUPPORT_DIR/ru-homolog-deploy-plugin' /usr/local/sbin/ru-homolog-deploy-plugin
  install -o root -g root -m 0440 '$REMOTE_SUPPORT_DIR/ru-homolog-deploy-plugin.sudoers' /etc/sudoers.d/ru-homolog-deploy-plugin
  visudo -cf /etc/sudoers.d/ru-homolog-deploy-plugin
EOF
