#!/usr/bin/python
# -*- coding: utf-8 -*-
u""" CERTIFYSERVERS: On each server update sshd_config files for client
and host certification, generate host certificate and make sure
initial trusted_cas and revoked_users files are in place; you do this
to set up the servers initially.

RECERTIFYSERVERS: On each previously certified server, regenerate and
reinstall host certificate using the same principals and validity as
the initial one. You do this each time the server instance changes or
when old certificate validity expires. When you supply fqdns, you will
update the intersection of existing servers and the fqdns you
supplied, otherwise you will update all the servers signed by the
given authority.

REFRESHSERVERS: On each server update the trusted_cas and
revoked_users files; you do this every time a new client ca is added
or a certificate is revoked.  """
from __future__ import print_function
import sys
import os
import socket
import argparse
import subprocess
import json
import pwd
import grp
import StringIO
import tempfile
import readline
import getpass
import datetime
from geekparts.datetime_util import zinfo, serialize_datetime, awarenow, awaredatetime, deserialize_datetime
from geekparts.datetime_util import allzonenames, is_naive, DateTimeEncoder, datetime_hook, aware_startup_datetime
from ssh_certificate.certhelper import set_defaults, get_base_dir, dbase_file_name, load_dbase
from ssh_certificate.certhelper import trusted_certifiers, revoked_lines, fqdnsplit, get_hostkeyfilename
from ssh_certificate.certhelper import certifyhost, trusted_cas_filename, revoked_users_filename
from ssh_certificate.certhelper import sshd_host_snippet, sshd_host_snippet_pattern, clienthost_cas, hostca_fqdns_pairs, host_map
from ssh_certificate.certhelper import sshd_client_snippet, sshd_client_snippet_pattern, revoked_line_generator
MYBUNDLE='ssh_certificate'
MYPROGNAME=os.path.basename(__file__)
MYHOSTNAME=socket.gethostname()
DEBUGMESSAGES=False
def cmd_to_string(command):
    """convert command list to command string"""
    if len(command) > 0:
        cstring = command[0]
        for apart in command[1:]:
            cstring = cstring + ' ' + apart
        return cstring
    else:
        return ""

def refreshserver(dbase, fqdn, dryrun=False):
    """update trusted_cas and revoked_users on the server"""
    # get the trusted_cas file contents
    certs = trusted_certifiers([],dbase)
    cert_data = ""
    for acert in certs:
        cert_data = cert_data + acert
    overwrite_command=["/usr/bin/ssh", "ubuntu@{}".format(fqdn), "/usr/bin/sudo /usr/bin/tee {}".format(trusted_cas_filename())]
    print("/usr/local/bin/certlocal trustedcas | {}".format(cmd_to_string(overwrite_command)), file=sys.stderr)
    if not dryrun:
        aprocess = subprocess.Popen(overwrite_command, stdin=subprocess.PIPE)
        aprocess.communicate(input=cert_data)
    # get revoked_users content
    rev_data=""
    for aline in revoked_lines(dbase):
        rev_data = rev_data + aline + "\n"
    overwrite_command=["/usr/bin/ssh","ubuntu@{}".format(fqdn),"/usr/bin/sudo /usr/bin/tee {}".format(revoked_users_filename())]
    print("/usr/local/bin/certlocal revoked | {}".format(cmd_to_string(overwrite_command)), file=sys.stderr)
    if not dryrun:
        aprocess = subprocess.Popen(overwrite_command, stdin=subprocess.PIPE)
        aprocess.communicate(input=rev_data)


def certify_cerver(dbase, fqdn, key_filename, authority, tag, other_subdomains, validity_weeks, dryrun=True):
    """Generate and install host certificate"""
    if key_filename is None:
        mykeyfilename = get_hostkeyfilename(dbase, authority, tag)
    else:
        mykeyfilename = key_filename
    cwrkd=os.getcwd()
    # Fetch host pub key
    fetch_host_key_command=["/usr/bin/scp", "ubuntu@{}:/etc/ssh/{}.pub".format(fqdn,mykeyfilename), cwrkd]
    print(cmd_to_string(fetch_host_key_command), file=sys.stderr)
    if not dryrun:
        subprocess.check_call(fetch_host_key_command)
    # Generate the certificate for the fetched pub key using host certifyer
    was_modified = certifyhost(fqdn, dbase,
                               authority=authority,
                               group_tag=tag,
                               other_subdomains=other_subdomains,
                               valid_weeks=validity_weeks,
                               dryrun=dryrun,
                               verbose=False)
    cert_filename="{}-cert.pub".format(mykeyfilename)
    upload_cert_command=["/usr/bin/ssh", "ubuntu@{}".format(fqdn),
                         "/usr/bin/sudo /usr/bin/tee /etc/ssh/{}".format(cert_filename)]
    print("cat {} | {}".format(cert_filename, cmd_to_string(upload_cert_command)), file=sys.stderr)
    if not dryrun:
        with open(cert_filename, "r") as cert_in:
            acert = cert_in.read()
        upload_process = subprocess.Popen(upload_cert_command, stdin=subprocess.PIPE)
        upload_process.communicate(input=acert)
    return was_modified

def configure_server_for_hosts(fqdn, key_filename, certline, dryrun=True):
    """Remove, then append sshd_config host snippets."""
    full_key_filename = os.path.join("/etc/ssh", key_filename + "-cert.pub")
    host, domain = fqdnsplit(fqdn)
    print("{}: configure_server_for_hosts : host={} domain={}".format(MYPROGNAME,host,domain), file=sys.stderr)
    args1 = "/bin/grep -E -v "
    args2 = sshd_host_snippet_pattern()
    args3 = " /etc/ssh/sshd_config "
    args4 = "| /usr/bin/sudo /usr/bin/tee /etc/ssh/sshd_config"
    allargs = args1 + args2 + args3 + args4
    remove_snippets_command=["/usr/bin/ssh", "ubuntu@{}".format(fqdn), allargs]
    print(cmd_to_string(remove_snippets_command), file=sys.stderr)
    if not dryrun:
        subprocess.check_call(remove_snippets_command)
    # get the sshd_config snippets as a string with embedded newlines
    mysnip = sshd_host_snippet(full_key_filename, verbose=True)
    append_snippets_command=["/usr/bin/ssh", "ubuntu@{}".format(fqdn), "/usr/bin/sudo /usr/bin/tee -a /etc/ssh/sshd_config"]
    print("SNIPPET BEGIN", file=sys.stderr)
    sys.stderr.write(mysnip)
    print("SNIPPET END | {}".format(cmd_to_string(append_snippets_command)), file=sys.stderr)
    if not dryrun:
        append_process = subprocess.Popen(append_snippets_command, stdin=subprocess.PIPE)
        append_process.communicate(input=mysnip)

    # Emit the certificate line to the certificate file
    
    emit_command=["/usr/bin/ssh", "ubuntu@{}".format(fqdn), "/usr/bin/sudo /usr/bin/tee {}".format(full_key_filename)]
    print("SNIPPET BEGIN", file=sys.stderr)
    sys.stderr.write(certline)
    print("SNIPPET END | {}".format(cmd_to_string(emit_command)), file=sys.stderr)
    if not dryrun:
        emit_process = subprocess.Popen(emit_command, stdin=subprocess.PIPE)
        emit_process.communicate(input=certline)


