#Copyright 2013 Barcelona Supercomputing Center (www.bsc.es)
#                                                                 
# Licensed under the Apache License, Version 2.0 (the "License"); 
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at                         
#                                                                 
#     http://www.apache.org/licenses/LICENSE-2.0                  
#                                                                 
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,  
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and     
# limitations under the License.                                          

#!/bin/sh

set -e

export PATH=$PATH:/usr/bin:/usr/x86_64-suse-linux/bin:

working_dir=`pwd`

function exittrap {
        rc=$?      
        if test x"$rc" != x"0" ; then
                echo "ERROR: Command exited with status" $rc"." 1>&2
                exit $rc                                            
        fi                                                          
}                                                                   

trap exittrap 0


# message functions
usage() {

        echo " "
        echo  Usage\: `basename $0` build \<component\> \<appname\> \<project_path\> \<resources_path\>
        echo  Usage\: `basename $0` copy   \<component\> \<appname\>
        echo  Usage\: `basename $0` clean \<component\> \<appname\>
        echo ""
        echo "  Available actions:"
        echo "    copy         Setup a compilation environment for the component for customization."
        echo "    build        Build the selected component ."
        echo "    clean        Remove generated binaries."
        echo ""
        echo "  Available components:"
        echo "    master       Build or copy the master part."
        echo "    worker       Build or copy the worker part."
        echo "    all          Build or copy the master and workers parts."
        echo ""
        echo "  <appname> Corresponds to the name of the application used for source files and IDL files."
        echo "  <projectpath> Corresponds to the path of the project description file."
        echo "  <resourcespath> Corresponds to the path of the resources description file."
        echo " "
        exit
}


error() {
        echo "An error occurred, please check the output."
        exit 1;                                           
}                                                   

# Generating autogen.sh script

generate_autogen_sh() {
worker=$1

/usr/bin/cat > autogen.sh << EOF

#!/bin/sh
set -e

export CC="gcc"
export CXX="g++"

/usr/bin/aclocal
/usr/bin/automake -a -c
/usr/bin/autoconf
EOF
if test x"$worker" != x"1" ; then
/usr/bin/cat >> autogen.sh << EOF
        if( test x\$4 != x"" ); then
                 ./configure --with-cs-prefix=$GS_HOME --with-prj-file=\$1 --with-res-file=\$2--with-master-dir=\$3
        else
                 ./configure --with-cs-prefix=$GS_HOME --with-prj-file=\$1 --with-res-file=\$2
        fi
EOF

else
/usr/bin/cat >> autogen.sh << EOF
        ./configure --with-cs-prefix=$GS_HOME
EOF
fi

/usr/bin/cat >> autogen.sh << EOF
EOF
        /usr/bin/chmod +x autogen.sh
}

# master functions

prepare_master_copy() {
        gsprefix=$1    
        appname=$2     

        if test -d master ; then      
                cd master             
           if test -e $2.cc ; then    
                                      
             if test -e $2.idl ; then 
                echo "All files needed found."
                                              
             else                             
                echo "File $2.idl not found." 
                exit                          
             fi                               

           else
             echo "File $2.cc not found."
             exit                        
           fi                            

        else
                echo "The master directory must exist when using copy action."
                exit                                                          
        fi                                                                    
}                                                                             

