'''
A simple forwarding proxy that forwards all traffic from one local port to
another, while keeping track of the number of bytes transferred in each
direction.
'''
#  Licensed to the Apache Software Foundation (ASF) under one
#  or more contributor license agreements.  See the NOTICE file
#  distributed with this work for additional information
#  regarding copyright ownership.  The ASF licenses this file
#  to you under the Apache License, Version 2.0 (the
#  "License"); you may not use this file except in compliance
#  with the License.  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

import socket
import threading
import argparse

LOCAL_HOST = '127.0.0.1'


def parse_args() -> argparse.Namespace:
    """Parse command line arguments."""
    parser = argparse.ArgumentParser(description=__doc__)

    parser.add_argument('--listening_port', type=int, help='Port where the proxy listens.')

    parser.add_argument('--forwarding_port', type=int, help='Server port to forward to.')

    return parser.parse_args()


def forward(source, destination, is_client_to_server, byte_counts):
    """Forward traffic from source to destination.

    :param source: socket to read from.
    :param destination: socket to write to.
    :param is_client_to_server: True if forwarding from client to server.
    :param byte_counts: A dictionary to record bytes sent in each direction.
    """
    bytes_transferred = 0

    try:
        while True:
            data = source.recv(4096)
            if not data:
                break
            destination.sendall(data)
            bytes_transferred += len(data)
    except OSError:
        pass
    finally:
        try:
            destination.shutdown(socket.SHUT_WR)
        except OSError:
            pass
    # Forwarding done. Print the number of bytes transferred in the direction.
    if bytes_transferred > 0:
        if is_client_to_server:
            byte_counts["client-to-server"] = bytes_transferred
            print(f"client-to-server: {bytes_transferred}", flush=True)
        else:
            byte_counts["server-to-client"] = bytes_transferred
            print(f"server-to-client: {bytes_transferred}", flush=True)


def start_bidirectional_forwarding(client_socket, forwarding_port):
    """Start forwarding traffic between client and server.

    :param client_socket: socket connected to the client.
    :param forwarding_port: server port to forward to.
    :return: The number of bytes forwarded in both directions.
    """
    CLIENT_TO_SERVER = True
    SERVER_TO_CLIENT = False
    byte_counts = {}
    with client_socket, socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server_socket:
        try:
            server_socket.connect((LOCAL_HOST, forwarding_port))
        except OSError:
            return 0

        # Spawn a thread to forward traffic from client to server.
        client_to_server = threading.Thread(target=forward, args=(client_socket, server_socket, CLIENT_TO_SERVER, byte_counts))
        client_to_server.start()

        server_to_client = threading.Thread(target=forward, args=(server_socket, client_socket, SERVER_TO_CLIENT, byte_counts))
        server_to_client.start()
        client_to_server.join()
        server_to_client.join()
    return sum(byte_counts.values())


def main() -> int:
    """Run the proxy."""
    print("Starting proxy...", flush=True)
    args = parse_args()
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as listen_socket:
        listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        listen_socket.bind((LOCAL_HOST, args.listening_port))
        listen_socket.listen()
        print(f"Proxy listening on {LOCAL_HOST}:{args.listening_port}", flush=True)
        try:
            while True:
                client_sock, client_addr = listen_socket.accept()
                print(f"Accepted connection from {client_addr}", flush=True)
                if start_bidirectional_forwarding(client_sock, args.forwarding_port) > 0:
                    break
        except KeyboardInterrupt:
            print("Caught KeyboardInterrupt, terminating the program", flush=True)
            return 0
    return 0


if __name__ == "__main__":
    main()
