#!/bin/bash
# Test-Ersatz fuer curl: Erreichbarkeitspruefungen und Debian-Abbild ohne
# Internet; alles andere (127.0.0.1, --resolve) geht an das echte curl.
. "$(dirname "$0")/../stublib"
url='' out='' head=0 prev='' w=0 host=''
for a in "$@"; do
	case "$a" in http*) url=$a ;; -I | -sSI | -sI) head=1 ;; esac
	[ "$prev" = -o ] && out=$a
	[ "$prev" = -w ] && w=1
	if [ "$prev" = -H ]; then case "$a" in 'Host: '*) host=${a#Host: } ;; esac; fi
	prev=$a
done
case "$url" in
*://203.0.113.*/.well-known/acme-challenge/*)
	# Reicht der andere Webserver Port 80 an psplay weiter? (STUB_WEB_FORWARD=ok|other)
	log "$url ($host)"
	case "${STUB_WEB_FORWARD:-}" in
	ok) printf 'HTTP/1.1 308 Permanent Redirect\r\nLocation: https://%s:%s%s\r\nServer: Caddy\r\n\r\n' "$host" "${STUB_WEB_HTTPS_PORT:-8443}" "/${url#*://*/}" ;;
	other) printf 'HTTP/1.1 301 Moved Permanently\r\nLocation: https://%s/\r\nServer: nginx\r\n\r\n' "$host" ;;
	*) exit 7 ;;
	esac
	exit 0 ;;
*://127.0.0.1/.well-known/acme-challenge/*)
	# Port 80 dieses Rechners: im Test kein anderer Webserver (STUB_WEB_FORWARD_LOCAL=ok fuer einen)
	log "$url ($host)"
	if [ "${STUB_WEB_FORWARD_LOCAL:-}" = ok ]; then
		printf 'HTTP/1.1 308 Permanent Redirect\r\nLocation: https://%s:%s%s\r\n\r\n' "$host" "${STUB_WEB_HTTPS_PORT:-8443}" "/${url#*://*/}"
		exit 0
	fi
	exit 7 ;;
*api.hetzner.cloud*)
	# Hetzner Console: STUB_HETZNER=ZONE (Token gilt, Zone im Projekt) | 401 | leer (nicht erreichbar)
	log "$url"
	case "${STUB_HETZNER:-}" in
	'') exit 7 ;;
	401) printf '{"error":{"code":"unauthorized","message":"unable to authenticate"}}\n401' ;;
	*)
		if [ "${url##*name=}" = "$STUB_HETZNER" ]; then
			printf '{"zones":[{"id":1,"name":"%s"}],"meta":{}}\n200' "$STUB_HETZNER"
		else
			printf '{"zones":[],"meta":{}}\n200'
		fi ;;
	esac
	exit 0 ;;
*github.com* | *registry-1.docker.io* | *auth.api.sonyentertainmentnetwork.com* | *deb.debian.org* | *pypi.org*)
	log "$url"
	if [ "$head" = 1 ]; then printf 'HTTP/2 200\r\ndate: %s\r\n\r\n' "$(LC_ALL=C date -u '+%a, %d %b %Y %H:%M:%S GMT')"; else [ "$w" = 1 ] && printf '200'; fi
	exit 0 ;;
*api.ipify.org* | *ifconfig.me* | *icanhazip.com* | *api64.ipify.org* | *api.cloudflare.com* | *duckdns.org*) exit 7 ;;
*://203.0.113.*)
	# Gibt es unter der oeffentlichen Adresse schon einen Webserver? (STUB_WEB_PROBE=Servername)
	log "$url"
	if [ -n "${STUB_WEB_PROBE:-}" ]; then printf 'HTTP/1.1 200 OK\r\nServer: %s\r\n\r\n' "$STUB_WEB_PROBE"; exit 0; fi
	exit 7 ;;
*cloud.debian.org*SHA512SUMS) log "$url"; printf '%s  debian-13-genericcloud-amd64.qcow2\n' "$(printf 'FAKE-QCOW2-IMAGE\n' | sha512sum | cut -d' ' -f1)"; exit 0 ;;
*cloud.debian.org*.qcow2) log "$url -> $out"; printf 'FAKE-QCOW2-IMAGE\n' >"$out"; exit 0 ;;
esac
real=$(PATH=$(printf '%s' "$PATH" | tr ':' '\n' | grep -v '/installer/tests/stubs/' | paste -sd: -) command -v curl)
exec "$real" "$@"