def configure_server_for_clients(fqdn, calist, dryrun=True):
    """Remotely, remove, then append sshd_config client snippets. 
    Write trusted cas and revoked users configured files."""
    
    host, domain = fqdnsplit(fqdn)
    print("{}: configure_server_for_clients : host={} domain={}".format(MYPROGNAME,host,domain), file=sys.stderr)
    args1 = "/bin/grep -E -v "
    args2 = sshd_client_snippet_pattern()
    args3 = " /etc/ssh/sshd_config "
    args4 = "| /usr/bin/sudo /usr/bin/tee /etc/ssh/sshd_config"
    allargs = args1 + args2 + args3 + args4
    remove_snippets_command=["/usr/bin/ssh", "ubuntu@{}".format(fqdn), allargs]
    print(cmd_to_string(remove_snippets_command), file=sys.stderr)
    if not dryrun:
        subprocess.check_call(remove_snippets_command)

    # get the sshd_config snippets as a string with embedded newlines
    mysnip = sshd_client_snippet()
    append_snippets_command=["/usr/bin/ssh", "ubuntu@{}".format(fqdn), "/usr/bin/sudo /usr/bin/tee -a /etc/ssh/sshd_config"]
    print("SNIPPET BEGIN", file=sys.stderr)
    sys.stderr.write(mysnip)
    print("SNIPPET END | {}".format(cmd_to_string(append_snippets_command)), file=sys.stderr)
    if not dryrun:
        append_process = subprocess.Popen(append_snippets_command, stdin=subprocess.PIPE)
        append_process.communicate(input=mysnip)

    trustedlines = [acert['PUBLIC'] for acert in calist ]
    trusteddata = ""
    for aline in trustedlines:
        trusteddata = trusteddata + aline
    print("TRUSTED CAS BEGIN", file=sys.stderr)
    sys.stderr.write(trusteddata)
    overwrite_command=["/usr/bin/ssh", "ubuntu@{}".format(fqdn),
                       "/usr/bin/sudo /usr/bin/tee {}".format(trusted_cas_filename())]
    print("TRUSTED CAS END | {}".format(cmd_to_string(overwrite_command)), file=sys.stderr)
    if not dryrun:
        overwrite_process = subprocess.Popen(overwrite_command, stdin=subprocess.PIPE)
        overwrite_process.communicate(input=trusteddata)
                
    revokeddata = ""            
    for aline in revoked_line_generator(calist):
        revokeddata = revokeddata + aline + '\n'
        
    print("REVOKED CLIENTS BEGIN", file=sys.stderr)
    sys.stderr.write(revokeddata)
    overwrite_command=["/usr/bin/ssh", "ubuntu@{}".format(fqdn),
                       "/usr/bin/sudo /usr/bin/tee {}".format(revoked_users_filename())]
    print("REVOKED CLIENTS END | {}".format(cmd_to_string(overwrite_command)), file=sys.stderr)
    if not dryrun:
        overwrite_process = subprocess.Popen(overwrite_command, stdin=subprocess.PIPE)
        overwrite_process.communicate(input=revokeddata)


def configure_servers(dbase, fqdns, dryrun=True):
    """Configure servers for client and/or host cerification"""
    def maybe_configure_client(fqdn, calist):
        """Configures for client IFF any cas"""
        if len(calist) < 1:
            return
        configure_server_for_clients(fqdn, calist, dryrun=dryrun)
        return

    def maybe_configure_server(fqdn, hostca):
        """Configures for host IFF hostca is not None"""
        if hostca is None:
            return
        filename = hostca['KEYNAME']
        certformat = hostca['SIGNEDHOSTS'][fqdn]["CERTFORMAT"]
        certname = hostca['SIGNEDHOSTS'][fqdn]["CERTNAME"]
        certbin = hostca['SIGNEDHOSTS'][fqdn]["CERTBIN"]
        certline = "{} {} {}\n".format(certformat,certbin,certname)
        configure_server_for_hosts(fqdn, filename, certline, dryrun=dryrun)
        return

    clientmap = clienthost_cas(dbase) # fqdn to client ca list
    hostmap = host_map(dbase) # fqdn to host ca
    serverset = set(hostmap.keys() + clientmap.keys())
    if len(fqdns) > 0:
        serverlist = list(serverset.intersection(set(fqdns)))
    else:
        serverlist = list(serverset)
    if len(serverlist) < 1:
        print("{}: configure_servers: EMPTY set of servers".format(MYPROGNAME), file=sys.stderr)
        return
    for fqdn in serverlist:
        try:
            clientcas = clientmap[fqdn]
        except KeyError as e:
            clientcas = []
        try:
            hostca = hostmap[fqdn]
        except KeyError as e:
            hostca = None
        if len(clientcas) < 1 and hostca is None:
            # At least one of the two should happen or else we have SW rot
            print("{}: BUG: neither host ca nor client ca list for fqdn {}".format(MYPROGNAME, fqdn),
                  file=sys.stderr)
        maybe_configure_server(fqdn, hostca)
        maybe_configure_client(fqdn, clientcas)
    print("{}: Updated configurations of these hosts: {}".format(MYPROGNAME, serverlist), file=sys.stderr)
        
