#!/usr/bin/env bash

set -euo pipefail

# The release host chooses each asset's name, and mise names the download after
# it. A name that is not a plain file name (here an absolute path) must be
# refused before anything is written, instead of being joined onto the download
# directory and placing the file wherever it points.
#
# Served from a local stand-in for the GitHub API so the test needs no network.

escaped="$TMPDIR/outside/escaped-tool"

start_http_server --handler - "$escaped" <<'PY'
import http.server
import json
import sys

ESCAPED = sys.argv[1]


class Handler(http.server.BaseHTTPRequestHandler):
    def reply(self, status, content_type, body):
        self.send_response(status)
        self.send_header("Content-Type", content_type)
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def release(self):
        port = self.server.server_address[1]
        return {
            "tag_name": "v1.0.0",
            "draft": False,
            "prerelease": False,
            "created_at": "2026-01-01T00:00:00Z",
            "published_at": "2026-01-01T00:00:00Z",
            "assets": [
                {
                    "name": ESCAPED,
                    "browser_download_url": f"http://127.0.0.1:{port}/download/tool",
                    "url": f"http://127.0.0.1:{port}/api/assets/1",
                }
            ],
        }

    def do_GET(self):
        path = self.path.split("?")[0]
        if path.startswith("/api/assets/") or path.startswith("/download/"):
            self.reply(200, "application/octet-stream", b"#!/bin/sh\necho escaped\n")
        elif path.endswith("/releases"):
            self.reply(200, "application/json", json.dumps([self.release()]).encode())
        elif "/releases/" in path:
            self.reply(200, "application/json", json.dumps(self.release()).encode())
        else:
            self.reply(404, "text/plain", b"not found")
PY

export MISE_USE_VERSIONS_HOST=0

cat >mise.toml <<EOF
[tools]
"github:acme/tool" = { version = "1.0.0", api_url = "http://127.0.0.1:$HTTP_PORT", asset_pattern = "*escaped-tool" }
EOF

assert_fail "mise install" "must be a plain file name"
if [[ -e $escaped ]]; then
  fail "the download was written outside the download directory: $escaped"
fi
