#!/usr/bin/env python3

import os
import sys
import getopt
import logging
import mimetypes
import jinja2

import ccbrowse
import ccbrowse.storage
from ccbrowse.config import load_config, sharepath


def usage():
    sys.stderr.write('''Usage: {program_name} [BASE]
       {program_name} --help

Try `{program_name} --help\' for more information.
'''.format(program_name=program_name))


def print_help():
    sys.stdout.write('''Usage: {program_name} [BASE]
       {program_name} --help

Load the ccbrowse application to the storage.

Positional arguments:
  BASE            host base URL

Report bugs to <ccplot-general@lists.sourceforge.net>
'''.format(program_name=program_name))


def put(storage, filename, name, context=None):
    print('%s -> %s' % (filename, name))
    try:
        with open(filename, 'rb') as f:
            contents = f.read()
    except IOError as e:
        logging.error('%s: %s' % (e.filename, e.strerror))

    if context is not None and filename.endswith('.html'):
        template = jinja2.Template(contents.decode('utf-8'))
        raw_data = template.render(context).encode('utf-8')
    else:
        raw_data = contents

    obj = {
        'name': name,
        'raw_data': raw_data,
    }
    mime = mimetypes.MimeTypes()
    content_type = mime.guess_type(filename)[0]
    if content_type is not None:
        obj['content_type'] = content_type
    storage.store(obj)


def upload(storage, path, prefix='', context=None):
    for root, dirs, files in os.walk(path):
        files = [f for f in files if not f[0] == '.']
        dirs[:] = [d for d in dirs if not d[0] == '.']
        for name in files:
            filename = os.path.join(root, name)
            object_name = os.path.relpath(filename, path)
            put(storage, filename, prefix + object_name, context)


if __name__ == "__main__":
    program_name = sys.argv[0]

    try:
        opts, args = getopt.getopt(sys.argv[1:], "h", ['help'])
    except getopt.GetoptError as err:
        print(str(err))
        usage()
        sys.exit(1)

    if len(args) > 1:
        usage()
        sys.exit(1)

    base = args[0] if len(args) == 1 else ''

    try:
        config = load_config()
    except IOError as e:
        logging.error('%s: %s' % (e.filename, e.strerror))
        sys.exit(1)

    storage = ccbrowse.storage.Router(config.get('storage'))

    context = {
        'base': base,
    }

    path = os.path.join(sharepath, 'www')
    upload(storage, path, context=context)

    path = os.path.join(sharepath, 'colormaps')
    upload(storage, path, 'colormaps/')

    put(storage, 'profile.json', 'profile.json')
