#! /usr/bin/env python3

# Core packages
import argparse
import os
import pkg_resources
import sys

# Local packages
from canonicalwebteam.upload_assets.uploader import gather_files, upload_files

api_domain = os.environ.get('UPLOAD_ASSETS_API_DOMAIN', 'assets.ubuntu.com')
api_secret_token = os.environ.get('UPLOAD_ASSETS_API_TOKEN')

parser = argparse.ArgumentParser(
    description='Upload assets from this directory'
)
parser.add_argument(
    '-d', '--api-domain',
    help=f'The domain for the API. Default: {api_domain}.',
    default=api_domain
)
parser.add_argument(
    '-i', '--insecure',
    help=(
        'Communicate with the API over HTTP rather than HTTPS.'
        'For use in development only.'
    ),
    action="store_true"
)
parser.add_argument(
    '-s', '--api-token',
    help='The secret authentication token for the API',
    default=api_secret_token
)
parser.add_argument(
    '-p', '--url-path',
    help='The URL path to upload the file to'
)
parser.add_argument(
    '-t', '--tags',
    help='Tags for uploaded assets',
    default='auto-upload'
)
parser.add_argument(
    '-v', '--version',
    action='store_true',
    help="Show the currently installed version of documentation-builder."
)
parser.add_argument(
    'upload_paths',
    help='A list of paths to files or directories to upload',
    nargs='*'
)
cli_arguments = vars(parser.parse_args())

if cli_arguments['version']:
    print(
        pkg_resources.get_distribution(
            "canonicalwebteam.upload-assets"
        ).version
    )
    sys.exit()
elif not bool(api_secret_token):
    print(
        "Error: API secret token required (--api-token|-s)"
    )
    sys.exit(1)

files = gather_files(cli_arguments['upload_paths'])
upload_files(
    files,
    api_domain=cli_arguments['api_domain'],
    api_token=cli_arguments['api_token'],
    tags=cli_arguments['tags'],
    url_path=cli_arguments['url_path'],
    insecure=cli_arguments['insecure']
)
