#!/usr/bin/env python
# -*- coding: UTF-8 -*-


import os
import lib_raise_c as C
import lib_raise_d as D
import lib_raise_linker as Linker
import lib_raise_fs as FS
import lib_raise_find as Find
import lib_raise_users as Users
import lib_raise_process as Process

def clean():
	"""Removes any files and directories generated when building."""
	FS.remove_file('a.out', ignore_failure = True)
	FS.remove_binaries('raise_example')
	FS.remove_binaries('lib_regex')

def _configure():
	cc = C.get_default_compiler()
	cc.debug = True
	cc.optimize_level = 2
	cc.warnings_all = True
	cc.warnings_as_errors = True

	dc = D.get_default_compiler()
	dc.debug = True
	dc.optimize = True
	dc.warnings_all = True
	dc.warnings_as_errors = True

	Find.require_header_file('libpcre', 'ver.major == 8')
	Find.require_shared_library('libpcre', 'ver.major == 8')
	Find.require_static_library('libphobos2')

	return (cc, dc)

def test():
	"""Builds the program, and runs it."""
	# Setup
	Users.require_not_root()
	clean()
	cc, dc = _configure()

	# Build the C object file
	cc.build_object('lib_regex.o', ['lib_regex.c'])

	# Build the D program using the C object file
	# FIXME: It should automatically get the library path from the require above
	link = '-L-l:' + Find.get_shared_library('libpcre')
	dc.build_program('raise_example.exe', ['main.d', 'lib_regex.o', 'lib_regex.d'], [link])

	# Run the program
	D.run_print('./raise_example.exe')

def _remove():
	D.uninstall_program('raise_example.exe')
	C.uninstall_library('lib_regex.so')

def remove():
	"""Uninstalls the program."""
	# Setup
	Users.require_root()
	clean()
	cc, dc = _configure()

	# Remove the files
	_remove()

	Linker.ldconfig()

def install():
	"""Installs the program."""
	# Setup
	Users.require_root()
	clean()
	cc, dc = _configure()

	# Build as a normal user
	def actual_build():
		cc.build_object('lib_regex.o', ['lib_regex.c'])
		cc.build_shared_library('lib_regex.so', ['lib_regex.o'])
		dc.build_program('raise_example.exe', ['main.d', 'lib_regex.d'], ['-Llib_regex.so', '-L-lpcre'])
	Users.do_as_normal_user(actual_build)

	# Remove old install
	_remove()

	# Install
	D.install_program('raise_example.exe')
	C.install_library('lib_regex.so')

	Linker.ldconfig()


