#!/usr/bin/env python

import sys
import os
import argparse

home_dir = "/home/"
source_dir = "authorized_keys.d"
temp = "authorized_keys.temp"
target_file = "authorized_keys"

text = "# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n"
text = text +  "# This file is autogenerated using update-akeys, please do not modify\n"
text = text +  "# it by hand, it will be likely overwritten\n"
text = text + "# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n"

parser = argparse.ArgumentParser(description="Tool that generates authorized_keys from authorized_keys.d")
parser.add_argument('-q', '--silent', action='store_true', help='Be completely quiet about all issues')
parser.add_argument('-p', '--home', type=str, help='Path to home folder')
parser.add_argument('-f', '--force', action='store_true', help='Forcefully update the file, removing any files that prevent it')
parser.add_argument('-u', '--user', type=str, help='Specify user for which you want to generate the keys')
params = parser.parse_args()

if (params.home is not None):
    home_dir = params.home

if (params.user is not None):
    source_dir = home_dir + params.user + "/.ssh/" + source_dir
    target_file = home_dir + params.user + "/.ssh/" + target_file

# Check if there is any directory for us
if (not os.path.isdir(source_dir)):
    if (not params.silent):
        print("Warning: no " + source_dir + " found")
    sys.exit(0)

#if (os.path.exists(temp)):
#    if (parser.force):
#        os.remove(temp)
#    else:
#        print("Error: the temp file " + temp + " already exists, please remove it first, or use --force option")
#        sys.exit(1)

files = os.listdir(source_dir)

for file in files:
    path = source_dir + "/" + file
    if (not os.path.isdir(path) and path.endswith(".keys")):
        with open(path, 'r') as fp:
            keys = fp.read()
            text = text + keys + "\n"

fp = open(target_file, "w")
fp.write(text)
fp.close()
