#!/usr/bin/env bash

set -euo pipefail

dry_run=false

while [[ $# -gt 0 ]]; do
  case "$1" in
    --dry-run)
      dry_run=true
      ;;
    *)
      echo "Unbekanntes Argument: $1" >&2
      echo "Verwendung: $0 [--dry-run]" >&2
      exit 1
      ;;
  esac
  shift
done

repo_root="$(cd "$(dirname "$0")/.." && pwd)"
config_file="$repo_root/.deploy.env"
include_file="${DEPLOY_INCLUDE_FILE:-$repo_root/scripts/deploy-include.txt}"

if [[ ! -f "$config_file" ]]; then
  echo "Fehlende Konfiguration: $config_file" >&2
  echo "Lege die Datei auf Basis von .deploy.env.example an." >&2
  exit 1
fi

if ! command -v sftp >/dev/null 2>&1; then
  echo "Das Kommando 'sftp' ist nicht verfuegbar." >&2
  exit 1
fi

if [[ ! -f "$include_file" ]]; then
  echo "Fehlende Deploy-Liste: $include_file" >&2
  exit 1
fi

set -a
source "$config_file"
set +a

: "${DEPLOY_HOST:?DEPLOY_HOST fehlt in .deploy.env}"
: "${DEPLOY_USER:?DEPLOY_USER fehlt in .deploy.env}"
: "${DEPLOY_TARGET_DIR:?DEPLOY_TARGET_DIR fehlt in .deploy.env}"

deploy_port="${DEPLOY_PORT:-22}"
batch_file="$(mktemp)"
deploy_items=()
cleanup() {
  rm -f "$batch_file"
}
trap cleanup EXIT

while IFS= read -r raw_item || [[ -n "$raw_item" ]]; do
  item="${raw_item%%#*}"
  item="${item%${item##*[![:space:]]}}"
  item="${item#${item%%[![:space:]]*}}"

  if [[ -z "$item" ]]; then
    continue
  fi

  if [[ ! -e "$repo_root/$item" ]]; then
    echo "Fehlender Deploy-Eintrag: $item" >&2
    exit 1
  fi

  deploy_items+=("$item")
done < "$include_file"

if [[ ${#deploy_items[@]} -eq 0 ]]; then
  echo "Keine Deploy-Eintraege in $include_file gefunden." >&2
  exit 1
fi

cat > "$batch_file" <<EOF
-mkdir $DEPLOY_TARGET_DIR
cd $DEPLOY_TARGET_DIR
EOF

for item in "${deploy_items[@]}"; do
  if [[ -d "$repo_root/$item" ]]; then
    printf 'put -r %s\n' "$item" >> "$batch_file"
  else
    printf 'put %s\n' "$item" >> "$batch_file"
  fi
done

if [[ "$dry_run" == true ]]; then
  echo "Dry-Run: folgende SFTP-Befehle wuerden ausgefuehrt:"
  cat "$batch_file"
  exit 0
fi

cd "$repo_root"
sftp -P "$deploy_port" "$DEPLOY_USER@$DEPLOY_HOST" < "$batch_file"

echo "Deployment abgeschlossen: $DEPLOY_USER@$DEPLOY_HOST:$DEPLOY_TARGET_DIR"