#!/usr/bin/python
import subprocess
import os
import sys
import time;
from optparse import OptionParser
from scripts import version
from scripts import configfile
import re
from scripts.run import run

HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'

def test_program_version (program, a, b, c):
	print ("Checking for %s version >= %s.%s.%s" % (program, a, b, c))
	process = subprocess.Popen (program + ' --version', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
	v = process.stdout.readline()
	process.communicate()[0]
	if not process.returncode == 0:
		print (FAIL + "Not found" + ENDC)
		exit (1)		
	print ("Found " + v)
	
	o = v.split (" ");
	for s in o:
		if re.search( r'[0-9]*\.', s):
			v = s
			break
			
	v = re.sub(r'[a-zA-Z\-].*', '0', v)
	version = [int(n) for n in v.split (".")]
	return [a,b,c] <= version	

def test_library_version (lib):
	print ("Looking for library: " + lib + "\t\t")
	process = subprocess.Popen ('pkg-config --modversion ' + lib, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
	process.communicate()[0]
	return process.returncode == 0

def configure ():	
	if not test_program_version ("valac", 0, 16, 0):
		print (FAIL + "valac is too old." + ENDC)
		exit (1)


	libs = [ 'glib-2.0' ]

	for lib in libs:
		if not test_library_version (lib):
			print (FAIL + "Can not find " + lib + ENDC)
			exit (1)

	run ('mkdir -p build')
	run ('touch build/configured')

	print ("");
	print (OKGREEN + "Done" + ENDC);


parser = OptionParser()
parser.add_option("-p", "--prefix", dest="prefix", help="Install prefix", metavar="PREFIX")
parser.add_option("-c", "--cc", dest="cc", help="C compiler", metavar="CC")

(options, args) = parser.parse_args()

if not options.prefix:
	if "bsd" in sys.platform:
		options.prefix = "${DESTDIR}${PREFIX}"
	else:
		options.prefix = "/usr"

if not options.cc:
	options.cc = "gcc"

configure ()
configfile.write_parameters (options.prefix, options.cc)	