def fqdn_other_validity_triples(dbase,authority,tag):
    """foo"""
    def extract_other(alist,exclude):
        def subdomain_part(fqdn):
            ahost, adomain = fqdnsplit(fqdn)
            return ahost
        extracted=[subdomain_part(anitem) for anitem in alist if anitem not in exclude]
        return extracted
    certifyerkey = authority + '_hostca_' + tag
    signed_hosts = dbase['HOSTCERTIFYERS'][certifyerkey]['SIGNEDHOSTS']
        
    triples=[(ahost, extract_other(avalue["PRINCIPALS"],[ahost, "127.0.0.1"]),
              avalue["VALIDITY_WEEKS"])for ahost, avalue in signed_hosts.items()]
    if DEBUGMESSAGES :
        for ahost, alist, avlid  in triples:
            print("{}: debug: ({},{},{})".format(MYPROGNAME, ahost, alist, avlid), file=sys.stderr) 
    return triples
    
    

if __name__ == '__main__':
    files_dir = get_base_dir(debugflag=DEBUGMESSAGES)
    defaults = set_defaults(files_dir)
    dbase_file=dbase_file_name(files_dir)
    if os.path.exists(dbase_file):
        dbase = load_dbase(dbase_file)
    else:
        print("{}:{} does not exist".format(MYPROGNAME,dbase_file), file=sys.stderr)
        exit(1)

    PARSER = argparse.ArgumentParser(prog=MYPROGNAME, description=__doc__)
    PARSER.add_argument('-d', '--dryrun',  dest='dryrun', action='store_true', default=False,
                        help="Do not invoke the commands. Just print them.")
    
    subparsers=PARSER.add_subparsers(help='"{} <subcommand> -h" for subcommand help'.format(MYPROGNAME),
                                     dest='subparser_name')

    parser_names = ["certifyservers", "configservers", "refreshservers", "recertifyservers"]
    parsers = {}
    for aname in parser_names:
        parsers[aname] = subparsers.add_parser(aname)
    
    parsers["configservers"].add_argument('-f', '--fqdns',  nargs='*', dest='fqdns',
                                          action='store', default=[],
                                          help="Hosts we will configure. Empty list means all of them." +
                                        " (default {})".format([]))
    
    parsers["certifyservers"].add_argument('-f', '--fqdns',  nargs='+', dest='fqdns',
                                          action='store', default=defaults['CLIENTHOSTS'],
                                        help="Hosts we will configure" +
                                        " (default {})".format(defaults['CLIENTHOSTS']))

    parsers["certifyservers"].add_argument('-k', '--key-filename', dest='key_filename', action='store', default=defaults['HOSTKEYFILE'],
                                        help="Host key file name without the .pub (default '{}')".format(defaults['HOSTKEYFILE']))
    parsers["certifyservers"].add_argument('-a', '--authority',  dest='authority', 
                                          action='store', default=defaults['HOSTAUTHORITY'],
                                          help="Name of authority that signs client and host certificates" +
                                          " (default {})".format(defaults['HOSTAUTHORITY']))

    parsers["certifyservers"].add_argument('-t', '--tag',  dest='tag', 
                                          action='store', default=defaults['HOSTTAG'],
                                          help="Tag related to the usage of the resulting certificates" +
                                          " (default {})".format(defaults['HOSTTAG']))
    
    parsers["certifyservers"].add_argument('-o', '--other-subdomains',  nargs='*', dest='other_subdomains',
                                          action='store', default=[],
                                          help="Alternate subdomain names which resolve to the same host" +
                                          " (default [])")

    parsers["certifyservers"].add_argument('-v', '--validity-weeks',  type=int, dest='validity_weeks',
                                          action='store', default=52,
                                          help="Grant client access for this many weeks" +
                                          " (default {})".format(52))

    parsers["recertifyservers"].add_argument('-f', '--fqdns',  nargs='+', dest='fqdns',
                                             action='store', default=[],
                                             help="Servers we want to recertify (default [] (implies All))")

    parsers["recertifyservers"].add_argument('-a', '--authority',  dest='authority', 
                                             action='store', default=defaults['HOSTAUTHORITY'],
                                             help="Name of authority that signs client and host certificates" +
                                             " (default {})".format(defaults['HOSTAUTHORITY']))

    parsers["recertifyservers"].add_argument('-t', '--tag',  dest='tag', 
                                          action='store', default=defaults['HOSTTAG'],
                                          help="Tag related to the usage of the resulting certificates" +
                                          " (default {})".format(defaults['HOSTTAG']))
    

    parsers["refreshservers"].add_argument('-f', '--fqdns',  nargs='+', dest='fqdns',
                                           action='store', default=defaults['CLIENTHOSTS'],
                                           help="Server hosts we will refresh" +
                                           " (default {})".format(defaults['CLIENTHOSTS']))



    ARGS = PARSER.parse_args()
    subcommand=ARGS.subparser_name
    if subcommand == 'certifyservers':
        any_modified = False
        for anfqdn in ARGS.fqdns:
            was_modified = configure_server(dbase, anfqdn, ARGS.key_filename, ARGS.authority, ARGS.tag,
                                            ARGS.other_subdomains, ARGS.validity_weeks, dryrun=ARGS.dryrun)
            if was_modified:
                any_modified = was_modified
        if any_modified:
            print("{}: Updating database: {}.".format(MYPROGNAME, dbase_file),
                  file=sys.stderr)
            with open(dbase_file, "w") as dbout:
                json.dump(dbase, dbout, indent=4,cls=DateTimeEncoder)

    if subcommand == 'configservers':
        configure_servers(dbase, ARGS.fqdns, dryrun=ARGS.dryrun)
    elif subcommand == 'recertifyservers':
        # Recertify regenerates certificates to extend validity
        # Recertify any *existing* fqdn
        # if ARGS.fqdns present recertify only those ones and only if they exist
        triples = fqdn_other_validity_triples(dbase,ARGS.authority, ARGS.tag)
        if len(ARGS.fqdns) > 0:
            # reduce to those in argument list
            mytriples = [(h,o,v) for h,o,v in triples if h in ARGS.fqdns]
        else:
            mytriples = triples
        if len(mytriples) < 1:
            print("{}: no existing servers in {}".format(MYPROGNAME, ARGS.fqdns), file=sys.stderr)
        any_modified=False
        for anfqdn, otherlist, validity in mytriples:
            was_modified = certify_cerver(dbase, anfqdn, None, ARGS.authority, ARGS.tag,
                                          otherlist, validity, dryrun=ARGS.dryrun)
            if was_modified:
                any_modified = was_modified
        if any_modified:
            print("{}: Updating database: {}.".format(MYPROGNAME, dbase_file),
                  file=sys.stderr)
            with open(dbase_file, "w") as dbout:
                json.dump(dbase, dbout, indent=4,cls=DateTimeEncoder)
    elif subcommand == 'refreshservers':
        for anfqdn in ARGS.fqdns:
            refreshserver(dbase, anfqdn, dryrun=ARGS.dryrun)
    else:
        print("{}: {} not implemented.".format(MYPROGNAME, subcommand))
