#!/usr/bin/python

# Set the location of the LightYears files here:
LIGHTYEARS_DIR = "/usr/share/games/lightyears" # (for Debian)

# Save games and configuration files are stored in the user's
# home directory.

import sys, os

def Check_Version():
    if ( sys.__dict__.get("version_info", None) ):
        (major, minor, micro, releaselevel, serial) = sys.version_info
    else:
        major = 1
        minor = 0

    if (( major < 3 ) or (( major == 3 ) and ( minor < 6 ))):
        sys.stderr.write("\n")
        sys.stderr.write("Python 3.6 or higher is required.\n")
        sys.stderr.write("You appear to be using version %d.%d\n" % (major, minor))
        sys.exit(1)

    pygame = "Please install the latest version with 'pip install pygame'\n"
    try:
        import pygame
    except:
        sys.stderr.write("\n")
        sys.stderr.write("Pygame does not appear to be installed.\n")
        sys.stderr.write(pygame)
        sys.exit(1)

    try:
        # The size of this field changed between
        # ver. 1.6 and ver. 1.7. Arrgh.
        [major, minor, micro] = list(pygame.version.vernum)[ :3 ]
    except:
        major = minor = micro = 0

    if (( major < 1 )
    or (( major == 1 ) and ( minor < 9 ))
    or (( major == 1 ) and ( minor == 9 ) and ( micro < 4 ))):
        sys.stderr.write("\n")
        sys.stderr.write("Pygame version 1.9.4 or higher is required.\n")
        sys.stderr.write(pygame)
        sys.exit(1)


class MissingFileError(Exception):
    pass


if __name__ == "__main__":
    # Path to data/code dir can be overridden by environment variable
    LIGHTYEARS_DIR = os.environ.get("LIGHTYEARS_DIR", LIGHTYEARS_DIR)

    # Path does not exist? Try current directory.
    if ((LIGHTYEARS_DIR == None)
    or (not os.path.isdir(LIGHTYEARS_DIR))
    or (not os.path.isfile(os.path.join(LIGHTYEARS_DIR, 
                            'code', '__init__.py')))):
        LIGHTYEARS_DIR = "."

    # Paths obtained
    if LIGHTYEARS_DIR != ".":
        LIGHTYEARS_DIR = os.path.abspath(LIGHTYEARS_DIR)
        sys.path.insert(0, LIGHTYEARS_DIR)
    else:
        LIGHTYEARS_DIR = os.path.abspath(LIGHTYEARS_DIR)

    data_dir = os.path.join(LIGHTYEARS_DIR, 'data')
    code_dir = os.path.join(LIGHTYEARS_DIR, 'lib20k')

    # Go
    if (os.path.isdir(code_dir)
    and os.path.isfile(os.path.join(code_dir, "__init__.py"))
    and os.path.isfile(os.path.join(code_dir, "main.py"))):
        Check_Version()
        from lib20k import Main, Events
        sys.exit(Main(data_dir=data_dir, args=sys.argv[1:], event=Events()))
    else:
        raise MissingFileError("Unable to find LightYears code in " + LIGHTYEARS_DIR)

    

