#!/usr/bin/env python
import re
import signal
import subprocess
import sys
import threading

port = int(sys.argv[1])
p = subprocess.Popen(['lt', '-p', str(port)], stdout=subprocess.PIPE, encoding="utf-8")
r = p.stdout.readline()
m = re.match(r'your url is: (https://.*\.localtunnel\.me)', r)
assert m, "could not get the localtunnel URL"
print(m[1], flush=True)
sys.stdout.close()

shutdown = threading.Event()
def cleanup(_sig, _frame):
    p.terminate()
    p.wait(30)
    shutdown.set()

signal.signal(signal.SIGTERM, cleanup)
signal.signal(signal.SIGINT, cleanup)

shutdown.wait()
