#!/usr/bin/env python3

# ------------------------------------------------------------------------
# Copyright 2021 IBM Corp. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ------------------------------------------------------------------------

""" Generate a passphrase-less SSH private / public key pair """


# Global modules

import getpass
from   pathlib import Path
import socket
import subprocess
import sys


# Local modules

from modules.args    import getCommonArgsParser
from modules.context import getContext
from modules.tools   import readInput


# Functions

def _getArgs():
    """ Get command line arguments """
    parser = getCommonArgsParser(
        'Generate a passphrase-less SSH private / public key pair'
    )

    parser.add_argument(
        '-i',
        '--ssh-id',
        metavar  = '<ssh-id>',
        required = False,
        help     = "Path to the SSH ID private key file"
    )

    return parser.parse_args()


def _getDefaultId(ctx):

    sshId = ctx.ar.ssh_id

    if not sshId:
        sshId = ctx.cr.build.user.sshid

    if not sshId:
        sshId = f'{Path.home()}/.ssh/id_rsa'

    return sshId


def _getDefaultComment():
    return f'{getpass.getuser()}@{socket.gethostname()}'


# ----------------------------------------------------------------------

def _main():

    ctx = getContext(_getArgs(), withConfig=False)

    sshId   = readInput('Enter file in which to save the key',
                        _getDefaultId(ctx), False, False, False)

    comment = readInput('Enter comment which is stored with the key',
                        _getDefaultComment(), False, False, False)

    subprocess.run(['ssh-keygen', '-f', sshId, '-C', comment], check=False)


# ----------------------------------------------------------------------

if __name__ == '__main__':
    try:
        _main()
    except KeyboardInterrupt:
        print()
    sys.exit(0)
