#!/usr/bin/env python
#
#  Copyright (C) 2015 IT4Innovations
#  Lumir Jasiok
#  lumir.jasiok@vsb.cz
#  http://www.it4i.cz
#
#
#

"""
EasyBuild support for building and installing Intel Trace Analyzer and Collector, implemented as an easyblock. 
@author: Lumir Jasiok (IT4Innovations)
"""

import os
import platform

from easybuild.easyblocks.generic.intelbase import IntelBase
from easybuild.tools.run import run_cmd

class EB_itac(IntelBase):
    """
    Support for installing Intel Trace Analyzer and Collector
    """

    def __init__(self, *args, **kwargs):
        """
        Custom variable initialization
        """
        IntelBase.__init__(self, *args, **kwargs)
        self.prefix_path = "itac_latest"

    def install_step(self):
        """Actual installation
        
        - create silent.cfg
        - run install.sh
        """
        
        machine = platform.machine()
        if machine == "i386":
            self.arch = "ia32"
        else:
            self.arch = "intel64"

        silent_cfg = """
ACCEPT_EULA=accept
CONTINUE_WITH_OPTIONAL_ERROR=yes
PSET_INSTALL_DIR=%s
CONTINUE_WITH_INSTALLDIR_OVERWRITE=yes
COMPONENTS=DEFAULTS
PSET_MODE=install
ACTIVATION_LICENSE_FILE=%s
ACTIVATION_TYPE=license_file
PHONEHOME_SEND_USAGE_DATA=no
SIGNING_ENABLED=yes
        """ % (self.installdir, self.license_file)
        build_dir = self.cfg['start_dir']
        silent_file = os.path.join(build_dir, 'silent.cfg')
        fd = open(silent_file, 'w')
        fd.write(silent_cfg)
        fd.close()

        os.chdir(build_dir)
        self.log.info("Build dir is %s" % (build_dir))
        cmd = "./install.sh -s silent.cfg --SHARED_INSTALL"
        run_cmd(cmd, log_all=True, simple=True)
        return True
    
    def make_module_req_guess(self):
        """
        A dictionary of possible directories to look for
        """
        guesses = super(EB_itac, self).make_module_req_guess()
        lib_path = '%s/%s/lib' % (self.prefix_path, self.arch)
        slib_path = '%s/%s/slib' % (self.prefix_path, self.arch)
        lib_arr = []
        lib_arr.append(lib_path)
        lib_arr.append(slib_path)


        guesses.update({
            'PATH': ['%s/bin' % self.prefix_path],
            'LD_LIBRARY_PATH': lib_arr,
            'LIBRARY_PATH': lib_arr,
            'VT_LIB_DIR': lib_arr,
            'VT_SLIB_DIR': ['%s/slib' % self.prefix_path],
            'CPATH': ['%s/include' % self.prefix_path],
            'INCLUDE': ['%s/include' % self.prefix_path],
            'MANPATH': ['%s/man' % self.prefix_path],
        })

        return guesses

    def sanity_check_step(self):
        """
        Custom sanity checks for ITAC
        """
        custom_paths = {
            'files': ["%s/bin/traceanalyzer" % self.prefix_path] +
                     ["%s/lib/%s" % (self.prefix_path, x) for x in ["libVT.a", "libVTdynamic.o", "libVTcs.a"]],
            'dirs': [],
        }

        IntelBase.sanity_check_step(self, custom_paths=custom_paths)