#!/usr/bin/env python

import os
import os.path
import json
import logging
from datetime import datetime
import mimetypes
import subprocess
import re
import copy

import six
from six.moves.urllib.parse import urlparse
import click


STATIC_DATA_ROOT_FOLDER = 'static-data'  # Root folder on S3


@click.group(context_settings=dict(help_option_names=['-h', '--help']))
def cli():
    """Static data management tools.

    These sets of commands help you with publishing and testing Static Data.
    """


@cli.command()
@click.option(
    '--repository',
    help="The name of the source repository that contains the static data files. If not "
         "specified then the name will be extracted from the url path from `git config "
         "--get remote.origin.url`.")
@click.option(
    '--user',
    help="A user name. The current version of static data on local disk will be published "
         "under /user-<user name>/. If not specified, then all referencable versions "
         "will be published.")
@click.option(
    '--region',
    default='eu-west-1',
    help="AWS region, default is 'eu-west-1'.")
@click.option(
    '--bucket',
    default='directive-tiers.dg-api.com',
    help="Bucket name, default is 'directive-tiers.dg-api.com'.")
def publish(repository, user, region, bucket):
    """Publish static data files to S3.

    Publish static data files by uploading to S3 and update the index file. All referencable
    versions will be published (i.e. all ).
    """
    click.echo("=========== STATIC DATA COMPRESSION ENABLED ===========")
    from boto.s3 import connect_to_region
    from boto.s3.connection import OrdinaryCallingFormat
    from boto.s3.key import Key

    conn = connect_to_region(region, calling_format=OrdinaryCallingFormat())
    bucket = conn.get_bucket(bucket)

    origin_url = None
    if not repository:
        try:
            cmd = 'git config --get remote.origin.url'
            click.echo("No repository specified. Using git to figure it out: {!r}".format(cmd))
            origin_url = subprocess.check_output(cmd.split(' ')).strip()
            if origin_url.startswith("http"):
                repository, _ = os.path.splitext(urlparse(origin_url).path)
            elif origin_url.startswith("git@"):
                repository = "/" + origin_url.split(":")[1].split(".")[0]
            else: