#!/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

VERSION = version.VERSION

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 version " + 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]
	if not process.returncode == 0:
		print (FAIL + "Can't find " + lib + ENDC)
		exit (1) 

def configure ():
	if not test_program_version ("valac", 0, 17, 3):
		print (FAIL + "Can't find a suitable vala compiler." + ENDC)
		exit (1)

	if not test_program_version ("doit", 0, 20, 0):		
		print (FAIL + "Doit is too old" + ENDC)
		exit (1)

	libs = [
			'cairo', 
			'gdk-pixbuf-2.0', 
			'gio-2.0', 
			'glib-2.0', 
			'gtk+-2.0',
			'libxml-2.0', 
			'webkit-1.0', 
			'libsoup-2.4'
			]

	for lib in libs:
		test_library_version (lib)

	v = subprocess.check_output ('mkdir -p build', shell=True)
	v = subprocess.check_output ('touch build/configured', shell=True)

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


parser = OptionParser()
parser.add_option("-p", "--prefix", dest="prefix", help="install prefix", metavar="PREFIX")

(options, args) = parser.parse_args()

if not options.prefix:
	options.prefix = "/usr"

configure ()
configfile.write_config (options.prefix)
