#!/bin/bash

# Taken from Flatpak

# Copyright 2017 Red Hat, Inc.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
#
# On Debian systems, the full text of the GNU Lesser General Public License
# version 2.1 can be found in the file '/usr/share/common-licenses/LGPL-2.1'.

set -euo pipefail

dir=$1
test_tmpdir=$(pwd)

cd ${dir}
env PYTHONUNBUFFERED=1 setsid python3 -m http.server 0 >${test_tmpdir}/httpd-output &
child_pid=$!

for x in $(seq 50); do
    # Snapshot the output
    cp ${test_tmpdir}/httpd-output{,.tmp}
    # If it's non-empty, see whether it matches our regexp
    if test -s ${test_tmpdir}/httpd-output.tmp; then
        sed -e 's,Serving HTTP on 0.0.0.0 port \([0-9]*\) .*,\1,' < ${test_tmpdir}/httpd-output.tmp > ${test_tmpdir}/httpd-port
        if ! cmp ${test_tmpdir}/httpd-output.tmp ${test_tmpdir}/httpd-port 1>/dev/null; then
            # If so, we've successfully extracted the port
            break
        fi
    fi
    sleep 0.1
done
port=$(cat ${test_tmpdir}/httpd-port)
echo "http://127.0.0.1:${port}" > ${test_tmpdir}/httpd-address
echo "$child_pid" > ${test_tmpdir}/httpd-pid
