#!/usr/bin/python
# -*- coding: utf-8 -*-
u""" Helper functions to manage CA certificates.
"""
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
import glob
import shutil

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

#### imports ####

from ssh_certificate.certhelper import targetconfigdir, get_base_dir, set_defaults, newclientca, remote_command_with_block
from ssh_certificate.certhelper import cas, clientinfo, known_hosts_authorities, interested_client_cas, sshd_host_script
from ssh_certificate.certhelper import servers_certifyers, interested_server_cas, read_certificate, pipe_block_into, remote_block_into
from ssh_certificate.certhelper import read_pubfile, read_key, print_certificate, newclientca, newhostca, new_dbase, normalizehost
from ssh_certificate.certhelper import save_dbase, generate_user_principals, fqdnsplit, prune_expired_keys
from ssh_certificate.certhelper import generate_certificate_filename_value_quints, generate_host_principals
from ssh_certificate.certhelper import setfrom_to_datetimes, certifyclient, recertify, hostca_fqdns_pairs
from ssh_certificate.certhelper import trusted_certifiers, known_hosts, certificate_status, md_block_into
from ssh_certificate.certhelper import cmd_to_string, certificate_sequence, export_client_pubs, export_revocations, export_routing, pubkey_line
from ssh_certificate.certhelper import revokeuser, revokehost, clientinfo, exportinfo, cas, get_hostkeyfilename
from ssh_certificate.certhelper import csv_string, principal_string, certifyhost, trusted_cas_filename
from ssh_certificate.certhelper import revoked_users_filename, known_hosts_filename, dbase_file_name, load_dbase, new_dbase
from ssh_certificate.certhelper import sshd_host_snippet, sshd_host_snippet_pattern, sshd_client_snippet
from ssh_certificate.certhelper import sshd_client_snippet_pattern, ssh_host_snippet, ssh_host_snippet_pattern
from ssh_certificate.certhelper import ssh_host_script, ssh_host_snippet_pattern, ssh_host_script, remote_block_execute
import tarfile

#### imports end ####


MYBUNDLE='ssh_certificate'
MYPROGNAME=os.path.basename(__file__)

REVOKED_USERS_FILE="revoked_users"
KNOWN_HOSTS_FILE="ssh_known_hosts"
FULL_KNOWN_HOSTS=os.path.join(targetconfigdir(), KNOWN_HOSTS_FILE)
DEFAULTS_FILE='{}_defaults.json'.format(MYBUNDLE)

## tarbal to extract from to initialize a new base directory
INITTARBALL="/etc/{}/certdbase.tar".format(MYBUNDLE)
CERTPAGELINK="`Certificates <{filename}/pages/certs.rst>`_"
EXAMPLEHOST="mangobiche"
EXAMPLE_KEY="{}_gituser".format(EXAMPLEHOST)
CONFIGDIR=targetconfigdir()
REMOTESCRIPTHEADER=["#!/bin/bash\n",
              "# ASSUMPTION on all hosts: remote use of sudo without password for /usr/bin/tee, and /bin/sed\n",
              "# This script was generated by the utility certssh of the package ssh_certificate\n",
              "# set -e\n",
              "MYPROGNAME=`basename $0`\n",
              'MYBUNDLE="ssh_certificate"\n',
              'if [ "$1" == "config" ]\n',
              "then\n"]
LOCALSCRIPTHEADER=["#!/bin/bash\n",
              "# This script was generated by the utility certssh of the package ssh_certificate\n",
              "set -e\n",
              "MYPROGNAME=`basename $0`\n",
              'MYBUNDLE="ssh_certificate"\n',
              'if [ "$1" == "config" ]\n',
              "then\n"]
SCRIPTTRAILEROPEN=["else\n",
                   "    cat <<EOF\n",
                   "${MYBUNDLE} remote configuration script.\n",
                   "Use: ${MYPROGNAME} config\n",
                   "        To make changes as follows:\n\n"]
SCRIPTTRAILERNODE="            update configuration of host {}\n"
REMOTETRAILERCLOSE=["\n",
                    "        MAKE SURE ssh keys are loaded and tunnels are up first\n",
                    "\n",
                    "     ${MYPROGNAME}\n",
                    "       To display this information\n",
                    "EOF\n",
                    "fi\n"]
LOCALTRAILERCLOSE=["\n",
                   "        MAKE SURE you do not run this on the wrong host\n",
                   "\n",
                   "     ${MYPROGNAME}\n",
                   "       To display this information\n",
                   "EOF\n",
                   "fi\n"]
MDADMINSOURCE="""
###Admin view

[Overview](#admin-overview)

Individual scripts are available for each host.

[Prepare](#admin-preparation) the host before using any script for the first time on that host.

There is one extra remote script consisting of the concatenation of
all the remote client and server scripts.  It is available in case a
single administrator is responsible for administering all nodes and
would find it convenient.

Update all nodes using a single script: [All nodes script]({allscript})

"""
MDUSERSOURCE="""
###User view

[Overview](#user-overview)

For a user certificate to gain access to an account on a host three
conditions must be met:  

* The account must be one of the principals within the certificate. 
* The signining authority that signed the certificate must be in /etc/ssh/truste_cas on the host.
* The account must exist on the host. 

<a name="signed-certificates"></a>**Signed Certificates**

"""
MDAUTHSOURCE="""
###Authority view

####Host Authorities

{hostinfo}

#### User Authorities

{userinfo}

"""

def comma_separated_list_string(alist):
    """convert a list into a string of elements separated by commas"""
    whatever_string="{}".format(alist[0])
    for awhatever in alist[1:]:
        whatever_string = whatever_string + ',' + "{}".format(awhatever)
    return whatever_string
    

def print_snippet():
    print(sshd_host_snippet(FULL_KNOWN_HOSTS, verbose=True))
    print(sshd_client_snippet(trusted_cas_filename(),
                              revoked_users_filename(),
                              verbose=True))
    
def curry_args_for_remote_block_into(remoteport=22,
                                     remoteuser="ubuntu",
                                     remotehost="guanabana.bernatchez.net"):
    """Return remote_block_into with args curried to match pipe_block_into"""
    
    def curried_remote_block_into(pipeline, datablock, targetfile):
        commands = remote_block_into(pipeline, datablock, targetfile,
                                     remoteport=remoteport,
                                     remoteuser=remoteuser,
                                     remotehost=remotehost)
        return commands
    return curried_remote_block_into

