#!/usr/bin/env python3

import os
import time
import sys
import pexpect
import os.path
import base64

# This script can probably use some improvement

process = "/root/openvpn-install.sh"

operatingDir = "/root"


fScript = pexpect.spawn(process)


if len(sys.argv) > 2:

    if sys.argv[1] == "--create-client":

        clientName = sys.argv[2]

        configFilePath = operatingDir + "/" + clientName + ".ovpn"

        fScript.expect("Looks")
        fScript.sendline("1")
        fScript.expect("Tell")
        fScript.sendline(clientName)
        fScript.expect(pexpect.EOF)        

        if os.path.exists(configFilePath):

            file = open(configFilePath, 'r')

            finalResult = base64.b64encode(file.read().encode("utf-8"))

            print(finalResult)
            quit()

        else:
            sys.stdout.write("Error! OpenVPN did not create the Configuration file.")
            sys.stdout.flush()
            quit()


    elif sys.argv[1] == "--revoke-client":

        prog = os.popen('which revoke-vpn-user').read() 
        
        if prog == "/usr/bin/revoke-vpn-user\n":

            os.system(prog + " " + sys.argv[2])
        else:
            sys.stdout.write("Error! This system is not ready for client revocation yet. Please try again later.")
            sys.stdout.flush()
            quit()

    else:
        sys.stdout.write("Error! Missing options!")
        sys.stdout.flush()
        quit()

else:
    sys.stdout.write("Error! Missing client name!")
    sys.stdout.flush()
    quit()