prepare_master_build() {
        gsprefix=$1     
        appname=$2      

        if test -d master ; then
                echo "The master directory already exists from a previous build. Removing."
                /usr/bin/rm -rf master                                                         
        fi                                                                                 

        /usr/bin/mkdir master
        /usr/bin/cp *.* master
        cd master 
		/usr/bin/rm $2-functions.cc                                                                                                

        /usr/bin/mkdir gsbuild
        cd gsbuild        

        ln -s -f ../*.c .
        ln -s -f ../*.cc .
        ln -s -f ../*.cpp .
        ln -s -f ../*.cxx .
        ln -s -f ../*.idl .
        ln -s -f ../*.h .  
        ln -s -f /home/cramonco/svn/compss/framework/trunk/builders/specs/deb/compss-c-binding/tmp/opt/COMPSs/Bindings/c/etc/gss-master-env.sh .
        ln -s -f /home/cramonco/svn/compss/framework/trunk/builders/specs/deb/compss-c-binding/tmp/opt/COMPSs/Bindings/c/etc/gss-master-env.csh .
}                                                  

copy_master_build_env() {
        gsprefix=$1      
        appname=$2       

        /usr/bin/cp /home/cramonco/svn/compss/framework/trunk/builders/specs/deb/compss-c-binding/tmp/opt/COMPSs/Bindings/c/share/compsuperscalar/build/c/master/Makefile.am Makefile.am.source
        /usr/bin/cat /home/cramonco/svn/compss/framework/trunk/builders/specs/deb/compss-c-binding/tmp/opt/COMPSs/Bindings/c/share/compsuperscalar/build/c/master/configure.in | /usr/bin/sed -e s/PACKAGE/"$appname"/g | /usr/bin/sed -e s/CLASSADS_SUPPORT/"@with_classads@"/g | /usr/bin/sed -e s/execution_env/"GRID"/g > configure.in                                                                                             
        /usr/bin/cat Makefile.am.source | /usr/bin/sed 's/PACKAGE/'$appname'/g' > Makefile.am


		#Machine Arch Calculation

    	#machine_arch=$(uname -p | /usr/bin/cut -c 1);

    	#if [ $machine_arch == 'i' ]; then
        #    arch="i386"
        #    subfolder="client"
        #fi
        
        #if [ $machine_arch == 'x' ]; then
        #    arch="amd64"
        #    subfolder="server"
        #fi
                                                                            
        #/usr/bin/cp Makefile.am Makefile.am.source
        #/usr/bin/cat Makefile.am.source | /usr/bin/sed s/ARCH/$arch/g | /usr/bin/sed s/SUBFLDR/$subfolder/g > Makefile.am
                                                                            
        generate_autogen_sh 0                                                                                                                                
        /usr/bin/touch NEWS README AUTHORS ChangeLog                                                                                                                
        echo "" > empty.cc                                                                                                                                   

        path_to_dist="/home/cramonco/svn/compss/framework/trunk/builders/specs/deb/compss-c-binding/tmp/opt/COMPSs/Bindings/c";
        path_to_dist=$(echo $path_to_dist | /usr/bin/sed 's/\//\\\//g')
        copy_comm="@SCP@";                             
        copy_comm=$(echo $copy_comm | /usr/bin/sed 's/\//\\\//g');     
        copy_comm_flags="-q -o StrictHostKeyChecking=no";                 
        copy_comm_flags=$(echo $copy_comm_flags | /usr/bin/sed 's/\//\\\//g');
}                                                                                                                     

build_master() {
        gsprefix=$1
        appname=$2
        project_file_path=$3
        resources_file_path=$4
        if [ -z "$project_file_path" ]
        then
                project_file_path="${working_dir}/project.xml"
        fi
        if [ -z "$resources_file_path" ]
        then
                resources_file_path="${working_dir}/resources.xml"
        fi
        echo "Running Autogen with: "
        echo "Project File: $project_file_path "
        echo "Resources File: $resources_file_path "
        ./autogen.sh $project_file_path $resources_file_path       
        /usr/bin/make                
}                   

finish_master_build() {
	gsprefix=$1    
        appname=$2     
        /usr/bin/cp -f $appname ..
        cd ..            
		#/usr/bin/cp gsbuild/*-constraints .
        
        #/usr/bin/rm -rf gsbuild 
        #/usr/bin/rm -f *.c
        #/usr/bin/rm -f *.cc
        #/usr/bin/rm -f *.cpp
        #/usr/bin/rm -f *.cxx
        #/usr/bin/rm -f *.h  
        #/usr/bin/rm -f *.xml
               
        #/usr/bin/rm -rf gsbuild/*
        #/usr/bin/mv *-constraints gsbuild
        cd ..          
}                                  

clean_master() {         
        if test -d master ; then
           cd master            
           /usr/bin/rm -f $appname gss-master-env.sh gss-master-env.csh
           cd ..                                                   
        else                                                       
           echo "The master directory must exist when using clean action."
           exit                                                           
        fi                           
}                                                                    


# worker functions
prepare_worker_copy() {
        gsprefix=$1    
        appname=$2     

        if test -d worker ; then
                cd worker       
           if test -e $2-functions.cc ; then
                                           
             if test -e $2.idl ; then      
                echo "All files needed found."

             else
                echo "File $2.idl not found."
                exit                         
             fi                              

           else
             echo "File $2-functions.cc not found."
             exit                                 
           fi                                     

        else
                echo "The worker directory must exist when using copy action."
                exit                                                          
        fi                                                                    
}                                                   

prepare_worker_build() {
	gsprefix=$1     
        appname=$2      


        if test -d worker ; then
                echo "The worker directory already exists from a previous build. Removing."
                /usr/bin/rm -rf worker                                                         
        fi                                                                                 

        /usr/bin/mkdir worker
        /usr/bin/cp *.* worker
        cd worker
		/usr/bin/rm $2.cc                           
        /usr/bin/mkdir files                    
                                                                              
        /usr/bin/mkdir gsbuild
        cd gsbuild        

        ln -s -f ../*.c .
        ln -s -f ../*.cc .
        ln -s -f ../*.cpp .
        ln -s -f ../*.cxx .
        ln -s -f ../*.idl .
        ln -s -f ../*.h .    
}                                           

copy_worker_build_env() {
        gsprefix=$1      
        appname=$2       

        /usr/bin/cp /home/cramonco/svn/compss/framework/trunk/builders/specs/deb/compss-c-binding/tmp/opt/COMPSs/Bindings/c/share/compsuperscalar/build/c/worker/Makefile.am Makefile.am.source
        /usr/bin/cat /home/cramonco/svn/compss/framework/trunk/builders/specs/deb/compss-c-binding/tmp/opt/COMPSs/Bindings/c/share/compsuperscalar/build/c/worker/configure.in | /usr/bin/sed -e s/PACKAGE/"$appname"/g | /usr/bin/sed -e s/execution_env/"GRID"/g > configure.in                                                                                                                                               
        /usr/bin/cat Makefile.am.source | /usr/bin/sed 's/PACKAGE/'$appname'/g'| /usr/bin/sed -e s/execution_env/"GRID"/g > Makefile.am                             
        generate_autogen_sh 1                                                                                                                                
        /usr/bin/touch NEWS README AUTHORS ChangeLog                                                                                                                

        path_to_dist="/home/cramonco/svn/compss/framework/trunk/builders/specs/deb/compss-c-binding/tmp/opt/COMPSs/Bindings/c";
        path_to_dist=$(echo $path_to_dist | /usr/bin/sed 's/\//\\\//g')
        copy_comm="@SCP@";                             
        copy_comm=$(echo $copy_comm | /usr/bin/sed 's/\//\\\//g');     
        copy_comm_flags="-q -o StrictHostKeyChecking=no";                 
        copy_comm_flags=$(echo $copy_comm_flags | /usr/bin/sed 's/\//\\\//g');

        ln -s -f ${appname}-worker worker_c
        
	#Generating worker_c.sh script
    #    echo '#!/bin/sh' >> worker_c.sh
    #    echo >> worker_c.sh
    #    echo 'export LD_LIBRARY_PATH=/home/cramonco/svn/compss/framework/trunk/builders/specs/deb/compss-c-binding/tmp/opt/COMPSs/Bindings/c/lib:/home/cramonco/svn/compss/framework/trunk/builders/specs/deb/compss-c-binding/tmp/opt/COMPSs/Bindings/c/../bindings-common/lib:$LD_LIBRARY_PATH' >> worker_c.sh
	#	 echo 'app_dir=$1' >> worker_c.sh                  
    #    echo "exec \$app_dir/worker_c \$@" >> worker_c.sh
    #    /usr/bin/chmod +x worker_c.sh   
    #    /usr/bin/cp -f worker_c.sh /home/cramonco/svn/compss/framework/trunk/builders/specs/deb/compss-c-binding/tmp/opt/COMPSs/Bindings/c/../../scripts/system/worker_c.sh 

	#Generating clean script
    #   echo '#!/bin/sh' >> clean.sh
    #    echo >> clean.sh
    #    echo 'rm -rf $1/*.IT' >> clean.sh
    #    /usr/bin/chmod +x clean.sh

}                                           

build_worker() {
	gsprefix=$1
        appname=$2 
        echo "Running Autogen... "
        ./autogen.sh              
        /usr/bin/make                
}                   

finish_worker_build() {
        gsprefix=$1    
        appname=$2     
        /usr/bin/cp -f $appname-worker ..
        #/usr/bin/cp -f worker_c.sh ..
		#/usr/bin/cp -f clean.sh ..		
		

        cd ..
        #/usr/bin/rm -rf gsbuild
        #/usr/bin/rm -f *.c
        #/usr/bin/rm -f *.cc
        #/usr/bin/rm -f *.cpp
        #/usr/bin/rm -f *.cxx
        #/usr/bin/rm -f *.h  
        #/usr/bin/rm -f *.xml

        ln -s -f ${appname}-worker worker_c
}                                           

clean_worker() {
 
        if test -d worker ; then
           cd worker            
           /usr/bin/rm -f ${appname}-worker worker_c clean.sh 
           cd ..                                                      
        else                                                          
           echo "The worker directory must exist when using clean action."
           exit                                                           
        fi                                   
}    
                                                          
# main code
if test $# != 3 ; then
   if test $# != 5; then
        usage           
   fi                   
fi                        

action=$1
component=$2
appname=$3
project_file_path=$4
resources_file_path=$5

if test x"$GS_LOCATION" != x ; then
        echo "Using environment variable GS_LOCATION."
        gsprefix=$GS_LOCATION                         
else                                                  
        gsprefix=/home/cramonco/svn/compss/framework/trunk/builders/specs/deb/compss-c-binding/tmp/opt/COMPSs/Bindings/c                             
fi                                                    


case $action in
        copy)  
                case $component in
                        master)   
                                echo "Preparing master build environment..."
                                prepare_master_copy $gsprefix $appname      
                                copy_master_build_env $gsprefix $appname    
                                ;;                                          
                        worker)                                             
                                echo "Preparing worker build environment..."
                                prepare_worker_copy $gsprefix $appname      
                                copy_worker_build_env $gsprefix $appname    
                                ;;                                          
                        all)                                                
                                echo "Preparing master and worker build environment:"
                                echo " "                                             

                                echo "Preparing master build environment..."
                                prepare_master_copy $gsprefix $appname      
                                copy_master_build_env $gsprefix $appname    
                                cd ..                                       

                                echo " "
                                echo "Preparing worker build environment..."
                                prepare_worker_copy $gsprefix $appname      
                                copy_worker_build_env $gsprefix $appname    
                                ;;                                    
                        *)                                            
                                usage                                 
                                ;;                                    
                esac                                                  
                ;;                                                    
        build)                                                        
                case $component in                                    
                        master)                                       
                                echo "Building master"                
                                prepare_master_build $gsprefix $appname
                                copy_master_build_env $gsprefix $appname
                                build_master $gsprefix $appname $project_file_path $resources_file_path
                                finish_master_build $gsprefix $appname                                 
                                ;;                                                                     
                        worker)                                                                        
                                echo "Building worker"                                                 
                                prepare_worker_build $gsprefix $appname                                
                                copy_worker_build_env $gsprefix $appname                               
                                build_worker $gsprefix $appname
                                finish_worker_build $gsprefix $appname
                                ;;
                        all)
                                echo "Building all:"
                                echo " "
                                echo "Building Master..."

                                prepare_master_build $gsprefix $appname
                                copy_master_build_env $gsprefix $appname
                                build_master $gsprefix $appname $project_file_path $resources_file_path
                                finish_master_build $gsprefix $appname

                                echo " "
                                echo "Building Worker..."

                                prepare_worker_build $gsprefix $appname
                                copy_worker_build_env $gsprefix $appname
                                build_worker $gsprefix $appname
                                finish_worker_build $gsprefix $appname
                                ;;
                        *)
                                usage
                                ;;
                esac
                ;;
        clean)
                case $component in
                        master)
                                echo "Cleaning master"
                                clean_master
                                ;;
                        worker)
                                echo "Cleaning worker"
                                clean_worker
                                ;;
                        all)
                                echo "Cleaning master and worker"
                                clean_master
                                clean_worker
                                ;;
                        *)
                                usage
                                ;;
                esac
                ;;
        *)
                usage
                ;;
esac

echo "Command succesful."

