#!/usr/bin/env python

import os
import signal
import sys
import traceback
import subprocess

ver = sys.version_info

if (ver[0] * 1000 + ver[1]) < 2007:
    print 'ERROR: Wrong Python version. Expected v2.7.x'
    sys.exit(1)

def sigint_handler(signal, frame):
    print '\nCommand aborted by user'
    sys.exit(signal)

signal.signal(signal.SIGINT, sigint_handler)

sys.path.append(os.path.abspath(
    os.path.join(os.path.realpath(__file__), '../../lib/python')))

from ovsdb_plugin.common import APP_ROOT
from ovsdb_plugin.common import JAVA_VERSION
from ovsdb_plugin import cli

try:
    os.chdir(APP_ROOT)

    try:
        java_version = subprocess.check_output(["java", "-version"], \
            stderr=subprocess.STDOUT)

        if JAVA_VERSION not in java_version:
            print 'ERROR: Wrong Java version. Expected ' \
                + JAVA_VERSION + '.x' + ' or higher'
            sys.exit(1)
    except OSError as os_error:
        print 'ERROR: Java not found. Please make sure Java ' \
            +  JAVA_VERSION + '.x' + ' or higher is installed.'
        sys.exit(1)

    sys.exit(cli.execute_user_input())
except Exception as e:
    from ovsdb_plugin.models.configuration import Configuration
    config = Configuration()

    if config.exists:
        base_logdir = config.logdir_path
    else:
        base_logdir = APP_ROOT

    path = os.path.abspath(os.path.join(base_logdir, 'cli.err'))

    print 'FATAL: An error occured while executing the command. ' \
          'The error message has been saved to {}'.format(path)

    with open(path, 'w') as the_file:
        the_file.write(traceback.format_exc())

    sys.exit(1)
