#! /bin/bash
printf "Content-type: text/html\n\n"

declare -A param   
while IFS='=' read -r -d '&' key value && [[ -n "$key" ]]; do
    param["$key"]=$value
done <<<"${QUERY_STRING}&"


container_id=$(
    docker run --rm -d \
        -p 8080 \
        --init true
        phillmac/media-srv \
        streamlink \
            --stream-segment-threads 3 \
            --ringbuffer-size 64M \
            --player-external-http \
            --player-external-http-port 8080 \
            "${param[url]}" "${param[quality]}"
)


listen_port=$(docker inspect "${container_id}" | jq '.[].NetworkSettings.Ports."8080/tcp"' | jq -r '.[].HostPort' | head -n 1)

printf "Listen port: ${listen_port}\n"