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

import os
import lib_raise_terminal as Print
import lib_raise_find as Find
import lib_raise_users as Users
import lib_raise_d as D
import lib_raise_ar as AR
import lib_raise_fs as FS
import lib_raise_config as Config


def clean():
	"""Removes any files and directories generated when building."""
	FS.remove_file('lib_math.di', ignore_failure = True)
	FS.remove_binaries('lib_math')
	FS.remove_binaries('main')

def _configure():
	dc = D.d_compilers[Config.arg]
	dc.debug = True
	dc.optimize = True
	dc.warnings_all = True
	return dc

def setup_failure():
	# Empty the path and reset the D module so it finds no compilers
	os.environ['PATH'] = ''
	D.is_setup = False
	D.d_compilers = {}
	D.setup()

def build_object():
	clean()
	dc = _configure()

	dc.build_object('lib_math.o', ['lib_math.d'])
	dc.build_object('main.o', ['main.d'])
	dc.build_program('main.exe', ['main.o', 'lib_math.o'])

	D.run_print('./main.exe')

def build_program():
	clean()
	dc = _configure()

	dc.build_program('main.exe', ['main.d', 'lib_math.d'])

	D.run_print('./main.exe')

def build_static_library():
	clean()
	dc = _configure()

	dc.build_object('lib_math.o', ['lib_math.d'])
	dc.build_static_library('lib_math.a', ['lib_math.o'])
	dc.build_program('main.exe', ['main.d', 'lib_math.a'])

	D.run_print('./main.exe')

def build_interface():
	clean()
	dc = _configure()

	dc.build_interface('lib_math.d')

# Tests that require root
def install_and_uninstall_program():
	# Configure
	Users.require_root()
	clean()
	dc = _configure()

	# Build as a normal user
	def actual_build():
		FS.remove_binaries('raise_example')
		dc.build_program('raise_example.exe', ['main.d', 'lib_math.d'])
	Users.do_as_normal_user(actual_build)

	# Install
	D.uninstall_program('raise_example.exe')
	D.install_program('raise_example.exe')

	# Run
	D.run_print('raise_example.exe')

	# Remove
	D.uninstall_program('raise_example.exe')

def install_and_uninstall_static_library():
	# Configure
	Users.require_root()
	clean()
	dc = _configure()

	# Build as a normal user
	def actual_build():
		dc.build_object('lib_math.o', ['lib_math.d'])
		AR.build_static_library('lib_math.a', ['lib_math.o'])
		dc.build_program('raise_example.exe', ['main.d', 'lib_math.a'])
	Users.do_as_normal_user(actual_build)

	# Install
	D.uninstall_program('raise_example.exe')
	D.uninstall_library('lib_math.a')
	D.install_program('raise_example.exe')
	D.install_library('lib_math.a')

	# Run
	D.run_print('raise_example.exe')

	# Remove
	D.uninstall_program('raise_example.exe')
	D.uninstall_library('lib_math.a')

