#!/usr/bin/python

#
# Copyright (C) 2023 Nethesis S.r.l.
# SPDX-License-Identifier: GPL-2.0-only
#
# Push the reserved IP address to the client
# 
# Environment variables:
# - config
# - common_name

import os
import sys
from euci import EUci
from nethsec import users

# The certificate of a migrated user is not present inside the index.txt
def is_migrated(instance, user):
    try:
        with open(f"/etc/openvpn/{instance}/pki/index.txt", "r") as fp:
            lines = fp.readlines()
            for line in lines:
                (status, expiration, revocation, serial, filename, name) = line.split("\t")
                if name == user:
                    return False
    except:
        return True
    return True

if len(sys.argv) < 3:
    print("Not enough script parameters", file=sys.stderr)
    sys.exit(3)

instance = sys.argv[1]
user_file = sys.argv[2]

uci = EUci()
# assume all checks on the instance have been executed in the script before this one
config = uci.get_all("openvpn", instance)
db = config.get("ns_user_db", None)
if not db:
    # this is probably a tunnel, just ignore it
    sys.exit(0)
cn = os.environ.get("common_name")
if '@' in cn and is_migrated(instance, os.environ.get("common_name")):
    # remove domain suffix
    cn = cn.split('@')[0]
user = users.get_user_by_name(uci, cn, db)

if user:
    ipaddr = user.get('openvpn_ipaddr', '')
    if config.get('server'):
        # routed mode
        netmask = config.get('server').split(" ")[1]
    else:
        netmask = config.get('server_bridge').split(" ")[1]

    if ipaddr and netmask:
        with open(user_file, 'a') as fp:
            fp.write(f'ifconfig-push {ipaddr} {netmask}\n')
