#!/usr/bin/env bash

# A `source` registry without RubyGems' JSON versions API, as GitHub Packages
# is, lists versions from its compact index (`info/<gem>`), the file Bundler
# installs from. Listing never shells out to `gem`, so this needs no Ruby.

TOKEN="ghp_e2eSECRET"

# A fake registry with only the compact index. It records each request's path
# and Authorization header.
cat >registry.py <<'PYTHON'
import os
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path

info = b"""---
1.0.0 |checksum:aa
2.2.0 thor:>= 1.2|checksum:bb
2.2.0-x86_64-linux thor:>= 1.2|checksum:cc
2.3.1 |checksum:dd
"""


class Handler(BaseHTTPRequestHandler):
    def log_message(self, *args):
        pass

    def do_GET(self):
        auth = self.headers.get("Authorization") or "none"
        with open("requests.log", "a") as log:
            log.write(f"{self.path} {auth}\n")
        if self.path != "/acme/info/internal-cli":
            self.send_error(404)
            return
        self.send_response(200)
        self.send_header("Content-Type", "text/plain")
        self.send_header("Content-Length", str(len(info)))
        self.end_headers()
        self.wfile.write(info)


def exit_with_test():
    parent = os.getppid()
    while os.getppid() == parent:
        time.sleep(0.5)
    os._exit(0)


threading.Thread(target=exit_with_test, daemon=True).start()
server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
Path("registry.port").write_text(str(server.server_port))
server.serve_forever()
PYTHON

python3 registry.py &
registry_pid=$!
wait_for_file registry.port "gem registry port" 30 "$registry_pid"
port="$(cat registry.port)"

cat >mise.toml <<EOF
[tools]
"gem:internal-cli" = { version = "latest", source = "http://${TOKEN}@127.0.0.1:${port}/acme" }
EOF

# Each version once, oldest first, and a prefix resolves against them.
assert "mise ls-remote gem:internal-cli" "1.0.0
2.2.0
2.3.1"
assert "mise latest gem:internal-cli@2.2" "2.2.0"

# The JSON API first, then the compact index, both with the credential
# (base64 of `ghp_e2eSECRET:`).
assert "cat requests.log" "/acme/api/v1/versions/internal-cli.json Basic Z2hwX2UyZVNFQ1JFVDo=
/acme/info/internal-cli Basic Z2hwX2UyZVNFQ1JFVDo="
