#!/usr/bin/env sh
set -eu

ROOT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
TMP_DIR=$(mktemp -d)
cleanup() { rm -rf "$TMP_DIR"; }
trap cleanup EXIT INT TERM

mkdir -p "$TMP_DIR/bin"
cat > "$TMP_DIR/bin/docker" <<'EOF'
#!/usr/bin/env sh
printf '%s\n' "docker $*" >> "${FAKE_DOCKER_LOG:?}"
exit 0
EOF
cat > "$TMP_DIR/bin/curl" <<'EOF'
#!/usr/bin/env sh
exit 0
EOF
chmod +x "$TMP_DIR/bin/docker" "$TMP_DIR/bin/curl"

run_mode() {
  name=$1
  input=$2
  dir="$TMP_DIR/$name"
  mkdir -p "$dir"
  tar -C "$ROOT_DIR" --exclude=node_modules --exclude=release-output -cf - . | tar -C "$dir" -xf -
  FAKE_DOCKER_LOG="$dir/docker.log"
  export FAKE_DOCKER_LOG
  printf '%b' "$input" | PATH="$TMP_DIR/bin:$PATH" sh "$dir/setup.sh" install > "$dir/out.log" 2>&1

  grep -q 'keine Datei musste manuell bearbeitet werden' "$dir/out.log"
  grep -q '^VENDOO_SETUP_TOKEN=[0-9a-f]\{64\}$' "$dir/.env"
  grep -q 'docker compose build --pull' "$dir/docker.log"
  grep -q 'docker compose up -d --remove-orphans' "$dir/docker.log"
  test "$(stat -c '%a' "$dir/.env")" = 600
}

run_mode docker '1\n8124\nnein\n'
grep -q '^VENDOO_PUBLISH_ADDRESS=127.0.0.1$' "$TMP_DIR/docker/.env"
grep -q '^VENDOO_BIND_HOST=0.0.0.0$' "$TMP_DIR/docker/.env"

run_mode nas '2\n9124\nhttp://192.168.1.50:9124\nnein\n'
test -d "$TMP_DIR/nas/runtime/config"
test -d "$TMP_DIR/nas/runtime/db"
grep -q '^VENDOO_PUBLISH_ADDRESS=0.0.0.0$' "$TMP_DIR/nas/.env"
grep -q '^PUBLIC_BASE_URL=http://192.168.1.50:9124$' "$TMP_DIR/nas/.env"

run_mode vps '3\n8124\nvendoo.example.invalid\nnein\n'
grep -q '^VENDOO_DOMAIN=vendoo.example.invalid$' "$TMP_DIR/vps/.env"
grep -q '^PUBLIC_BASE_URL=https://vendoo.example.invalid$' "$TMP_DIR/vps/.env"
grep -q '^VENDOO_COOKIE_SECURE=true$' "$TMP_DIR/vps/.env"
grep -q '^VENDOO_TRUST_PROXY=true$' "$TMP_DIR/vps/.env"

printf '%s\n' 'Shell-Installer-Gate erfolgreich: Docker-, NAS- und VPS-Dialog erzeugen valide, geschützte Konfiguration ohne manuelle Dateibearbeitung.'
