#! /bin/ksh
#*******************************************************************************
# E.S.O. - VLT project
#
# "@(#) $Id: buildTcltk,v 1.23 2012/04/17 11:55:54 jschwarz Exp $"
#
# who       when        what
# --------  ----------  ----------------------------------------------
# eallaert  2007-09-03  first version for ACS 7.0, derived from VLTSW
# eallaert  2008-08-28  modified for ACS 8.0 (product updates)
# eallaert  2011-06-03  modified for ACS 10.0 (compilation fix in snack)
#
#************************************************************************
#   NAME
#   buildTcltk
#
#   SYNOPSIS
#   buildTcltk [-v]
# 
#   DESCRIPTION
#   Compiles and install the Tcl/Tk packages needed for ALMA Common Software 
#
#    - tcl/tk     8.4.19
#    - [incr Tcl] 3.4 2008-08-06
#    - iwidgets   4.0.2 2008-08-20
#    - tclX       8.4 2008-06-29
#    - BLT        2.4z
#    - msqltcl    1.99
#    - tkimg      1.3
#    - Tktable    2.9 
#    - snack      2.2.10           
#    - tkman      2.2
#    - rman       3.1
#    - tcllib     1.10
#    - tklib      0.4.1 2008-08-19
#    - expect     5.43 2006-03-01  
#    - tclCheck   1.1.10
#    - tkcon      2.4
#
#   Target installation directory is specified by the enviroment
#   variable $TCLTK_ROOT (usually $ALMASW_INSTDIR/tcltk).  If undefined,
#   /usr/local is used instead.
#
#   Option -d[ebug] allows to run the shell in verbose mode, while option 
#   -m[sql] includes the generation of the msql C-lib, the msqltcl Tcl-extension
#   and the generation of msql directories/files under $ACSDATA.
#
#   FILES
#   input files: are taken from ../tcltk.
#   
#   ENVIRONMENT
#
#   RETURN VALUES
#
#   CAUTIONS
#   Tkman assumes that groff is already installed. If tkman does
#   not start, modify "man(print)" in $HOME/.tkman.
#
#   EXAMPLES
#
#   SEE ALSO
#
#   BUGS     
#   Does not stop in case of compilation errors.
#------------------------------------------------------------------------
#
#
# Remark that the Tcl/Tk source directory should be a sibbling of
# the directory containing this file, whereby this subdir name is
# derived from this file's name (i.e. it is the part coming after
# the dash).
#
# The following variable may need to be edited here in order to have
# proper installation:
#    - PREFIX : dirpath where the lib/ bin/ man/ files must be installed
#               (this directory and necessary subdirs will be created if
#               they do not yet exist).
#    - TCL_MEM_DEBUG: set to CFGLAGS=-DTCL_MEM_DEBUG if the Tcl memory 
#               command is needed
# EAL 20040719
#
#************ PLEASE EDIT vvvvvvvv ACCORDING TO YOUR NEEDS *************
###PREFIX=$ALMASW_INSTDIR/tcltk
###TCLTK_ROOT=$ALMASW_INSTDIR/tcltk
##PREFIX=$TCLTK_ROOT
##TCL_MEM_DEBUG="CFGLAGS=-DTCL_MEM_DEBUG"
#************ PLEASE EDIT ^^^^^^^^ ACCORDING TO YOUR NEEDS *************

##########################################################################################
# Function definitions used later in this script.
##########################################################################################
# definition of a function to print the usage statement for this script
printUsageAndExit ()
{
    echo ""
    echo "Usage: $0 [-d] [-h] [-m]";
    echo "Options: "
    echo "   -d | --debug: echo all commands as they are executed to stdout."
    echo "   -h | --help: print this usage message and exit."
    echo "   -m | --msql: include the msql stuff (typically in for an environment"
    echo "          where VxWorks hosts are managed via vcc/acc"
    echo ""
    exit $1;
}

##########################################################################################
# Script logic starts here...                                                            #
##########################################################################################
MY_NAME=`basename $0`

#
# These will contain the command line arguments and/or options
#
HELP=
DEBUG=
MSQL=

#
# These options can be recognized (longopts comma-separated. Colon means 1 argument is required)
#
LONGOPTS=help,debug,msql
SHORTOPTS=h,d,m
#
# Run getopt (posixly_correct needed). We run twice:
# First run is simply to check the commandline for correctness.
# Second run is does the real work and sets execution flags for this script,
# as appropriate.
export POSIXLY_CORRECT=1