def curry_args_for_remote_block_execute(remoteport=22,
                                        remoteuser="ubuntu",
                                        remotehost="guanabana.bernatchez.net",
                                        dryrun=True):
    """Return remote_block_execute with args curried to match pipe_block_into"""
    def curried_remote_block_execute(pipeline, datablock, targetfile):
        commands = remote_block_execute(pipeline, datablock, targetfile,
                                        remoteport=remoteport,
                                        remoteuser=remoteuser,
                                        remotehost=remotehost,
                                        dryrun=dryrun)
        return commands
    return curried_remote_block_execute

def generate_remote_server(fqdn,
                           remoteport, remoteuser, remotehost,
                           server_certs, server_calist_map, scriptfilename,
                           open_file=None,
                           dbase=None):
    """generate a remote script for a given host"""
    def emit_lines(afile, remote_blk_into, rendered_commands):
        """emit remote script lines into open file"""
        afile.write("echo UPDATING server {}\n".format(fqdn))
        afile.write("echo ACCESSING {} as follows: ssh -p {} {}@{}\n".format(fqdn,
                                                                             remoteport,
                                                                             remoteuser,
                                                                             remotehost))
        if len(rendered_commands) == 0:
            afile.write("echo No configuration changes required for {} as a server host\n".format(fqdn))
        for acommand in rendered_commands:
            afile.write(acommand)
        
    remote_blk_into = curry_args_for_remote_block_into(remoteuser=remoteuser,
                                                       remotehost=remotehost,
                                                       remoteport=remoteport)
    rendered_commands = sshd_host_script(fqdn,
                                         server_certs, server_calist_map, 
                                         target_config=os.path.join(targetconfigdir(), "sshd_config"),
                                         render_command=remote_blk_into,
                                         dbase=dbase)
    
    if open_file is None:
        print("{}: Generating script: {}".format(MYPROGNAME, scriptfilename), file=sys.stderr)
        with open(scriptfilename, "w") as scriptfile:
            for aline in REMOTESCRIPTHEADER:
                scriptfile.write(aline)
            emit_lines(scriptfile, remote_blk_into, rendered_commands)
            for aline in SCRIPTTRAILEROPEN:
                scriptfile.write(aline)
            scriptfile.write(SCRIPTTRAILERNODE.format(fqdn))
            for aline in REMOTETRAILERCLOSE:
                scriptfile.write(aline)
    else:
        emit_lines(open_file, remote_blk_into, rendered_commands)

def execute_remote_server(fqdn,
                          remoteport, remoteuser, remotehost,
                          server_certs, server_calist_map,
                          dbase=None,
                          dryrun=True):
    """execute remote commands"""
    remote_blk_execute = curry_args_for_remote_block_execute(remoteuser=remoteuser,
                                                             remotehost=remotehost,
                                                             remoteport=remoteport,
                                                             dryrun=dryrun)
    executed_commands = sshd_host_script(fqdn,
                                         server_certs, server_calist_map, 
                                         target_config=os.path.join(targetconfigdir(), "sshd_config"),
                                         render_command=remote_blk_execute,
                                         dbase=dbase)
    # executed_commands is a list of empty strings, one per command
    # Feedback was emitted directly to stderr
    if len(executed_commands) == 1:
        myformat = "{}: Executed {} server host config command for {}"
    else:
        myformat = "{}: Executed {} server host config commands for {}"
    print(myformat.format(MYPROGNAME, len(executed_commands), fqdn), file=sys.stderr)

def generate_local_server(fqdn, server_certs, server_calist_map, scriptfilename, dbase=None):
    rendered_commands = sshd_host_script(fqdn,
                                         server_certs, server_calist_map, 
                                         target_config=os.path.join(targetconfigdir(), "sshd_config"),
                                         render_command=pipe_block_into,
                                         dbase=dbase)
    print("{}: Generating script: {}".format(MYPROGNAME, scriptfilename), file=sys.stderr)
    with open(scriptfilename, "w") as scriptfile:
        for aline in LOCALSCRIPTHEADER:
            scriptfile.write(aline)
        if len(rendered_commands) == 0:
            scriptfile.write("echo No configuration changes required for {} as a server host\n".format(fqdn))
        for acommand in rendered_commands:
            scriptfile.write(acommand)
        for aline in SCRIPTTRAILEROPEN:
            scriptfile.write(aline)
        scriptfile.write(SCRIPTTRAILERNODE.format(fqdn))
        for aline in LOCALTRAILERCLOSE:
            scriptfile.write(aline)

def admin_heading(fqdn):
    """Make a string to use as heading for a given host"""
    myhost, ignore = fqdnsplit(fqdn)
    alink = "{}_admin".format(myhost)
    return alink

            
def generate_admin_markdown(fqdn, server_certs, server_calist_map, client_calist_map, namemap, mdfile, dbase=None):
    rendered_sshd = sshd_host_script(fqdn,
                                     server_certs, server_calist_map, 
                                     target_config=os.path.join(targetconfigdir(), "sshd_config"),
                                     render_command=md_block_into,
                                     dbase=dbase)
    rendered_ssh = ssh_host_script(fqdn,
                                   client_calist_map, 
                                   target_ssh_config=os.path.join(targetconfigdir(), "ssh_config"),
                                   render_command=md_block_into,
                                   dbase=dbase)
    print("{}: Generating markdown for: {}".format(MYPROGNAME, fqdn), file=sys.stderr)
    dt = awarenow(zonename='UTC')
    nowstring = dt.strftime("%c")
    mdfile.write("___\n\n")
    mdfile.write("####" + admin_heading(fqdn) + '\n')
    mdfile.write("Actual Configuration parameters as at {} UTC\n\n".format(nowstring))
    if len(rendered_sshd) > 0:
        mdfile.write("**Server side configuration for {}**\n\n".format(fqdn))
        mdfile.write("[Prepare](#admin-preparation) the host first.\n[Remote Server Script]({}) | [Local Server Script]({})\n\n".format(namemap['rserver'],
                                                                                        namemap['lserver']))
        for asnippet in rendered_sshd:
            mdfile.write(asnippet)
    if len(rendered_ssh) > 0:
        mdfile.write("**Client side configuration for {}**\n\n".format(fqdn))
        mdfile.write("[Prepare](#admin-preparation) the host first.\n[Remote Client Script]({}) | [Local Client Script]({})\n\n".format(namemap['rclient'],
                                                                                        namemap['lclient']))
        for asnippet in rendered_ssh:
            mdfile.write(asnippet)

