#!/usr/bin/env bash

set -euo pipefail

repo_root="$(cd "$(dirname "$0")/.." && pwd)"
config_file="$repo_root/.deploy.env"

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

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)"
cleanup() {
  rm -f "$batch_file"
}
trap cleanup EXIT

cat > "$batch_file" <<EOF
-mkdir $DEPLOY_TARGET_DIR
cd $DEPLOY_TARGET_DIR
put index.html
put datenschutz.html
put impressum.html
put robots.txt
put sitemap.xml
put -r css
put -r img
put -r vendor
EOF

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

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