getopt -n $MY_NAME -a -l $LONGOPTS $SHORTOPTS "$@" > /dev/null
if [ $? -ne 0 ] 
    then 
    printUsageAndExit 1;
fi

set -- `getopt -u -a -l $LONGOPTS $SHORTOPTS "$@"`

# Some programs behave differently if POSIXLY_CORRECT is set. In particular
# the configure/build of TclX and Itcl may fail ...
unset POSIXLY_CORRECT

#
# Iterate over getopt's output and set variables accordingly
#
while :
  do
  case "$1" in
      -h|--help)       HELP=true ;;
      -d|--debug)      DEBUG=true ;;
      -m|--msql)       MSQL=true;;
      --) break ;;
  esac
  shift
done
shift

if [ "$HELP" ] ; 
then
    printUsageAndExit 0
fi

# first, verify that the script was invoked without any command-line arguments 
if [ $# -ne 0 ] ;
then 
    printUsageAndExit 1
fi

if [ "$DEBUG" ]
then
    set -x
fi

LOG=buildTcltk.log
CWD=`pwd`
#
exec > $LOG 2>&1

date

#
# print header
#
TITLE="     Installing TCL/TK and related tools  "
BUILD_NAME="Tcl/Tk"
. ./standardPrologue
# The standardPrologue re-defines the echo function, whereby it disables
# the use of escape-sequences under Linux - I wonder why.

TCLTK=${INSTALL_ROOT}/PRODUCTS/tcltk
cd ${INSTALL_ROOT}/PRODUCTS/

if [ -d tcltk ]
then
    echo "$TCLTK already existing; I'll first remove it"
    rm -rf $TCLTK
fi
if ! [ -f tcltk.tar.gz ]
then
    echo "Tcl/Tk tar-file (tcltk.tar.gz) missing"
    exit 1
else
    tar xzf tcltk.tar.gz
fi
cd $CWD

#
# get current operating system
#
build_OS=`uname -s`
build_OSV=`uname -r`

if [ ${build_OS} = "Linux" ]
then
     distro=`cat /etc/redhat-release | awk '{ print $1 $2 }'`
     if [ "X${distro}" = "XRedHat" ] ; then
          build_OSV=${distro}`cat /etc/redhat-release | awk '{ print $3 $7 }'`
     elif [ "X${distro}" = "XScientificLinux" ] ; then
          build_OSV=${distro}`cat /etc/redhat-release | awk '{ print $(NF-1) }'`
     elif [ "X${distro}" = "XFedoraCore" ] ; then
          build_OSV=${distro}`cat /etc/redhat-release | awk '{ print $4 }'`
     fi   
fi

echo $SEPARATOR
echo " Installing on $build_OS version $build_OSV"

if [     ${build_OS}-${build_OSV} != "Linux-RedHatEnterprise4"    \
     -a  ${build_OS}-${build_OSV} != "Linux-RedHatEnterprise5.2"  \
     -a  ${build_OS}-${build_OSV} != "Linux-RedHatEnterprise5.3"  \
     -a  ${build_OS}-${build_OSV} != "Linux-ScientificLinux6.2"  \
     -a  ${build_OS}-${build_OSV} != "Linux-FedoraCore6"          \
   ]
then
    echo ""
    echo "        WARNING: this procedure has not been tested on this system!"
    echo ""
fi

echo "--- Check current environment and prepare installation"
#-------------------
# check that ACSDATA is defined as directory (needed by msql)
#
if [ "$MSQL" ]
then
    echo "check ACSDATA . . ."
    if [ "X$ACSDATA" = "X" ]
	then	
	echo "$ACSDATA not defined, cannot continue."
	exit 1
    fi
    
    DIR_LIST="
         ENVIRONMENTS      \
         config            \
         tmp               \
         msql              \
         msql/.tmp         \
         msql/msqldb       \
         msql/msqldb/.tmp  \
        "

    if [ ! -d $ACSDATA ]
	then
	if mkdir $ACSDATA
	    then
	    echo "   CREATED >>> |---$ACSDATA "
	else
	    echo ""
	    echo "ERROR: cannot create the starting directory >>$ACSDATA<<"
	    echo "          Please fix the problem and try again."
	    echo ""
	    exit 1
	fi
    else
	echo "               |---$ACSDATA "
    fi
    #
    # if not already there, create all the needed subdirectories
    for dir in $DIR_LIST
      do
      if [ ! -d $ACSDATA/$dir ]
	  then
	  mkdir $ACSDATA/$dir
	  chmod g+w $ACSDATA/$dir
	  echo "   CREATED >>>     |---$dir "
      else
	  echo "                   |---$dir "
      fi
    done
    chmod -R g+w $ACSDATA
    echo " . . . ok"
fi

#-------------------
# check that all needed files are there
#
FILE_LIST="
	 tclCheck-1.1.13.tar.gz    \
	 tcltk-ACS10.0.tar.gz       \
	 tkcon-2.4.tar.gz
	 "
if [ "$MSQL" ]
    then 
    FILE_LIST="
        $FILE_LIST \
	msql2.tar.gz
	"
fi

for file in $FILE_LIST
do
    if [ ! -f ${TCLTK}/$file ]
    then
    	echo "$file missing - should be contained in ${INSTALL_ROOT}/PRODUCTS/tcltk.tar.gz"
	exit 1
    fi
done

#
# setup and check target directory
#
if [ "$TCLTK_ROOT" = "" ]
then
    TCLTK_ROOT=/usr/local
fi

if [ ! -d $TCLTK_ROOT ]
then
     mkdir -p $TCLTK_ROOT
     RET=$?
     if [ $RET -ne 0 ]
     then
        echo "Failed to create $TCLTK_ROOT, cannot continue..."
        exit 1  
     fi
fi

PREFIX=$TCLTK_ROOT
export PREFIX
echo "target directory set to: $PREFIX . . . \c"

if [ ! -d $PREFIX ]
then
    echo "but that is not a directory, cannot continue."
    exit 1
fi

if [ ! -w $PREFIX ]
then
    echo "but that is not a writable directory, cannot continue."
    exit 1
fi
echo " . . . ok"


#
# Use GNU c compiler
#
CC=gcc
export CC


#
# create a temporary directory used to expand the tar files and 
# to compile
#
if [ "$build_OS" = "$CYGWIN_VER" ]; then
   SRC="$TCLTK/$build_OS"
else
   SRC="$TCLTK/$build_OS-$build_OSV"
fi
echo "set temporary build directory: $SRC . . . \c"
if [ -d $SRC ]
then
    echo "removing current content . . . \c"
    rm -rf $SRC
fi
mkdir $SRC
# Make sure SRC is an absolute path
cwd=`pwd`
cd $SRC
SRC=`pwd`
cd $cwd
echo "done"

#
# get current content of the target directory
#
cwd=`pwd`
bFile=$SRC/before_buildTcltk
aFile=$SRC/after_buildTcltk
rm -f $bfile $aFile
cd $PREFIX
find . -print > $bFile
cd $cwd

#
# when target dir is not /usr/local, delete the current content
#
if [ "X$PREFIX" != "X/usr/local" ]
then	
    echo "remove ${PREFIX} . . .\c"
    rm -rf $PREFIX
    mkdir -p $PREFIX/bin $PREFIX/lib $PREFIX/include $PREFIX/man/man1 $PREFIX/man/man3 $PREFIX/man/mann $PREFIX/doc
    echo " . . . done"
fi

#######################################################################
#
# 1. msql   
#
#    needed to implement the VCC/ACC database. 
#    The msql static library is linked by seqSh/seqWish (as there is no
#    shared lib available for dynamic loading)
#    The ad hoc installation procedure created the database in ACSDATA and the
#    binaries in the target directory
#
if [ "$MSQL" ]
then
    echo $SEPARATOR
    echo "msql: untarring . . . "
    cd $SRC
    gunzip -c $TCLTK/msql2.tar.gz | tar xf -
    cd msql-2.0.11/targets/$build_OS
    ./setup
    make install
    cp ../../msql.acl $TCLTK_ROOT/include
    cd $TCLTK_ROOT
    rm -fr README README.sco makegen misc www msql.acl.sample
    cd bin
    rm -f msqld msqlrelshow
    ln -s msql2d msqld
    ln -s relshow msqlrelshow
fi

#*********************************************
#
#  2.
#      product    current version
#      ======     ===============
#    - tcl/tk     8.4.19
#    - [incr Tcl] 3.4 2008-08-06
#    - iwidgets   4.0.2 2008-08-20
#    - tclX       8.4 2008-06-29
#    - BLT        2.4z
#    - msqltcl    1.99
#    - tkimg      1.3
#    - Tktable    2.9 
#    - snack      2.2.10           
#    - tkman      2.2
#    - rman       3.1
#    - tcllib     1.10
#    - tklib      0.4.1 2008-08-19
#    - expect     5.43 2006-03-01  
#

echo $SEPARATOR
echo "tcltk: untarring . . . "
cd $SRC
gunzip -c $TCLTK/tcltk-ACS10.0.tar.gz | tar xf -
if [ "${build_OS}" = "$CYGWIN_VER" ]; then
  patch $SRC/tcl8.4.19/unix/tcl.m4 < ${INSTALL_ROOT}/PRODUCTS/tcl.m4.patch
  patch $SRC/tcl8.4.19/generic/tclEnv.c < ${INSTALL_ROOT}/PRODUCTS/tcl.putenv.patch
  patch $SRC/tk8.4.19/unix/tcl.m4 < ${INSTALL_ROOT}/PRODUCTS/tcl.m4.patch
  ln -s $SRC/tk8.4.19/unix/tkUnixDefault.h $SRC/tk8.4.19/unix/tkWinDefault.h
  patch $SRC/tclx-2008-06-29/tclconfig/tcl.m4 < ${INSTALL_ROOT}/PRODUCTS/tclx.m4.patch
  patch $SRC/tclx-2008-06-29/configure < ${INSTALL_ROOT}/PRODUCTS/tclx.configure.patch
fi

# Make first the static libraries for Tcl/Tk and [incr Tcl]
# then the shared version; this should come second, so tclConfig.sh 
# refers to the shared version, and the executables are the shared ones.
# Remark that configuring itcl fails if srcdir is not given explicitly with
# an absolute path; otherwise it uses ".", which messes up things.
for dir in tcl8.4.19/unix tk8.4.19/unix tclx-2008-06-29 itcl-2008-08-06 ; do \
    (cd ${dir} ; \
    if [ "${build_OS}" = "$CYGWIN_VER" ]; then \
      rm configure; \
      autoconf; \
    fi; \
    ./configure --prefix=$PREFIX --disable-shared --enable-gcc --srcdir=`pwd`; \
    make ; make -k install; \
    make distclean ; \
    ./configure --prefix=$PREFIX --enable-shared --enable-gcc --srcdir=`pwd`; \
    make; make -k install ) \
done;

# Link the default shell names to the version specific names
cd $PREFIX/lib
ln -s tclConfig.sh tcl8.4/tclConfig.sh
ln -s tkConfig.sh tk8.4/tkConfig.sh
cd $PREFIX/bin
rm -f tclsh wish
ln -s tclsh8.4   tclsh
ln -s wish8.4    wish

# Link the default library names to the versions under specific subdirs
SHLIB_EXT=`echo "puts [info sharedlibextension]"|${PREFIX}/bin/tclsh`
cd $PREFIX/lib
rm -f libtclx8.4${SHLIB_EXT} libtclx8.4.a
##ln -s `pwd`/tclx8.4/libtclx8.4${SHLIB_EXT} libtclx8.4${SHLIB_EXT}
##ln -s `pwd`/tclx8.4/libtclx8.4.a           libtclx8.4.a
ln -s tclx8.4/libtclx8.4${SHLIB_EXT} libtclx8.4${SHLIB_EXT}
ln -s tclx8.4/libtclx8.4.a           libtclx8.4.a

# Install the wrapper scripts for the pre-8.4 TclX shells (tcl, wishx)
cd $SRC
cp tcl $PREFIX/bin
cp wishx $PREFIX/bin
chmod +x $PREFIX/bin/tcl $PREFIX/bin/wishx

cd $SRC/iwidgets-2008-08-20
./configure --prefix=$PREFIX --enable-shared --with-itcl=$SRC/itcl-2008-08-06/
make -k install
cd $PREFIX/lib
rm -f iwidgets
ln -s iwidgets4.0.2 iwidgets

# The "configure" of BLT, MSQLTCL and IMG depend on an *installed* Tcl/Tk,
# so that is why they have to come after the "make install" of Tcl/Tk
cd $SRC/blt2.4z
./configure --prefix=$PREFIX --enable-shared
##./configure --prefix=$PREFIX --enable-shared --with-cflags="-O6 -DUSE_OLD_CANVAS"
make
make -k install
cd $PREFIX/lib
rm -f libBLT${SHLIB_EXT}
ln -s libBLT24${SHLIB_EXT} libBLT${SHLIB_EXT}

if [ "$MSQL" ]
then
    # This requires libmsql.a and msql.h (usually under $TCLTK_ROOT)
    cd $SRC/msqltcl-1.99
    ./configure --prefix=$PREFIX --enable-shared --with-msql-include=$PREFIX/include --with-msql-library=$PREFIX/lib
    make
    make -k install
fi

cd $SRC/tkimg1.3
# Include --srcdir: see SF bug report 682911 on tkimg
./configure --prefix=$PREFIX --enable-shared --disable-stubs --srcdir=`pwd`
make
make -k install

cd $SRC/Tktable2.9
./configure --prefix=$PREFIX --enable-shared 
make
make -k install

cd $SRC/snack2.2.10/unix
# include --libdir, as configure does not do a proper job, it seems.
./configure --prefix=$PREFIX --enable-shared --with-tcl=$SRC/tcl8.4.19/unix --with-tk=$SRC/tk8.4.19/unix --disable-stubs --libdir=$PREFIX/lib
make
make -k install

cd $SRC/rman-3.1
make
make -k install

cd $SRC/tkman-2.2
make 
make -k install

cd $SRC/tcllib-1.10
./configure --prefix=$PREFIX
make -k install

# tklib 2008-08-19 contains tablelist 4.8
cd $SRC/tklib-2008-08-19
./configure --prefix=$PREFIX
make -k install

# The "--with-tclinclude" is needed only if any of the components of 
# Tcl's version number contains more than 1 digit (due to a limitation
# in expect's configure script)
cd $SRC/expect-2006-03-01
# With the option "--enable-shared" only the shared lib gets built!
./configure --prefix=$PREFIX --enable-shared --with-tcl=$SRC/tcl8.4.19/unix --with-tk=$SRC/tk8.4.19/unix --with-tclinclude=$SRC/tcl8.4.19/generic --disable-threads
make 
make -k install

###########################################
# 3. tclCheck
# 
# no man page, only $PREFIX/bin/tclCheck has been installed
#
echo $SEPARATOR
echo "tclCheck: untarring . . . "
cd $SRC
gunzip -c $TCLTK/tclCheck-1.1.13.tar.gz | tar xf -
cd tclCheck-1.1.13

# 1. to avoid problem with 'getopt': comment the line 
#    extern int getopt(int, char**, char*);
# 2. replace  'install -s' by 'cp' in Makefile

cp tclCheck.c tclCheck.orig.c
rm -rf tclCheck.c
cat tclCheck.orig.c | grep -v 'int getopt' > tclCheck.c

make

cp Makefile Makefile.orig
rm -rf Makefile
cat Makefile.orig | sed s'/install -s/cp/' > Makefile
make install BIN=$PREFIX/bin

###########################################
# 4. tkcon
# 
#
echo $SEPARATOR
echo "tkcon: untarring . . . "
cd $SRC
gunzip -c $TCLTK/tkcon-2.4.tar.gz | tar xf -
cd tkcon-2.4
cp tkcon.tcl $PREFIX/bin/tkcon
chmod 755 $PREFIX/bin/tkcon
cp -R docs $PREFIX/doc/
mv $PREFIX/doc/docs $PREFIX/doc/tkcon

###############################################################
# 5. Fix to the msql.conf file to put the real path to the TCLTK_ROOT 
# and the ACSDATA directories (the msql deamon itself does not 
# understand environment variables)
if [ "$MSQL" ]
then
    cd $TCLTK_ROOT
    sed -e 's,Inst_Dir = [^\n]*,'"Inst_Dir = $TCLTK_ROOT,g" \
	-e 's,DB_Dir = [^\n]*,'"DB_Dir = $ACSDATA/msql/msqldb,g" \
	-e 's,mSQL_User = [^\n]*,'"mSQL_User = almamgr,g" \
	-e 's,Admin_User = [^\n]*,'"Admin_User = almamgr,g" \
	msql.conf > msql.conf.acs
    mv msql.conf.acs msql.conf
fi

###############################################################
# 7. VERIFICATION
#
echo $SEPARATOR
echo "\n                          VERIFICATION\n"

cd ${INSTALL_ROOT}/INSTALL
if [ "$MSQL" ]
then
    ./checkTcltk --msql
else 
    ./checkTcltk
fi
