#!/usr/bin/env python
import os
import subprocess

from setuptools import setup
from setuptools.command.install import install

from distutils.sysconfig import get_python_lib

class alin_install(install):
	def run(self):
		install.run(self)

        # This portion of the code has not the expected result. The environment variable created is not kept for always.
        # it is just created on the python sessions where this is lanched.
        # TODO: imporve this in the future.
		py_folder = get_python_lib()
		alin_folder = py_folder+"/alin"
			
		res = os.environ.get('ALINPATH', 'Not Set')
		if res == 'Not Set':

			
			os.environ['ALINPATH'] = alin_folder
			
			# Generate environment profile for ALINPAT
			profile_folder = '/etc/profile.d/'
			profile_name = "alin.sh"
			with open(profile_folder+profile_name,"w") as f:
				f.write("export ALINPATH="+alin_folder)
			
			subprocess.call(profile_name, shell=True)
			
		# Generate documentation
		if os.path.isfile("alin_docconfig"):
			os.system("doxygen alin_docconfig")
			
			# Move generated doc folder to its porper location together witht the python module
			os.system("cp -rf doc/man/man10 /usr/share/man/")
			os.system("mandb")
			
			cmd = "cp -rf doc/ "+alin_folder+"/doc"
			os.system(cmd)
			
		print "\nInstallation completed!!!\n\n*** PLEASE restart session to apply changes ***\n"


def main():
	uname_folder = os.uname()[2]
	system_folder = '/lib/modules/'+uname_folder+'/extra'
	
	setup(name='AlIn',
			version='1.2',
			description='Alba Instrument',
			author='Manolo Broseta',
			author_email='mbroseta@cells.es',
			url='git@gitcomputing.cells.es:electronics/em2.git',
			cmdclass={'install': alin_install},
			packages=['alin', 'alin.tools','alin.tools.panel','alin.tools.telnet'],
			scripts = ['scripts/alin',
						'scripts/alinecho',
						'scripts/alingen',
						'scripts/alinpanel',
						'scripts/alinpaneloff',
						'scripts/alinsave'
						],
			long_description=open('README.txt').read(),
			
			data_files=[('/lib/firmware/fmc', ['resources/binaries/spec-init.bin']),
						('/usr/lib/', ['resources/lib/libspec.so']),						
						(system_folder, ['resources/kernel/spec.ko',
										'resources/kernel/fmc.ko',
										'resources/kernel/fmc-chardev.ko',
										'resources/kernel/fmc-fakedev.ko',
										'resources/kernel/fmc-trivial.ko',
										'resources/kernel/fmc-write-eeprom.ko',
										'resources/kernel/wr-nic.ko'
										]),
						#('/usr/lib/alin', ['tools/alininfo.py','tools/alingen.py','tools/alinsave.py']),
						#('/usr/lib/alin/panel', ['tools/panel/image_res.py','tools/panel/panel.py','tools/panel/paneldrv.py','tools/panel/paneloff.py']),
						#('/usr/lib/alin/telnet', ['tools/telnet/echo_client.py','tools/telnet/echo_server.py'])
						]
			)
				
if __name__ == "__main__":
    main()  