#!/usr/bin/env python

import argparse
from pathlib import Path, PurePath
from awscli_mfa_token_manager.token_data_builder import TokenDataBuilder
from awscli_mfa_token_manager.credentials_manager import CredentialsManager


def main():
    __parser = argparse.ArgumentParser(prog="manage_credentials",
                                       description="Utility to generate credentials for IAM users with MFA enabled",
                                       formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    user_home_path = str(Path.home())
    default_path = str(PurePath(user_home_path) / '.aws')
    __parser.add_argument("--profile", default="default", help="The aws profile to populate credentials")
    __parser.add_argument("--serial-number",
                          help="The ARN of the MFA device attached to the IAM user, skip if already added to AWS "
                               "config file, if provided will overwrite the existing mfa_serial for the given profile",
                          dest="serial_number")
    __parser.add_argument("--credentials-dir", default=default_path,
                          help="The path to credentials file, defaults to \'[USER_HOME]/.aws\'", dest="credentials_dir")
    __parser.add_argument("--token-code", help="The MFA token code to generate credentials", dest="token_code")
    __parser.add_argument("--expires", help="The time in seconds for which this token should be valid")
    args = __parser.parse_args()
    token_data = TokenDataBuilder()\
        .with_profile(args.profile)\
        .with_credentials_directory(args.credentials_dir)\
        .with_serial_number(args.serial_number)\
        .with_token_code(args.token_code)\
        .with_expires_in(args.expires).get_token_builder_data()
    credentials_manager = CredentialsManager(token_data["credentials_dir"],
                                             token_data["mfa_serial"],
                                             token_data["profile"],
                                             token_data["token_code"],
                                             token_data["expires"],
                                             token_data["lifetime"])
    credentials_manager.generate_token()


if __name__ == '__main__':
    main()
