#!/bin/bash
set -euo pipefail

ROOT="$(cd "$(dirname "$0")" && pwd)"
CREDENTIALS_FILE="$ROOT/.ftp-credentials"
FTP_HOST="194.230.87.205"
FTP_PORT="21"
FTP_TARGET="httpdocs"

if [ ! -f "$CREDENTIALS_FILE" ]; then
  echo "Fehlt: $CREDENTIALS_FILE" >&2
  exit 1
fi

# shellcheck disable=SC1090
source "$CREDENTIALS_FILE"

if [ -z "${FTP_USER:-}" ] || [ -z "${FTP_PASS:-}" ]; then
  echo "FTP_USER oder FTP_PASS fehlt in $CREDENTIALS_FILE" >&2
  exit 1
fi

upload_file() {
  local file="$1"
  curl --disable-epsv --silent --show-error \
    --user "${FTP_USER}:${FTP_PASS}" \
    -T "$ROOT/$file" \
    "ftp://${FTP_HOST}:${FTP_PORT}/${FTP_TARGET}/${file}"
}

upload_file "index.html"
upload_file "styles.css"
upload_file "script.js"
upload_file "lupe.svg"

find "$ROOT/media" -type f ! -name '.DS_Store' -print0 | while IFS= read -r -d '' file; do
  relative_path="${file#$ROOT/}"
  curl --disable-epsv --silent --show-error \
    --user "${FTP_USER}:${FTP_PASS}" \
    --ftp-create-dirs \
    -T "$file" \
    "ftp://${FTP_HOST}:${FTP_PORT}/${FTP_TARGET}/${relative_path}"
done

echo "FTP deploy abgeschlossen."
