#!/usr/bin/env python
'''Create Makefile for tools installation'''

# Copyright (c) 2006 Qualcomm
# Miki Tebeka <mtebeka@qualcomm.com>

from sys import version_info

MIN_VERSION = 2.3
PREFIX = "/opt/p4vaddins"
ADDINS_TXT = "p4vaddins.txt"
ADDINS_TXT_NEW = "p4vaddins.xml"
MAKEFILE = '''
all:
\t@echo "Done! Now run 'make install'"

install:
\tinstall -d %(prefix)s
\tinstall %(sources)s %(prefix)s
'''

SOURCES = [
    "checkout-to.py",
    "label2change.py",
    "make-dev-branch.py",
    "p4v_common.py",
    "publish.py",
    "publishui.py",
    "quick-label.py",
    "safe-sync.py",
]

def assert_have_module(module, module_name):
    print "checking if you have %s installed..." % module_name,
    try:
        __import__(module)
        print " [OK]"
    except ImportError:
        print " [NO]"
        raise SystemExit("error: can't find %s" % module_name)

def create_from_template(filename, install_dir):
    text = open(filename + ".in").read()
    text = text.replace("_INSTALL_DIR_", install_dir)
    fo = open(filename, "wt")
    fo.write(text)
    fo.close()

# Check for good Python version
if float("%s.%s" % version_info[:2]) < MIN_VERSION:
    raise SystemExit("error: python version %0.1f or higher is required" % \
            MIN_VERSION)

from optparse import OptionParser
from os.path import isfile

parser = OptionParser("usage: %prog [options]")
parser.add_option("--prefix", help="install location [%s]" % PREFIX,
        dest="prefix", default=PREFIX)
parser.add_option("-m", help="output makefile name", dest="makefile",
        default="Makefile")
parser.add_option("--sources", help="print sources and exit", dest="sources",
        action="store_true", default=0)

opts, args = parser.parse_args()
if args:
    parser.error("wrong number of arguments") # Will exit

if opts.sources:
    print "\n".join(SOURCES)
    raise SystemExit

print "configuring for installation at %s" % opts.prefix

if isfile(opts.makefile):
    raise SystemExit("error: %s already exists" % opts.makefile)

assert_have_module("wx", "wxPython")
assert_have_module("p4", "P4Python")

for filename, version in ((ADDINS_TXT, "older than 2006.1"),
                        (ADDINS_TXT_NEW, "2006.1 or newer")):
    print "creating %s (for p4v %s)" % (filename, version)
    try:
        create_from_template(filename, opts.prefix)
    except IOError, e:
        error_message = "error: can't create %s (%s)" % (filename, e.strerror)
        raise SystemExit(error_message)

print "creating %s" % opts.makefile
fo = open(opts.makefile, "wt")
src = SOURCES + [ADDINS_TXT, ADDINS_TXT_NEW, "default.css", "README.html" ]
fo.write(MAKEFILE % { "prefix" : opts.prefix, "sources": " ".join(src)})
fo.close()