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

# Vorabkopie der persistenten Daten von Quelle -> Ziel (App bleibt online).
# Auf dem Quellsystem ausfuehren.

TARGET_HOST="${TARGET_HOST:-root@10.0.0.19}"
TARGET_APP_DIR="${TARGET_APP_DIR:-/opt/hoerdle}"
SOURCE_APP_DIR="${SOURCE_APP_DIR:-$(pwd)}"
SSH_OPTS="${SSH_OPTS:-}"

cd "$SOURCE_APP_DIR"

require_cmd() {
  if ! command -v "$1" >/dev/null 2>&1; then
    echo "Fehlend: $1"
    exit 1
  fi
}

require_cmd rsync
require_cmd ssh
require_cmd sha256sum
require_cmd find

echo "== Hördle Precopy =="
echo "Quelle: $(pwd)"
echo "Ziel: $TARGET_HOST:$TARGET_APP_DIR"
echo

for d in data public/uploads; do
  if [ ! -d "$d" ]; then
    echo "Pfad fehlt: $d"
    exit 1
  fi
done

echo "-- Zielordner sicherstellen --"
ssh $SSH_OPTS "$TARGET_HOST" "mkdir -p '$TARGET_APP_DIR/data' '$TARGET_APP_DIR/public/uploads'"
echo

echo "-- Vorabkopie data/ --"
rsync -aHAX --numeric-ids --delete \
  -e "ssh $SSH_OPTS" \
  "./data/" "$TARGET_HOST:$TARGET_APP_DIR/data/"
echo

echo "-- Vorabkopie public/uploads/ --"
rsync -aHAX --numeric-ids --delete \
  -e "ssh $SSH_OPTS" \
  "./public/uploads/" "$TARGET_HOST:$TARGET_APP_DIR/public/uploads/"
echo

echo "-- Verifikation (Dateien/Groesse) --"
LOCAL_DATA_COUNT="$(find data -type f 2>/dev/null | wc -l)"
REMOTE_DATA_COUNT="$(ssh $SSH_OPTS "$TARGET_HOST" "cd '$TARGET_APP_DIR' && find data -type f 2>/dev/null | wc -l")"
echo "data files local=$LOCAL_DATA_COUNT remote=$REMOTE_DATA_COUNT"

LOCAL_UPLOAD_COUNT="$(find public/uploads -type f 2>/dev/null | wc -l)"
REMOTE_UPLOAD_COUNT="$(ssh $SSH_OPTS "$TARGET_HOST" "cd '$TARGET_APP_DIR' && find public/uploads -type f 2>/dev/null | wc -l")"
echo "uploads files local=$LOCAL_UPLOAD_COUNT remote=$REMOTE_UPLOAD_COUNT"

LOCAL_DATA_SIZE="$(du -sb data | awk '{print $1}')"
REMOTE_DATA_SIZE="$(ssh $SSH_OPTS "$TARGET_HOST" "du -sb '$TARGET_APP_DIR/data' | awk '{print \$1}'")"
echo "data bytes local=$LOCAL_DATA_SIZE remote=$REMOTE_DATA_SIZE"

LOCAL_UPLOAD_SIZE="$(du -sb public/uploads | awk '{print $1}')"
REMOTE_UPLOAD_SIZE="$(ssh $SSH_OPTS "$TARGET_HOST" "du -sb '$TARGET_APP_DIR/public/uploads' | awk '{print \$1}'")"
echo "uploads bytes local=$LOCAL_UPLOAD_SIZE remote=$REMOTE_UPLOAD_SIZE"
echo

if [ -f "data/prod.db" ]; then
  echo "-- DB Hash Vergleich (Precopy) --"
  LOCAL_HASH="$(sha256sum data/prod.db | awk '{print $1}')"
  REMOTE_HASH="$(ssh $SSH_OPTS "$TARGET_HOST" "sha256sum '$TARGET_APP_DIR/data/prod.db' | awk '{print \$1}'")"
  echo "prod.db sha256 local=$LOCAL_HASH"
  echo "prod.db sha256 remote=$REMOTE_HASH"
fi

echo
echo "Precopy abgeschlossen. Fuer konsistente Enddaten jetzt Cutover ausfuehren."
