#!/usr/bin/env python3
"""Serves the offline copy of robertducky.fr at http://localhost:<port>.

Usage: python3 serve.py [port]   (default port: 8000)
"""
import http.server
import os
import sys
import webbrowser

PORT = int(sys.argv[1]) if len(sys.argv) > 1 else 8000
SITE_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "pocketpond")


def main():
    os.chdir(SITE_DIR)
    url = f"http://localhost:{PORT}"

    try:
        httpd = http.server.ThreadingHTTPServer(("127.0.0.1", PORT), http.server.SimpleHTTPRequestHandler)
    except OSError as exc:
        print(f"Could not start server on port {PORT}: {exc}", file=sys.stderr)
        print(f"Try a different port: python3 serve.py {PORT + 1}", file=sys.stderr)
        sys.exit(1)

    with httpd:
        print(f"Serving robertducky.fr offline at {url}")
        print("Press Ctrl+C to stop.")
        try:
            webbrowser.open(url)
        except Exception:
            pass
        try:
            httpd.serve_forever()
        except KeyboardInterrupt:
            print("\nStopped.")


if __name__ == "__main__":
    main()
