#!/usr/bin/env python3
"""
LAN-local HTTPS file server for Adhan audio files.

Serves /home/user/adhan/ over HTTPS on port 9443 using a Let's Encrypt
certificate obtained via DuckDNS DNS-01 challenge. Because the cert is
signed by a public CA, the Google Nest Mini accepts the audio streams.

This is the internet-independent audio source: once the cert exists on
disk, the server works on the LAN even with the internet completely down
(until cert expiry ~90 days; certbot renews it when internet returns).

Usage:
  sudo python3 local_https_server.py            # foreground
  sudo nohup python3 local_https_server.py &    # background
"""
import ssl
import os
import sys
import http.server

SERVE_DIR = "/home/user/adhan"
PORT = 9443

# Let's Encrypt cert locations (DuckDNS DNS-01)
CERT_DIR = "/etc/letsencrypt/live/hpt520.duckdns.org"
CERT_FILE = os.path.join(CERT_DIR, "fullchain.pem")
KEY_FILE = os.path.join(CERT_DIR, "privkey.pem")


def main():
    if not os.path.isfile(CERT_FILE) or not os.path.isfile(KEY_FILE):
        print("ERROR: cert not found at {}".format(CERT_DIR), file=sys.stderr)
        print("Run certbot first (see plan: DuckDNS DNS-01 challenge)", file=sys.stderr)
        sys.exit(1)

    os.chdir(SERVE_DIR)
    server_address = ("0.0.0.0", PORT)
    httpd = http.server.HTTPServer(server_address, http.server.SimpleHTTPRequestHandler)

    ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
    ctx.load_cert_chain(CERT_FILE, KEY_FILE)
    httpd.socket = ctx.wrap_socket(httpd.socket, server_side=True)

    print("HTTPS server running on https://0.0.0.0:{} serving {}".format(PORT, SERVE_DIR))
    print("Certs: {} / {}".format(CERT_FILE, KEY_FILE))
    httpd.serve_forever()


if __name__ == "__main__":
    main()
