#!/usr/bin/env python

import sys
import os
import logging
from tornado.options import parse_command_line, parse_config_file
from tornado.options import options, print_help

import slickbird
from slickbird import orm


def _log():
    if not _log.logger:
        _log.logger = logging.getLogger(__name__)
    return _log.logger
_log.logger = None


def main():
    defcfg = 'slickbird.cfg'
    parse_command_line()
    if options.config:
        parse_config_file(options.config)
    elif os.path.exists(defcfg):
        parse_config_file(defcfg)
    parse_command_line()  # override config file
    args = []
    for a in sys.argv[1:]:
        if a.startswith('--'):
            continue
        args.append(a)
    if len(args) < 1:
        print('Usage: {} <files...>'.format(sys.argv[0]))
        print_help()
        sys.exit(1)
    session = orm.make_session(options.database)()
    fi = slickbird.FileImporter(session, options.home)
    for f in args:
        r, status = fi.file_import(f)
        _log().info('{}: {}'.format(f, status))


if __name__ == "__main__":
    main()