###
def generate_remote_client(fqdn,
                           remoteport, remoteuser, remotehost,
                           client_calist_map, scriptfilename, open_file=None,
                           dbase=None):
    """generate a remote script lines for a given client host"""
    def emit_lines(afile, remote_blk_into, rendered_commands):
        """emit remote script lines into open file"""
        afile.write("echo UPDATING client {}\n".format(fqdn))
        afile.write("echo ACCESSING {} as follows: ssh -p {} {}@{}\n".format(fqdn,
                                                                             remoteport,
                                                                             remoteuser,
                                                                             remotehost))
    
        if len(rendered_commands) == 0:
            afile.write("echo No configuration changes required for {} as a client host\n".format(fqdn))

        for acommand in rendered_commands:
            afile.write(acommand)
    
    remote_blk_into = curry_args_for_remote_block_into(remoteuser=remoteuser,
                                                       remotehost=remotehost,
                                                       remoteport=remoteport)
    rendered_commands = ssh_host_script(fqdn,
                                        client_calist_map, 
                                        target_ssh_config=os.path.join(targetconfigdir(), "ssh_config"),
                                        render_command=remote_blk_into,
                                        dbase=dbase)
    if open_file is None:
        print("{}: Generating script: {}".format(MYPROGNAME, scriptfilename), file=sys.stderr)
        with open(scriptfilename, "w") as scriptfile:
            for aline in REMOTESCRIPTHEADER:
                scriptfile.write(aline)
            emit_lines(scriptfile, remote_blk_into, rendered_commands)
            for aline in SCRIPTTRAILEROPEN:
                scriptfile.write(aline)
            scriptfile.write(SCRIPTTRAILERNODE.format(fqdn))
            for aline in REMOTETRAILERCLOSE:
                scriptfile.write(aline)
    else:
        emit_lines(open_file, remote_blk_into, rendered_commands)

def execute_remote_client(fqdn,
                          remoteport, remoteuser, remotehost,
                          client_calist_map, 
                          dryrun=True,
                          dbase=None):
    """execute remote commands"""
    remote_blk_execute = curry_args_for_remote_block_execute(remoteuser=remoteuser,
                                                             remotehost=remotehost,
                                                             remoteport=remoteport,
                                                             dryrun=dryrun)

    executed_commands = ssh_host_script(fqdn,
                                        client_calist_map, 
                                        target_ssh_config=os.path.join(targetconfigdir(), "ssh_config"),
                                        render_command=remote_blk_execute,
                                        dbase=dbase)
    # executed_commands is a list of empty strings, one per command
    # Feedback was emitted directly to stderr
    if len(executed_commands) == 1:
        myformat = "{}: Executed {} client host config command for {}"
    else:
        myformat = "{}: Executed {} client host config commands for {}"
    print(myformat.format(MYPROGNAME, len(executed_commands), fqdn), file=sys.stderr)

#def normalizehost(hostname, default_domain="bernatchez.net"):
#    """When a host name contains no '.' append '.' + default_domain"""
#    if '.' in hostname:
#        return hostname
#    else:
#        return hostname + '.' + default_domain

def generate_local_client(fqdn, client_calist_map, scriptfilename, dbase=None):
    """generate a local script for a given client host"""
    rendered_commands = ssh_host_script(fqdn,
                                        client_calist_map, 
                                        target_ssh_config=os.path.join(targetconfigdir(), "ssh_config"),
                                        render_command=pipe_block_into,
                                        dbase=dbase)


    print("{}: Generating script: {}".format(MYPROGNAME, scriptfilename), file=sys.stderr)
    with open(scriptfilename, "w") as scriptfile:
        for aline in LOCALSCRIPTHEADER:
            scriptfile.write(aline)
        if len(rendered_commands) == 0:
            scriptfile.write("echo No configuration changes required for {} as a client host\n".format(fqdn))
        for acommand in rendered_commands:
            scriptfile.write(acommand)
        for aline in SCRIPTTRAILEROPEN:
            scriptfile.write(aline)
        scriptfile.write(SCRIPTTRAILERNODE.format(fqdn))
        for aline in LOCALTRAILERCLOSE:
            scriptfile.write(aline)


def port_user_host_func(dbase):
    """curry dbase arg out of  port,user,host mapping function"""
    def port_user_host(fqdn):
        user = "ubuntu"
        port = 22
        host = fqdn
        try:
            mapping = dbase['ROUTES'][fqdn]
            try:
                ruser = mapping['REMOTEUSER']
                if ruser is not None:
                    user = ruser
            except KeyError as e:
                pass
            try:
                rport = mapping['REMOTEPORT']
                if rport is not None:
                    port = rport
            except KeyError as e:
                pass
            try:
                rhost = mapping['REMOTEHOST']
                if rhost is not None:
                    host = rhost
            except KeyError as e:
                pass
        except KeyError as e:
            pass
        return (port, user, host,)
    return port_user_host

DEFAULT_PUBSCRIPTPREFIX="configscripts/cfg"
def makeup_scriptfilenames(fqdn, prefix=DEFAULT_PUBSCRIPTPREFIX):
    """Compose script file names"""
    mynames={"rserver": '{}-remoteserver-{}'.format(prefix, fqdn),
             "lserver": '{}-localserver-{}'.format(prefix, fqdn),
             "rclient": '{}-remoteclient-{}'.format(prefix, fqdn),
             "lclient": '{}-localclient-{}'.format(prefix, fqdn)}
    return mynames

