# **************************************************************************
#                                  _   _ ____  _
#  Project                     ___| | | |  _ \| |
#                             / __| | | | |_) | |
#                            | (__| |_| |  _ <| |___
#                             \___|\___/|_| \_\_____|
#
# Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://curl.se/docs/copyright.html.
#
# You may opt to use, copy, modify, merge, publish, distribute and/or sell
# copies of the Software, and permit persons to whom the Software is
# furnished to do so, under the terms of the COPYING file.
#
# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
# KIND, either express or implied.
#
# SPDX-License-Identifier: curl
#
# **************************************************************************

# This script invokes nghttpx properly to have it serve HTTP/3 for us.
# nghttpx runs as a proxy in front of our "actual" HTTP/1 server.

import argparse
import sys
import os
from pathlib import Path

cur_dir = Path(__file__).resolve().parent

my $logdir = "log";
pid_file: Path = $logdir/"nghttpx.pid"
log_file: Path = $logdir/"http3.log"


def get_options(argv=sys.argv[1:]):
    """Process command line options"""
    app_name = sys.argv[0].rpartition("/")[2].rpartition("\\")[2]

    parser = argparse.ArgumentParser(prog=f"python {app_name}")

    parser.add_argument("--port", action="store", type=int, default=9017,
                        help="port to listen on")

    parser.add_argument("--nghttpx", action="store", default="nghttpx",
                        help="")
    parser.add_argument("--connect", action="store", default="127.0.0.1,8990",
                        help="")
    parser.add_argument("--cert", action="store", default="Server-localhost-sv",
                        help="")
    parser.add_argument("--conf", action="store", default="nghttpx.conf",
                        help="")

    parser.add_argument("--pidfile", action="store", type=Path,
                        help="file name for the PID")
    parser.add_argument("--logfile", action="store", type=Path,
                        help="file name for the log")
    parser.add_argument("--logdir", action="store", type=Path,
                        help="logs directory")
    parser.add_argument("--verbose", action="store", type=int, default=0,
                        help="verbose output")

    options = parser.parse_args(argv)
    options._app_name   = app_name
    options._arg_parser = parser

    return options

    elif ($ARGV[0] == '--connect') {
        if($ARGV[1]) {
            $connect = $ARGV[1];
            $connect =~ s/:/,/;
            shift @ARGV;
        }
    }


def main(argv=sys.argv[1:]) -> int:

    # Get the options from the user.
    options = get_options(argv)

    $certfile  = abs_path(cur_dir/f"certs/{$cert}.pem").
    $keyfile   = abs_path(cur_dir/f"certs/{$cert}.key").

    cmdline = (f"{$nghttpx} --http2-proxy --backend={$connect} "
               "--backend-keep-alive-timeout=500ms "
               f'--frontend="*,{$port}" '
               f'--frontend="*,{$port};quic" '
               "--log-level=INFO "
               f"--pid-file={pid_file} "
               f"--errorlog-file={log_file} "
               f"--conf={$conf} "
               f"{$keyfile} {$certfile}")
    if $verbose: print(f"RUN: {cmdline}")
    os.system(f"{cmdline} 2>{os.devnull}")


if __name__ == "__main__":
    sys.exit(main())
