#!/bin/sh
set -eu

if [ "$#" -ne 2 ]; then
    echo "usage: $0 BASE_URL API_KEY" >&2
    exit 2
fi

base=${1%/}
api_key=$2
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT HUP INT TERM

request() {
    expected=$1
    method=$2
    url=$3
    output=$4
    shift 4
    actual=$(curl --path-as-is -sS -o "$output" -w '%{http_code}' -X "$method" "$url" "$@")
    if [ "$actual" != "$expected" ]; then
        echo "$method $url: expected HTTP $expected, got $actual" >&2
        sed -n '1,20p' "$output" >&2
        exit 1
    fi
}

request 200 GET "$base/" "$work/root"
request 200 GET "$base///" "$work/root-slashes"
request 200 GET "$base/static/" "$work/static-index"
request 200 GET "$base/static/app.js/" "$work/app"
request 200 GET "$base/api/health/" "$work/health"
grep -q '"service": "url-shortener"' "$work/health"
request 200 OPTIONS "$base/api/health/" "$work/options"

destination="https://destination.example/trailing-slash-smoke"
encoded_destination="https%3A%2F%2Fdestination.example%2Ftrailing-slash-smoke"
request 201 POST "$base/api/shorten/" "$work/created" \
    -H 'Content-Type: application/json' \
    --data "{\"url\":\"$destination\"}"
short_url=$(sed -n '1p' "$work/created")
code=${short_url##*/}
case "$short_url" in
    "$base"/*) ;;
    *) echo "unexpected generated short URL: $short_url" >&2; exit 1 ;;
esac

request 200 GET "$base/api/lookup/?url=$encoded_destination" "$work/lookup"
grep -q "\"short_code\": \"$code\"" "$work/lookup"
request 200 GET "$base/api/urls/$code/" "$work/metadata"
request 200 GET "$base/api/urls/?api_key=$api_key" "$work/list"
request 302 GET "$base/$code/" "$work/redirect"
request 204 DELETE "$base/api/urls/$code/?api_key=$api_key" "$work/delete"
request 404 GET "$base/api/urls/$code/" "$work/missing"

echo "trailing-slash smoke test passed: $base"
