#!/usr/bin/env python -u

"""This is the start script."""

import logging
import os
import sys
from os import path

import requests
from ansible.utils.display import Display
from prudentia import __version__ as v


def set_terminal_size():
    """Sets the environment variable COLUMNS using the number of columns in the terminal."""
    if sys.stdin.isatty():
        rows, columns = os.popen('stty size', 'r').read().split()
        os.environ['COLUMNS'] = columns


def init_user_dir():
    """Initializes the Prudentia user directory"""
    os.environ['PRUDENTIA_USER_DIR'] = user_dir = path.join(path.expanduser('~'), 'prudentia')
    if not path.exists(user_dir):
        os.makedirs(user_dir)
    return user_dir


def init_logging(user_dir):
    """Initializes the logging using the cli.log located inside the Prudentia user directory."""
    os.environ['PRUDENTIA_LOG'] = log_file = path.join(user_dir, 'cli.log')
    os.environ['ANSIBLE_DEBUG'] = 'False'
    logging.basicConfig(
        filename=log_file,
        format='%(asctime)s.%(msecs).03d [%(name)s] %(levelname)s: %(message)s',
        datefmt='%d-%m-%Y %H:%M:%S',
        level=logging.INFO
    )


def init_readline(user_dir):
    """Allows the use of tab completion when Prudentia is used as interactive CLI."""
    import readline
    import atexit

    if 'libedit' in readline.__doc__:
        readline.parse_and_bind("bind ^I rl_complete")
    else:
        readline.parse_and_bind("tab: complete")

    history_path = path.join(user_dir, 'history')

    def _save_history(p=history_path):
        """Makes sure we can save commands history across sessions."""
        import readline
        readline.write_history_file(p)

    try:
        readline.read_history_file(history_path)
    except:
        pass

    atexit.register(_save_history)


def check_latest():
    """Checks if Prudentia is up to date"""
    url = "https://pypi.python.org/pypi/prudentia/json"
    try:
        pkg_info = requests.get(url, timeout=0.5).json()
        last = pkg_info['info']['version']
        if v != last:
            print '\nNOTICE: Versions mismatch'
            print '  the latest release is {0}, currently running {1}'.format(last, v)
            print '  consider upgrading Prudentia (e.g. $ pip install -U prudentia)\n'
    except:
        pass


if __name__ == "__main__":
    set_terminal_size()
    ud = init_user_dir()
    init_logging(ud)
    init_readline(ud)
    check_latest()

    # Ansible expects to reuse the display only if it is available under __main__
    display = Display()

    from prudentia import cli

    exit_error = 1
    args = cli.parse()
    try:
        exit_error = 0 if cli.run(args) else 1
    except Exception, e:
        logging.exception('Error during run.')
        print '\nError during run: %s\n' % e

    sys.exit(exit_error)