def config_all(server_certs,
               server_calist_map,
               client_calist_map,
               basedir="content",
               publishpartsdir="parts",
               publishscriptprefix=DEFAULT_PUBSCRIPTPREFIX,
               port_user_host_lookup=None,
               dbase=None):
    """\
    Config all hosts, servers and clients for host and/or user certificate authentication.
    Includes installing host certificates, trusted cas, revoked users, and sshd_config snippets.
    hosts = client_calist_map.keys()
    """
    user_authenticators = server_calist_map.keys()
    hosts = server_certs.keys()
    both = list(set(hosts + user_authenticators))
    allnodes = list(set( both + client_calist_map.keys()))
    fqdns = allnodes
    count = len(fqdns)
    # copy cert_setup and limited-passwordfree-sudo  scripts so that they will be made available for download
    # with publish.
    full_cert_setup = os.path.join(basedir, publishscriptprefix + '-cert_setup')
    full_cert_setup_source = os.path.join( '/usr/local/bin', 'cert_setup')
    print("{}: duplicating {} to {}".format(MYPROGNAME, full_cert_setup_source, full_cert_setup), file=sys.stderr)
    shutil.copyfile(full_cert_setup_source, full_cert_setup)
    
    full_limited = os.path.join(basedir, publishscriptprefix + '-limited-passwordfree-sudo')
    full_limited_source = os.path.join( '/usr/local/bin', 'limited-passwordfree-sudo')
    print("{}: duplicating {} to {}".format(MYPROGNAME, full_limited_source, full_limited), file=sys.stderr)
    shutil.copyfile(full_limited_source, full_limited)

    monoall=publishscriptprefix + '-all'
    fullmonoall=os.path.join(basedir, monoall)
    if count == 0:
        print("{}: No Hosts to configure", file=sys.stderr)
        with open(fullmonoall, "w") as scriptfile:
            # emit header lines
            scriptfile.write("#!/bin/bash\n")
            scriptfile.write("# This script was generated by the utility {} of the package {}\nset -e\n".format(MYPROGNAME,
                                                                                                                MYBUNDLE))
            scriptfile.write("echo No Hosts to configure")
    else:
        # one script for each combination
        for fqdn in fqdns:
            mynames=makeup_scriptfilenames(fqdn, prefix=publishscriptprefix)
            for akey in mynames.keys():
                mynames[akey] = os.path.join(basedir, mynames[akey])
            remoteport, remoteuser, remotehost = port_user_host_lookup(fqdn)
            generate_remote_server(fqdn, remoteport, remoteuser, remotehost, server_certs, server_calist_map, mynames['rserver'],
                                   open_file=None,
                                   dbase=dbase)
            generate_remote_client(fqdn, remoteport, remoteuser, remotehost, client_calist_map, mynames['rclient'],
                                   open_file=None,
                                   dbase=dbase)
            generate_local_server(fqdn, server_certs, server_calist_map, mynames['lserver'], dbase=dbase)
            generate_local_client(fqdn, client_calist_map, mynames['lclient'], dbase=dbase)
        # regenerate one monolithic remote script combining all server and client remote script lines
        monoall=publishscriptprefix + '-all'
        fullmonoall=os.path.join(basedir, monoall)
        with open(fullmonoall, "w") as scriptfile:
            # emit header lines
            for aline in REMOTESCRIPTHEADER:
                scriptfile.write(aline)
            for fqdn in fqdns:
                mynames=makeup_scriptfilenames(fqdn, prefix=publishscriptprefix)
                remoteport, remoteuser, remotehost = port_user_host_lookup(fqdn)
                generate_remote_server(fqdn, remoteport, remoteuser,
                                       remotehost, server_certs, server_calist_map, mynames['rserver'],
                                       open_file=scriptfile, dbase=dbase)
                generate_remote_client(fqdn, remoteport, remoteuser, remotehost, client_calist_map, mynames['rclient'],
                                       open_file=scriptfile,
                                       dbase=dbase)
            # emit trailer lines
            for aline in SCRIPTTRAILEROPEN:
                scriptfile.write(aline)
            for fqdn in fqdns:
                scriptfile.write(SCRIPTTRAILERNODE.format(fqdn))
            for aline in REMOTETRAILERCLOSE:
                scriptfile.write(aline)
    return monoall


            
DEBUGMESSAGES=False
if __name__ == '__main__':
    files_dir = get_base_dir(debugflag=False)
    defaults = set_defaults(files_dir)
    dbase_file=dbase_file_name(files_dir)
    if os.path.exists(dbase_file):
        dbase = load_dbase(dbase_file)
        server_calist_map = interested_server_cas(dbase) # server fqdn to user ca list for updating trusted cas and revoked user certs
        client_calist_map = interested_client_cas(dbase) # client fqdn to host ca list for updating ssh_known_hosts and revoked host certs
        server_certs = servers_certifyers(dbase) # map server fqdn to CA record that certified the server
        serverset = server_calist_map.keys() # servers who trust some user cas
        clientset = client_calist_map.keys() # clients who can access some certified hosts
        certified_servers = server_certs.keys()
        nodeset = list(set(serverset + clientset + certified_servers))
    else:
        dbase = None


    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= ["defaults", "newdbase", "newclientca", "newhostca",
                   "certifyclient","certifyhost", "recertify",
                   "revuser", "revhost", "publish", "routing", "addservers", "addclients",
                   "export", "samplekeygen", "info", "prune"]
    parsers = {}
    for aname in parser_names:
        parsers[aname] = subparsers.add_parser(aname)
    agroup=parsers["routing"].add_mutually_exclusive_group(required=True)
    agroup.add_argument('-v', '--view',  dest='view', action='store_true', default=False,
                        help="View all routings in json format.")
    agroup.add_argument('-n', '-nodename', dest='nodename', action='store', 
                        help="hostname of the node that needs to be routed")
    agroup.add_argument('-l', '-load-json', dest='load_json', action='store', 
                        help="Load all routings from this json format filename.")
    parsers["routing"].add_argument('-u', '--user',  dest='user',
                                          action='store', default='ubuntu',
                                          help="user account name we route to" +
                                          " (default 'ubuntu')")
    parsers["routing"].add_argument('-p', '--port',  dest='port', type=int,
                        action='store', default=32000,
                        help="port number we route to" +
                        " (default {})".format(32000))
    parsers["routing"].add_argument('-r', '--remote-host',  dest='remote_host', default="guanabana",
                                          action='store',
                                          help="remote host name we route to" +
                                          " (default {})".format("guanabana"))
    parsers["routing"].add_argument('--default-domain',  dest='default_domain', 
                                        action='store', default=defaults['DEFAULT_DOMAIN'],
                                        help="Domain name that we'll append to dotless host names" +
                                        " (default {})".format(defaults['DEFAULT_DOMAIN']))
    parsers["addservers"].add_argument('-a', '--authority',  dest='authority', 
                                        action='store', default=defaults['USERAUTHORITY'],
                                        help="Name of authority that signs client certificates" +
                                        " (default {})".format(defaults['USERAUTHORITY']))
    parsers["addservers"].add_argument('-t', '--tag',  dest='tag', 
                                        action='store', default=defaults['USERTAG'],
                                        help="Tag regarding the range of activity of this CA's certificates." +
                                        " (default {})".format(defaults['USERTAG']))
    parsers["addservers"].add_argument('--default-domain',  dest='default_domain', 
                                        action='store', default=defaults['DEFAULT_DOMAIN'],
                                        help="Domain name that we'll append to dotless host names" +
                                        " (default {})".format(defaults['DEFAULT_DOMAIN']))
    parsers["addservers"].add_argument('interested-servers',  nargs='+', action='store', 
                                        help="Additional interested servers to add to the user CA")

    
    
