#!/usr/bin/env python
# -*- coding: utf-8 -*-
# +--------------------------------------------------------------------------+
# | OpenFW UTM Community                                                          |
# +--------------------------------------------------------------------------+

#
# Environ variables example:
#
# link_mtu=1576
# untrusted_port=60407
# daemon_log_redirect=0
# dev_type=tap
# ifconfig_local=192.168.151.1
# tun_mtu=1500
# remote_port_1=1194
# daemon_start_time=1426524468
# ifconfig_netmask=255.255.255.0
# script_context=init
# redirect_gateway=0
# verb=1
# local_port_1=1194
# ifconfig_broadcast=192.168.151.255
# daemon_pid=12489
# untrusted_ip=192.168.18.164
# daemon=1
# config=/etc/openvpn/openvpn.3.conf
# proto_1=tcp-server
# dev=tap2
# script_type=user-pass-verify

import os
import sys
import base64
from endian.job.engine_control import send_cmd_to_engine


password = base64.urlsafe_b64encode(os.environ.get('password'))
result = send_cmd_to_engine(
    cmd='call openvpnjob.authenticate',
    prefix='nolog',
    options={
        'common_name': "'{}'".format(os.environ.get('username')),
        'password_base64': password,
        'dev': os.environ.get('dev'),
        'remote': os.environ.get('untrusted_ip'),
        'remote_port': os.environ.get('untrusted_port')
    }
)

auth_ok = "280 OK" in result
auth_control_file = os.environ.get("auth_control_file")

if auth_control_file:
    out = "1" if auth_ok else "0"
    with open(auth_control_file, "w") as f:
        f.write(out)

# Retorna código 0 para sucesso ou código 1 para falha de autenticação
sys.exit(0 if auth_ok else 1)