#!/usr/bin/env python3
import argparse
import os


def main():
    args = handle_args()
    cmd = build_cmd(args)
    # Run the command
    print(f'Running command: {cmd}')
    result = os.system(cmd)
    if result != 0:
        print('')
        print('Removing problematic SSH key and trying again..')
        remove_ssh_key_cmd = 'ssh-keygen -f "${HOME}/.ssh/known_hosts" -R "[localhost]:1535"'
        os.system(remove_ssh_key_cmd)
        result = os.system(cmd)


def handle_args():
    help_string = 'This script copies files to the Q7S as long as port forwarding is active.\n'
    help_string += 'You can set up port forwarding with ' \
        '"ssh -L 1535:192.168.133.10:22 <eive-flatsat-ip>" -t /bin/bash'
    parser = argparse.ArgumentParser(
        description=help_string
    )
    # Optional arguments
    parser.add_argument('-r', '--recursive', dest='recursive', default=False, action='store_true')
    parser.add_argument('-t', '--target', help='Target destination', default='/tmp')
    parser.add_argument('-P', '--port', help='Target port', default=1535)
    # Positional argument(s)
    parser.add_argument('source', help='Source files to copy')
    return parser.parse_args()


def build_cmd(args):
    # Build run command
    cmd = 'scp '
    if args.recursive:
        cmd += '-r '
    cmd += f'-P {args.port} {args.source} root@localhost:'
    if args.target:
        cmd += args.target
    return cmd


if __name__ == "__main__":
    main()