#!/usr/bin/env python
"""
Role of this executable:
Determine where kalite is installed and which python to use. This can be
set in the system's env (useful for distribution).

Notes...
This script might be invoked on a system where 'python' means python3 so we try
to be smart and allow that to happen, in which case we spawn a new process with
python2. Also, we don't have data to support putting something like
'/usr/bin/python27' in the shebang.

Q&A
Q: Why is this not written in Bash?
A: Because Bash isn't cross-platform

Environment variables used:

- KALITE_DIR: The root directory of the installation
- KALITE_PYTHON: If you want kalite run with a diffent python than the one
  in your path
  All arguments are proxied for kalite, and all stderr and stdout is returned.


"""
import os
import sys
import subprocess
import warnings

from distutils import spawn


# Python 2+3 definition
try:
    input = raw_input  # @ReservedAssignment
except NameError:
    pass

# Ensure that PATH is set because distutils.find_executable fails on
# windows with no path set.
os.environ['PATH'] = os.environ.get("PATH", "")

# Yay! The path is set!
if 'KALITE_DIR' in os.environ:
    if not os.path.exists(os.environ['KALITE_DIR']):
        raise RuntimeError("KALITE_DIR environment var is invalid: {:s}".format(os.environ['KALITE_DIR']))


# TODO(benjaoming): Delegate responsibility to the .deb package
# This always evaluates to False on Windows, so no problem with the
# system-specific path
if os.name == "posix" and os.path.isfile("/etc/ka-lite/username"):
    username = open("/etc/ka-lite/username", "r").read()
    username = username.split("\n")[0] if username else None
    if username and username != os.environ["USER"]:
        default_home = os.environ.get("KALITE_HOME", os.path.expanduser("~/.kalite"))
        if not os.path.exists(default_home) or not os.listdir(default_home):
            sys.stderr.write((
                "You are not running kalite as the default user {0}. "
                "This is recommended unless you want to re-create the database "
                "and start storing new videos/exercises etc. for a different "
                "user account\n\n"
            ).format(username))
            sys.stderr.write((
                "To run the command as the default user, run this instead:\n\n"
                "    sudo su {user} -c {command}\n\n"
            ).format(user=username, command=" ".join(sys.argv)))
            cont = input("Do you wish to continue? [y/N] ")
            if not cont.lower() == "y":
                sys.exit(0)


python_executable = None

if 'KALITE_PYTHON' in os.environ:
    python_executable = os.environ['KALITE_PYTHON']
    if not spawn.find_executable(python_executable):
        raise RuntimeError("KALITE_PYTHON set to invalid python path")
else:
    # If we are invoked with python3, force executable to be python2
    if sys.version_info >= (3, 0):
        python_executable = 'python2'

        if not spawn.find_executable(python_executable):
            python_executable = 'python'
        # Set full path of executable - returns None if it's not found
        python_executable = spawn.find_executable(python_executable)
    
        # Check that the executable exists
        if not python_executable:
            python_executable = sys.executable
            warnings.warn("Could not determine Python in your path, defaulting to {0:s}".format(python_executable), RuntimeWarning)
    
# Arguments to proxy
args = sys.argv[1:]

# If we are told to use another executable, we do that...
if python_executable:
    env = {}
    env.update(os.environ.copy())

    # Open up a process and proxy both the process' stdout and stderr
    p = subprocess.Popen(
        [python_executable, "-m", "kalite"] + args,
        env=env,
    )
    
    try:
        p.communicate()
    except KeyboardInterrupt:
        # We are not going to show this un-interesting traceback!
        pass
    sys.exit(p.returncode)

# Otherwise, if we can stay in the current Python environment, that's also the
# best option....
else:
    
    from kalite import cli
    cli.main()
