#!/usr/bin/python
# -*- coding: utf-8 -*-
u"""
Generates an ssh public keyfile from a private key file using 'ssh-keygen -y'
and appends the private key file name as the comment field of the public key file. NOTE that
you will need to supply passphrases for each keyfile.
"""
from __future__ import print_function
import sys
import os
import socket
import argparse
import subprocess

MYBUNDLE='misc_client'
MYPROGNAME=os.path.basename(__file__)
MYHOSTNAME=socket.gethostname()

DERIVE_COMMAND=['/usr/bin/ssh-keygen', '-y', '-f', ]

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 ""


if __name__ == '__main__':
    currentdir = os.getcwd()
    PARSER = argparse.ArgumentParser(prog=MYPROGNAME, description=__doc__)
    PARSER.add_argument('-d', '--dryrun', dest='dryrun', action='store_true', default=False,
                       help="Just print the feedback, don't invoke any commands")
    PARSER.add_argument('-t', '--target-directory', dest='target_directory', default=currentdir,
                        help="Directory where to emit the public key file(s) (default {})".format(currentdir))
    mxgroup = PARSER.add_mutually_exclusive_group(required=True)
    mxgroup.add_argument('-f', '--keyfile', dest='keyfile', nargs='+',
                         help="private key file(s) from which public one(s) will be derived")
    ARGS = PARSER.parse_args()
    target = os.path.abspath(os.path.expanduser(ARGS.target_directory))
    absfiles = [ os.path.abspath(afile) for afile in ARGS.keyfile ]
    print("{}: Target directory: {}".format(MYPROGNAME, target), file=sys.stderr)
    try:
        os.chdir(target)
        for afile in absfiles:
            bfile = os.path.basename(afile)
            tfile = bfile + '.pub'
            derive_cmd = DERIVE_COMMAND + [ afile ]
            cstring = cmd_to_string(derive_cmd)
            redirected_cstring = "{} >{}".format(cstring,tfile)
            if ARGS.dryrun:
                print(redirected_cstring , file=sys.stderr)
                continue
            elif os.path.exists( tfile ):
                print("{}: skipping {} because it already exists.".format(MYPROGNAME, tfile), file=sys.stderr)
                continue
            else:
                print(redirected_cstring , file=sys.stderr)
                with open(tfile, "w") as pubfile:
                    try:
                        subprocess.check_call(derive_cmd, stdout=pubfile)
                    except subprocess.CalledProcessError:
                        print("{}: {} FAILED. Continuing...".format(MYPROGNAME, afile), file=sys.stderr)
                        continue
                with open(tfile, "r") as inpubfile:
                    pubfilestring = inpubfile.read()
                with open(tfile, "w") as pubfile:
                    print("{} {}".format(pubfilestring.rstrip('\n'), bfile), file=pubfile)

    finally:
        os.chdir(currentdir)

