#!/usr/bin/env python

USAGE = """
Open and wait for VPN connection, open given SSH connection
"""

import sys
import os
import time

from systematic.shell import Script
from darwinist.process import ProcessList
from darwinist.networkprofile import NetworkProfileList

CONFIG_PATH = os.path.join(os.getenv('HOME'), '.networks.conf')

script = Script()

def wait_connection(connection, process=None):
    """
    Function to wait startup of vpn connection, or VPN process quitting.
    Doesn't make sense for other connection types.
    """
    pl = ProcessList()
    time.sleep(1)
    while True:
        if process is not None:
            pl.update()
            if not pl.filter_command(process):
                script.exit(1, 'Process not found: {0}'.format(process))
        if n.connected:
            break
        time.sleep(1)

linktype = 'vpn'
process = 'racoon'

if len(sys.argv[1:]) == 0:
    script.exit(1, 'No ssh connection arguments provided')

npl = NetworkProfileList(config=CONFIG_PATH)
n = npl.filter(linktype)[0]
if not n.connected:
    n.connect()
    script.log.info('Waiting for {0} to connect...'.format(n.name))
    wait_connection(n, process)

script.execute(['ssh'] + sys.argv[1:])

