# -*- coding: utf-8 -*-

import subprocess

_options = ['PasswordAuthentication=no', 'ConnectTimeout=1', 'VerifyHostKeyDNS=no',
        'BatchMode=yes', 'ServerAliveInterval=5', 'ServerAliveCountMax=1']
_args = ["ssh", "-4", "-i", "/etc/crans/secrets/trigger-generate" ]

def build_args(host):
    if not 'adm.crans.org' in host:
        host=host + '.adm.crans.org'
    args = list(_args)
    for opt in _options:
        args.append('-o')
        args.append(opt)
    args.extend(["rpcssh@%s" % host, "generate"])
    return args

def trigger_generate(host, background=False):
    args = build_args(host)
    if background:
        subprocess.Popen(args)
    else:
        p=subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        out, err = p.communicate()
        if err:
            raise Exception(err)
        return out

def trigger_generate_cochon(host):
    """Ceci est une fonction crade qui permet de se débarraser du process enfant
    que l'on aurait laissé en arrière plan"""
    args = build_args(host)
    p = subprocess.Popen(['/bin/bash'],
        stdin=subprocess.PIPE, )
    p.communicate(' '.join(args) + ' &> /dev/null &')
