#!/bin/dash

set -e

set +a
PGPASSWORD="${PGPASSWORD:-''}"
set -a

HOST_FROM="${1:?}"
HOST_TO="${2:?}"

DBPORT="${3:?}"

BACKUP_DIR="/root/pgbackup"
PGDATA="/var/lib/postgresql/15"

# --- POSTGRESQL TRANSFER ---

# shellcheck disable=SC2087
ssh "${HOST_FROM:?}" <<EOF
rm -rf "${BACKUP_DIR:?}"

env PGPASSWORD="${PGPASSWORD}" pg_basebackup \
  -h localhost -p "${DBPORT:?}" -U postgres \
  -D "${BACKUP_DIR:?}" -Ft -X stream -z -P
EOF

ssh "${HOST_TO:?}" mkdir -p "${BACKUP_DIR:?}"

scp -r "${HOST_FROM:?}":"${BACKUP_DIR?}" "${HOST_TO:?}":"$(dirname "${BACKUP_DIR:?}")"

# shellcheck disable=SC2087
ssh "${HOST_TO:?}" <<EOF
  sudo systemctl stop postgresql
  sudo rm -rf "${PGDATA:?}"/*
  
  sudo tar -xzf "${BACKUP_DIR:?}/base.tar.gz" -C "${PGDATA:?}"
  [ -f "${BACKUP_DIR:?}/pg_wal.tar.gz" ] && sudo tar -xzf "${BACKUP_DIR:?}/pg_wal.tar.gz" -C "${PGDATA:?}/pg_wal"
  
  sudo chown -R postgres:postgres "${PGDATA:?}"
  sudo chmod 700 "${PGDATA:?}"
  
  sudo ls -l "${PGDATA:?}/pg_wal"
  
  sudo rm -f "${PGDATA:?}/standby.signal" "${PGDATA:?}/recovery.signal"
  
  sudo systemctl start postgresql
  journalctl -u postgresql -b --no-pager -n 100
EOF

# --- REDIS TRANSFER ---

ssh "${HOST_FROM:?}" <<'EOF'
  mkdir /root/redisdump/
  # vproxy support db
  redis-cli -p 6379 --rdb /root/redisdump/6379.rdb
  # vpn suppoort db
  redis-cli -p 6380 --rdb /root/redisdump/6380.rdb
  # domain support db
  redis-cli -p 6381 --rdb /root/redisdump/6381.rdb
EOF

scp -r "${HOST_FROM:?}":/root/redisdump "${HOST_TO:?}":/root

ssh -T "$HOST_TO" <<'EOF'
  set -euo pipefail

  port="6379"
  tgt="/var/lib/redis-support-bot-vproxy/dump.rdb"; src="/root/redisdump/6379.rdb"
  systemctl stop redis-support-bot-vproxy
  sleep 1
  echo move ${src:?} ${tgt:?}
  cp "${src:?}" "${tgt:?}"
  chown "redis-support-bot-vproxy" "${tgt:?}"
  chgrp "redis-support-bot-vproxy" "${tgt:?}"
  chmod 600 "${tgt:?}"
  systemctl start redis-support-bot-vproxy

  port="6380"
  tgt="/var/lib/redis-support-bot-vpn/dump.rdb"; src="/root/redisdump/6380.rdb"
  systemctl stop redis-support-bot-vpn
  sleep 1
  echo move ${src:?} ${tgt:?}
  cp "${src:?}" "${tgt:?}"
  chown "redis-support-bot-vpn" "${tgt:?}"
  chgrp "redis-support-bot-vpn" "${tgt:?}"
  chmod 600 "${tgt:?}"
  systemctl start redis-support-bot-vpn

  port="6381"
  tgt="/var/lib/redis-support-bot-domain/dump.rdb"; src="/root/redisdump/6381.rdb"
  systemctl stop redis-support-bot-domain
  sleep 1
  echo move ${src:?} ${tgt:?}
  cp "${src:?}" "${tgt:?}"
  chown "redis-support-bot-domain" "${tgt:?}"
  chgrp "redis-support-bot-domain" "${tgt:?}"
  chmod 600 "${tgt:?}"
  systemctl start redis-support-bot-domain
EOF

# --- DREAM PROXY ---

ssh "${HOST_TO:?}" mkdir dreamproxy

scp -r "${HOST_FROM:?}":'dreamproxy/*' "${HOST_TO:?}":dreamproxy

# --- RESTART SERVICES ---

systemct restart vproxy-bot dreamproxy-bot support-bot-domain support-bot-vpn support-bot-vproxy vproxy-web postgrest
