#!/usr/bin/env python3
# vim: ft=python :

import datetime
import re
import sys
import telnetlib
import time
import traceback

def retry_telnet_obj():
    try:
        return telnetlib.Telnet("localhost", 5194)
    except ConnectionRefusedError:
        time.sleep(5)
        return retry_telnet_obj()

tel = retry_telnet_obj()

def management_loop():
    should_die = False
    while not should_die:
        try:
            result = tel.expect([b">HOLD:Waiting"])
            if result[0] != -1:
                print(datetime.datetime.now().strftime("%H:%M"), "openvpn is waiting on a hold release")
                raise Exception("Replace this line with whatever you need to run as pre-connect code (use subprocess.call() to run external programs)")
                tel.write(b"hold release\n")
                print(datetime.datetime.now().strftime("%H:%M"), "right, off you go")
        except Exception as err:
            if not isinstance(err, EOFError):
                traceback.print_exception(err)
            should_die = True

try:
    while True:
        management_loop()
        tel.close()
        tel = retry_telnet_obj()
except KeyboardInterrupt:
    tel.close()
    sys.exit()