###    
    parsers["newclientca"].add_argument('-a', '--authority',  dest='authority', 
                                        action='store', default=defaults['USERAUTHORITY'],
                                        help="Name of authority that signs client certificates" +
                                        " (default {})".format(defaults['USERAUTHORITY']))
    
    parsers["newclientca"].add_argument('--default-domain',  dest='default_domain', 
                                        action='store', default=defaults['DEFAULT_DOMAIN'],
                                        help="Domain name that we'll append to dotless host names" +
                                        " (default {})".format(defaults['DEFAULT_DOMAIN']))
    
    parsers["newclientca"].add_argument('-u', '--users',  nargs='+', dest='users',
                                        action='store', default=defaults['USERS'],
                                        help="Accounts on server(s) this CA will authorize by default in its certificates." +
                                        " Can be overidden by certifyclient." +
                                        " (default {})".format(defaults['USERS']))

    parsers["newclientca"].add_argument('-i', '--interested-servers',  nargs='+', dest='interested_servers',
                                          action='store', default=defaults['INTERESTED_SERVERS'],
                                        help="This CA's certificates will grant access to these servers." +
                                        " (default {})".format(defaults['INTERESTED_SERVERS']))

    parsers["newclientca"].add_argument('-v', '--validity-weeks',  type=int, dest='validity_weeks',
                                          action='store', default=defaults['USERVALIDITY_WEEKS'],
                                        help="This CA will sign certificates for this many weeks by default." +
                                        " Can be overidden by certifyclient." +
                                        " (default {})".format(defaults['USERVALIDITY_WEEKS']))

    parsers["newclientca"].add_argument('-t', '--tag',  dest='tag', 
                                        action='store', default=defaults['USERTAG'],
                                        help="Tag regarding the range of activity of this CA's certificates." +
                                        " (default {})".format(defaults['USERTAG']))
    
    parsers["newhostca"].add_argument('-a', '--authority',  dest='authority', 
                                      action='store', default=defaults['HOSTAUTHORITY'],
                                      help="Name of authority that signs host certificates" +
                                      " (default {})".format(defaults['HOSTAUTHORITY']))

    parsers["newhostca"].add_argument('--default-domain',  dest='default_domain', 
                                        action='store', default=defaults['DEFAULT_DOMAIN'],
                                        help="Domain name that we'll append to dotless host names" +
                                        " (default {})".format(defaults['DEFAULT_DOMAIN']))
    
    parsers["newhostca"].add_argument('-i', '--interested-clients',  nargs='+', dest='interested_clients',
                                      action='store', default=defaults['INTERESTED_CLIENTS'],
                                      help="This CA's certificates will be known to these clients." +
                                      " (default {})".format(defaults['INTERESTED_CLIENTS']))

    parsers["newhostca"].add_argument( '-k', '--keyfilename', dest="keyfilename",
                                       action='store', default=defaults['HOSTKEYFILE'], 
                                       help="Name to use for host key files (default {}).".format(defaults['HOSTKEYFILE']))

    parsers["newhostca"].add_argument('-v', '--validity-weeks',  type=int, dest='validity_weeks',
                                      action='store', default=defaults['HOSTVALIDITY_WEEKS'],
                                      help="Default lifespan - in weeks - of certificates this CA signs" +
                                      " (default {})".format(defaults['HOSTVALIDITY_WEEKS']))

    parsers["newhostca"].add_argument('-t', '--tag',  dest='tag', 
                                      action='store', default=defaults['HOSTTAG'],
                                      help="Tag to identify the group of hosts CA is going to service" +
                                      " (default {})".format(defaults['HOSTTAG']))
    
    parsers["certifyclient"].add_argument('-a', '--authority',  dest='authority', 
                                          action='store', default=defaults['USERAUTHORITY'],
                                          help="Name of authority that signs client certificates" +
                                          " (default {})".format(defaults['USERAUTHORITY']))

    parsers["certifyclient"].add_argument('-t', '--tag',  dest='tag', 
                                          action='store', default=defaults['USERTAG'],
                                          help="Tag related to the usage of the resulting certificates" +
                                          " (default {})".format(defaults['USERTAG']))
    
    parsers["certifyclient"].add_argument('-u', '--users',  nargs='*', dest='users',
                                          action='store', default=[],
                                          help="Allows access to these server user accounts" +
                                          " (default is set by authority)")

    parsers["certifyclient"].add_argument('-v', '--validity-weeks',  type=int, dest='validity_weeks',
                                          action='store', default=None,
                                          help="Grant client access for this many weeks" +
                                          " (default is set by authority)")

    parsers["certifyclient"].add_argument('keyfilename', 
                                          action='store', 
                                          help="Name of key file to certify. E.G. 'mangobiche_repouser'")

    parsers["samplekeygen"].add_argument( '-k', '--keyfilename', 
                                          action='store', default="hostname_purpose", 
                                          help="Name of key file to certify (default 'hostname_purpose')."+
                                         " E.G. 'mangobiche_repouser'")

    parsers["certifyhost"].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["certifyhost"].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["certifyhost"].add_argument('fqdn',  
                                          action='store',
                                          help="Fully qualified domain name of host the certificate is for")
    
    parsers["certifyhost"].add_argument('-o', '--other-subdomains',  nargs='*', dest='other_subdomains',
                                          action='store', 
                                          help="Alternate subdomain names which resolve to the same host" )

    parsers["certifyhost"].add_argument('--default-domain',  dest='default_domain', 
                                        action='store', default=defaults['DEFAULT_DOMAIN'],
                                        help="Domain name that we'll append to dotless host names" +
                                        " (default {})".format(defaults['DEFAULT_DOMAIN']))
    
    parsers["certifyhost"].add_argument('-v', '--validity-weeks',  type=int, dest='validity_weeks',
                                          action='store', 
                                          help="Host certificate will be valid for this many weeks from now.")

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

    parsers["recertify"].add_argument('-t', '--tag',  dest='tag', 
                                          action='store', default=defaults['USERTAG'],
                                          help="Tag related to the usage of the resulting certificates" +
                                          " (default {})".format(defaults['USERTAG']))
    
    parsers["recertify"].add_argument('keyfilename', 
                                          action='store', 
                                          help="Name of key file to certify. E.G. 'mangobiche_bzuser'")

    parsers["recertify"].add_argument('-u', '--users',  nargs='*', dest='users',
                                          action='store', 
                                          help="Allows access to these server user accounts" +
                                          " (default same as before)")

    parsers["recertify"].add_argument('-v', '--validity-weeks',  type=int, dest='validity_weeks',
                                          action='store',
                                          help="Grant client access for this many weeks from now" +
                                          " (default same as before)")

    parsers["revuser"].add_argument('-a', '--authority',  dest='authority', 
                                          action='store', default=defaults['USERAUTHORITY'],
                                          help="Name of authority that initially signed client certificate" +
                                          " (default {})".format(defaults['USERAUTHORITY']))

    parsers["revuser"].add_argument('-t', '--tag',  dest='tag', 
                                          action='store', default=defaults['USERTAG'],
                                          help="Tag of the ca that initially signed client certificate" +
                                          " (default {})".format(defaults['USERTAG']))
    
    agroup=parsers["revuser"].add_mutually_exclusive_group(required=True)
    agroup.add_argument('-k', '--keyfilename', dest='keyfilename', action='store', 
                        help="Name of key file to revoke. E.G. 'mangobiche_repouser'")
    agroup.add_argument('-l', '-load-json', dest='load_json', action='store',
                        help="Name of json file to load all user revocations from. E.G. export/user_revocations.json")
    
    parsers["revhost"].add_argument('-a', '--authority',  dest='authority', 
                                          action='store', default=defaults['USERAUTHORITY'],
                                          help="Name of authority that initially signed client certificate" +
                                          " (default {})".format(defaults['USERAUTHORITY']))

    parsers["revhost"].add_argument('-t', '--tag',  dest='tag', 
                                          action='store', default=defaults['USERTAG'],
                                          help="Tag of the ca that initially signed client certificate" +
                                          " (default {})".format(defaults['USERTAG']))
    
    agroup=parsers["revhost"].add_mutually_exclusive_group(required=True)
    agroup.add_argument('-n', '--nodename', dest='nodename', action='store', 
                        help="domain name of the node to revoke.")
    agroup.add_argument('-l', '-load-json', dest='load_json', action='store',
                        help="Name of json file to load all host revocations from. E.G. export/host_revocations.json")
    
    parsers["revhost"].add_argument('--default-domain',  dest='default_domain', 
                                    action='store', default=defaults['DEFAULT_DOMAIN'],
                                    help="Domain name that we'll append to dotless node names" +
                                    " (default {})".format(defaults['DEFAULT_DOMAIN']))
    
    defaultscript = 'cfg'
    parsers["publish"].add_argument('-s', '--scriptname', dest='scriptname', default=defaultscript,
                                          help='Prefix to use for generating script file names. (default {})'.format(defaultscript))
    parsers["publish"].add_argument('-b', '--base-directory',  dest='base_directory', 
                                    action='store', default=defaults['PUBLISHDIR'],
                                    help="base directory where " +
                                    "{}/ and {}/ and {}/ files are published (default {})".format(defaults['PUBLISHPARTS'],
                                                                                                 defaults['PUBLISHCERTS'],
                                                                                                 defaults['PUBLISHSCRIPTS'],
                                                                                                 defaults['PUBLISHDIR']))
    parsers["publish"].add_argument('-r', '--remove-existing',  dest='remove_existing', 
                                    action='store_true', default=False,
                                    help="Remove all certificates allready in publish directory.")
    ARGS = PARSER.parse_args()
    subcommand=ARGS.subparser_name
    
    if subcommand == 'defaults':
        json.dump(defaults, sys.stdout, indent=4, sort_keys=True)
        print(file=sys.stdout)
    elif subcommand == 'newdbase':
        new_dbase(dbase_file)
        tar = tarfile.open(INITTARBALL)
        tar.extractall()
        tar.close()
        print("{}: {} has been created".format(MYPROGNAME, dbase_file))
    elif dbase is None:
        print("{}: No database. First create a data base using 'newdbase'".format(MYPROGNAME),
              file=sys.stderr)
    elif subcommand == 'info':
        print("{}: CAS".format(MYPROGNAME), file=sys.stderr)
        cas(dbase)
        print("{}: CLIENTINFO".format(MYPROGNAME), file=sys.stderr)
        clientinfo(dbase)
    elif subcommand == 'routing':
        if ARGS.view:
            json.dump(dbase['ROUTES'], sys.stdout, indent=4, cls=DateTimeEncoder)
        elif ARGS.nodename:
            myhostname = normalizehost(ARGS.nodename, default_domain=ARGS.default_domain)
            rhostname = normalizehost(ARGS.remote_host, default_domain=ARGS.default_domain)
            myport = ARGS.port
            myuser = ARGS.user
            myentry = { "REMOTEUSER":myuser,
                        "REMOTEPORT":myport,
                        "REMOTEHOST":rhostname}
            dbase['ROUTES'][myhostname]=myentry
            if ARGS.dryrun:
                pass
            else:
                with open(dbase_file, "w") as dbout:
                    json.dump(dbase, dbout, indent=4, cls=DateTimeEncoder)
        elif ARGS.load_json:
            loadfilename = os.path.expanduser(ARGS.load_json)
            with open(loadfilename, "r") as loadfile:
                myindirects = json.load(loadfile, object_hook=datetime_hook)
            dbase['ROUTES']=myindirects
            if ARGS.dryrun:
                pass
            else:
                with open(dbase_file, "w") as dbout:
                    json.dump(dbase, dbout, indent=4, cls=DateTimeEncoder)
    elif subcommand == 'newclientca':
        mydbase = dbase
        interested_servers = [normalizehost(ahost, default_domain=ARGS.default_domain) for ahost in ARGS.interested_servers]
        
        was_modified = newclientca(authority=ARGS.authority,
                                   users=ARGS.users,
                                   interested_servers=interested_servers,
                                   validity_weeks=ARGS.validity_weeks,
                                   tag=ARGS.tag, 
                                   dbase=mydbase,
                                   dryrun=ARGS.dryrun)
        if was_modified:
            print("{}: Updating database: {}.".format(MYPROGNAME, dbase_file),
                  file=sys.stderr)
            with open(dbase_file, "w") as dbout:
                json.dump(mydbase, dbout, indent=4, cls=DateTimeEncoder)
            
    elif subcommand == 'newhostca':
        mydbase = dbase
        interested_clients = [normalizehost(ahost, default_domain=ARGS.default_domain) for ahost in ARGS.interested_clients]
        was_modified = newhostca(authority=ARGS.authority,
                                 keyname=ARGS.keyfilename,
                                 interested_clients=interested_clients,
                                 validity_weeks=ARGS.validity_weeks,
                                 group_tag=ARGS.tag, 
                                 dbase=mydbase,
                                 dryrun=ARGS.dryrun)
        if was_modified:
            print("{}: Updating database: {}.".format(MYPROGNAME, dbase_file),
                  file=sys.stderr)
            with open(dbase_file, "w") as dbout:
                json.dump(mydbase, dbout, indent=4,cls=DateTimeEncoder)

    elif subcommand == 'export':
        exportdir='export'
        myexportdir = os.path.expanduser(exportdir)
        try:
            os.makedirs(myexportdir)
        except OSError as e:
            if e.errno == 17:
                print("{}: {} : {}. Continuing.".format(MYPROGNAME, e.filename, e.strerror), file=sys.stderr)
            else:
                raise
        if ARGS.dryrun:
            was_modified = False
        else:
            was_modified = prune_expired_keys(dbase)
            export_client_pubs(dbase, exportdir=myexportdir)
            export_revocations(dbase, exportdir=myexportdir)
            export_routing(dbase, exportdir=myexportdir)
            exportinfo(dbase)
        if was_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 == 'certifyclient':
        if len(ARGS.users) == 0:
            myusers = None
        else:
            myusers = ARGS.users
        was_modified = certifyclient(ARGS.keyfilename,
                          dbase,
                          authority=ARGS.authority,
                          tag=ARGS.tag,
                          users=myusers,
                          valid_weeks=ARGS.validity_weeks,
                          dryrun=ARGS.dryrun,
                          verbose=False)
        if was_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 == 'recertify':
        was_modified = recertify(ARGS.keyfilename,
                                 dbase,
                                 authority=ARGS.authority,
                                 tag=ARGS.tag,
                                 users=ARGS.users,
                                 valid_weeks=ARGS.validity_weeks,
                                 dryrun=ARGS.dryrun,
                                 verbose=False)
        if was_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 == 'revuser':
        if ARGS.keyfilename is not None:
            was_modified = revokeuser(ARGS.keyfilename,
                                      dbase,
                                      authority=ARGS.authority,
                                      tag=ARGS.tag,
                                      dryrun=ARGS.dryrun)
        else:
            myjsonfile = os.path.expanduser(ARGS.load_json)
            if ARGS.dryrun:
                was_modified = False
            else:
                with open(myjsonfile, "r") as load_json:
                    urevocations = json.load(load_json, object_hook=datetime_hook)
                dbase['USER_REVOCATIONS']=urevocations
                was_modified = True
        if was_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 == 'revhost':
        if ARGS.nodename is not None:
            mynodename = normalizehost(ARGS.nodename, default_domain=ARGS.default_domain)
            was_modified = revokehost(mynodename,
                                      dbase,
                                      authority=ARGS.authority,
                                      tag=ARGS.tag,
                                      dryrun=ARGS.dryrun)
        else:
            myjsonfile = os.path.expanduser(ARGS.load_json)
            if ARGS.dryrun:
                was_modified = False
            else:
                with open(myjsonfile, "r") as load_json:
                    hrevocations = json.load(load_json, object_hook=datetime_hook)
                dbase['HOST_REVOCATIONS']=hrevocations
                was_modified = True
        if was_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 == 'certifyhost':
        myfqdn = normalizehost(ARGS.fqdn, default_domain=ARGS.default_domain)
        was_modified = certifyhost(myfqdn, dbase,
                                   authority=ARGS.authority,
                                   group_tag=ARGS.tag,
                                   other_subdomains=ARGS.other_subdomains,
                                   valid_weeks=ARGS.validity_weeks,
                                   dryrun=ARGS.dryrun,
                                   verbose=False)
        if was_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 == 'publish':
        currentdir = os.getcwd()
        print("{}: CWD: {}".format(MYPROGNAME, currentdir), file=sys.stderr)
        # example_host='mangobiche.bernatchez.net'
        basedir=os.path.expanduser(ARGS.base_directory)
        publishpage=defaults['PUBLISHAUTHVIEW']
        publishcerts=defaults['PUBLISHCERTS']
        publishpartsdir=defaults['PUBLISHPARTS']
        publishscriptprefix=os.path.join(defaults['PUBLISHSCRIPTS'], ARGS.scriptname)
        port_user_host_lookup=port_user_host_func(dbase)
        
        # host_calist = client_calist_map[example_host]
        if ARGS.remove_existing:
            # remove all our previously published certificates and public keys
            for f in glob.glob( os.path.join( basedir, publishcerts , "*.pub")):
                print("{}: Removing: {}".format(MYPROGNAME, f), file=sys.stderr)
                if ARGS.dryrun:
                    pass
                else:
                    os.remove(f)
            # remove all our previously published config scripts
            for f in glob.glob( os.path.join( basedir, publishscriptprefix + "-*")):
                print("{}: Removing: {}".format(MYPROGNAME, f), file=sys.stderr)
                if ARGS.dryrun:
                    pass
                else:
                    os.remove(f)

        # server fqdn to user ca list for updating trusted cas and revoked user certs
        server_calist_map = interested_server_cas(dbase)
        # client fqdn to host ca list for updating ssh_known_hosts and revoked host certs
        client_calist_map = interested_client_cas(dbase)
        # map server fqdn to CA record that certified the server
        server_certs = servers_certifyers(dbase) 
        serverset = server_calist_map.keys() # servers who trust some user cas
        clientset = client_calist_map.keys() # clients who can access some certified hosts
        certified_servers = server_certs.keys()
        nodeset = list(set(serverset + clientset + certified_servers))

        # generate all the client and server scripts
        allscript_link=config_all(server_certs,
                                  server_calist_map,
                                  client_calist_map,
                                  basedir=basedir,
                                  publishpartsdir=publishpartsdir,
                                  publishscriptprefix=publishscriptprefix,
                                  port_user_host_lookup=port_user_host_lookup,
                                  dbase=dbase)

        # generate host authority view
        principal_quints = [ aquint for aquint in generate_host_principals(dbase)]
        mdhostinfo = ""
        for anauthority, atag, aprincipals, aclients, aothers in principal_quints:
            mdhostinfo=mdhostinfo + "* Authority: {} Tag: {}\n".format(anauthority, atag)
            mdhostinfo=mdhostinfo + "    + Interested Clients:\n"
            for aclient in aclients:
                mynames=makeup_scriptfilenames(aclient, prefix=publishscriptprefix)
                aline = "        - {} | [Admin]({})\n".format(aclient, '#' + admin_heading(aclient))
                mdhostinfo=mdhostinfo + aline
            mdhostinfo=mdhostinfo + "    + Authenticated Servers:\n"
            for aprincipal in aprincipals:
                mynames=makeup_scriptfilenames(aprincipal, prefix=publishscriptprefix)
                aline = "        - {} | [Admin]({})\n".format(aprincipal, '#' + admin_heading(aprincipal))
                mdhostinfo = mdhostinfo + aline
        if mdhostinfo == "":
            mdhostinfo = "No hosts have been certified\n\n"
        else:
            mdhostinfo = mdhostinfo + "\n"

        # generate user authority view
        principal_quads = [ aquad for aquad in generate_user_principals(dbase)]
        mduserinfo=""
        for anauthority, atag, akeys, aservers in principal_quads:
            mduserinfo=mduserinfo + "* Authority: {} Tag: {}\n".format(anauthority, atag)
            mduserinfo=mduserinfo + "    + Interested Servers:\n"
            for aserver in aservers:
                mynames=makeup_scriptfilenames(aserver, prefix=publishscriptprefix)
                aline = "        - {} | [Admin]({})\n".format(aserver, '#' + admin_heading(aserver))
                mduserinfo=mduserinfo + aline
            mduserinfo=mduserinfo + "    + Authenticated User Keys:\n"
            for akey in akeys:
                aline = "        - {0} | [certificate]({1}) | [pubkey]({2})\n".format(akey,
                                                                                  os.path.join(defaults['PUBLISHCERTS'],
                                                                                               '{}-cert.pub'.format(akey)),
                                                                                  os.path.join(defaults['PUBLISHCERTS'],
                                                                                               '{}.pub'.format(akey)))
                mduserinfo = mduserinfo + aline
            
        cert_file_quints = [ apair for apair in generate_certificate_filename_value_quints(dbase)]
        mdpart=MDAUTHSOURCE.format(hostinfo=mdhostinfo,
                                   userinfo=mduserinfo,
                                   allscript=allscript_link,
                                   configdir=targetconfigdir())

        # emit authority view
        outputmdfile=os.path.join(basedir, publishpage)
        print("{}: Generating markdown: {}".format(MYPROGNAME, outputmdfile), file=sys.stderr)
        with open(outputmdfile, "w") as publishout:
            publishout.write(mdpart)

        # generate and emit admin view
        publishpage=defaults['PUBLISHADMINVIEW']
        mdpart=MDADMINSOURCE.format(allscript=allscript_link)
        outputmdfile=os.path.join(basedir, publishpage)
        print("{}: Generating markdown: {}".format(MYPROGNAME, outputmdfile), file=sys.stderr)
        with open(outputmdfile, "w") as publishout:
            publishout.write(mdpart)
            for anode in nodeset:
                mynames=makeup_scriptfilenames(anode, prefix=publishscriptprefix)
                generate_admin_markdown(anode,
                                        server_certs, server_calist_map, client_calist_map,
                                        mynames,
                                        publishout,
                                        dbase=dbase)
            

        # generate and emit user view
        publishpage=defaults['PUBLISHUSERVIEW']
        mdpart=MDUSERSOURCE
        outputmdfile=os.path.join(basedir, publishpage)
        print("{}: Generating markdown: {}".format(MYPROGNAME, outputmdfile), file=sys.stderr)
        with open(outputmdfile, "w") as publishout:
            publishout.write(mdpart)
            for afilename, acertvalue, apubvalue, ausers, ahosts  in cert_file_quints:
                aline = "* {} | [certificate]({}) | [public key]({})\n".format(afilename,
                                                                               os.path.join(publishcerts,
                                                                                            afilename + "-cert.pub"),
                                                                               os.path.join(publishcerts,
                                                                                            afilename + ".pub"))
                publishout.write(aline)
                publishout.write("    + accounts\n")
                for auser in ausers:
                    publishout.write("        - {}\n".format(auser))
                publishout.write("    + hosts\n")
                for ahost in ahosts:
                    publishout.write("        - {}\n".format(ahost))
        # publish all our certificates and public keys
        for afilename, acertvalue, apubvalue, ausers, ahosts in cert_file_quints:
            fullname = os.path.join(basedir, publishcerts, afilename  + "-cert.pub")
            print("{}: Emitting certificate: {}".format(MYPROGNAME, fullname), file=sys.stderr)
            with open(fullname, "w") as acertfile:
                acertfile.write(acertvalue)
            fullname = os.path.join(basedir, publishcerts, afilename  + ".pub")
            print("{}: Emitting public key: {}".format(MYPROGNAME, fullname), file=sys.stderr)
            with open(fullname, "w") as apubfile:
                apubfile.write(apubvalue)
        
    elif subcommand == 'samplekeygen':
        keygen_cmd= [ '/usr/bin/ssh-keygen', '-b', '4096', '-t', 'rsa',  '-C', ARGS.keyfilename, '-f', ARGS.keyfilename ]
        scmd = cmd_to_string(keygen_cmd)
        print(scmd)
    elif subcommand == 'prune':
        if ARGS.dryrun:
            pass
        else:
            was_modified = prune_expired_keys(dbase)
            if was_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)
        
    else:
        print("{}: {} not implemented.".format(MYPROGNAME, subcommand))
