from flask import Flask, render_template
from datetime import datetime

STATUS_FILE = "/etc/openvpn/server/openvpn-status.log"

app = Flask(__name__)

# Establish VPN server coordinates
SERVER_LATITUDE = 40.4993
SERVER_LONGITUDE = -74.3990
SERVER_CITY = "Piscataway, New Jersey"

def get_clients():
    clients = []
    # Extract client information
    with open(STATUS_FILE) as f:
        for line in f:
            parts = line.strip().split('\t')

            if parts and parts[0] == "CLIENT_LIST":
                clients.append({
                    "NAME": parts[1],
                    "CLIENT_REAL_ADDRESS": parts[2],
                    "VPN_IP_ADDRESS": parts[3],
                    "BYTES_IN": parts[5],
                    "BYTES_OUT": parts[6],
                    "CONNECTED_SINCE": parts[7],
		    "CONNECTED_SINCE_RAW": int(parts[8]),
                    "CIPHER": parts[12]
                })

    return clients

def get_uptime():
    # Display uptime based on earliest client
    clients = get_clients()

    if not clients:
        return "No active clients detected"

    earliest = min(c["CONNECTED_SINCE_RAW"] for c in clients)
    now = int(datetime.now().timestamp())

    seconds = now - earliest

    hours = seconds // 3600
    minutes = (seconds % 3600) // 60

    return f"{hours}h {minutes}m"


@app.route("/")
def index():
    clients = get_clients()

    return render_template(
        "index.html",
        clients=clients,
        uptime=get_uptime(),
        server_ip="64.237.55.206",
	server_latitude = SERVER_LATITUDE,
	server_longitude = SERVER_LONGITUDE,
	server_city = SERVER_CITY
    )


if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5000)
