#!/bin/bash

##+----------------------------------------------------------------------------------+
##            Copyright(c) Microsoft Corp. 2015
##+----------------------------------------------------------------------------------+
## File         :   StartupScript.sh
##
## Description  :   Start-up script invoked by Azure guest agent when the custom-script
##                  extension is set for hydration-vm as part of recovery work-flow.
##
## History      :   1-6-2015 (Venu Sivanadham) - Created
##+----------------------------------------------------------------------------------+

#
# Binaries and command
#
export MKDIR=/bin/mkdir
export RM=/bin/rm
export COPY=/bin/cp
export SET_PERMS=/bin/chmod
export UNZIP_CMD=/usr/bin/unzip

#
# Other global variables
#
export LOGFILE=/usr/local/AzureRecovery/AzureRecoveryUtil.log
export WORK_DIR=/usr/local/AzureRecovery
export LINUX_GA_DIR=/usr/local/AzureRecovery/WALinuxAgentASR

export RECOVERY_TOOLS_ZIPFILE="AzureRecoveryTools.zip"
export LINUX_GA_TOOLS_ZIPFILE="master.zip"

export HOSTINFO_PREFIX="hostinfo"
export REC_INFO_PREFIX="azurerecovery"
export AZURE_RECOVERY_UTIL="AzureRecoveryUtil"

#
# Info files global variables
#
export RECOVERY_INFO_FILE=""
export HOSTINFO_FILE=""
export HYDRATION_CONFIG_SETTINGS="emptyconfig"

#
# Status global variable
#
export EXEC_STATUS="Processing"
export EXEC_TASK_DESC="Preparing Environment"
export EXEC_ERROR="0"
export EXEC_ERROR_MSG="Preparing the environment for pre-recovery steps execution"
export EXEC_PROGRESS="0"

_MAX_RETRY_ATTEMPTS_=10
_TRUE_=1
_FALSE_=0
_HOST_ID_=""
_SCENARIO_=""
_SCENARIO_RECOVERY_="recovery"
_SCENARIO_MIGRATION_="migration"
_SCENARIO_RECOVERY_TEST_="testrecovery";
_SCENARIO_MIGRATION_TEST_= "testmigration";

#
# Trace functions to log the trace messages to log file.
#
function Trace
{
    echo "$(date +"%a %b %d %Y %T") : $1" >> $LOGFILE

    # Log to the standard console as well.
    echo "$(date +"%a %b %d %Y %T") : $1"
}

function Trace_Error
{
    Trace "Error : $1"
}

function Trace_Cmd
{
    Trace " Command: $1"
}

function Verify_User
{
    if [ "$(id -u)" != "0" ]
    then
        echo "Only root user can run this script." >2
        exit 1
    fi
}

#
# Synopsis    : Create_Dir <directory-path>
#
# Description : Creates a directory if not exist. If it exist then the existing directory will be
#               forcefully deleted and then new one will be created.
#
function Create_Dir
{
    if [ -z "$1" ] ; then
        echo "Create_Dir : Directory argument missing"
        return 1
    fi

    if [ -d $1 ] ; then
        echo "Directory $1 already exist. Deleting it..."
        $RM -rf $1
        if [ $? -ne 0 ] ; then
            echo "Could not clean-up old directory"
            return 1
        fi
    fi

    echo  "Creating directory $1"

    $MKDIR -p $1
    if [ $? -ne 0 ] ; then
        echo "Error creating directory. Error $?"
        return 1
    fi

    return 0
}

#
# Synopsis    : Change_Dir <target-directory>
#
# Description : Changes the present working directory to target-directory
#
#
function Change_Dir
{
    if [ "$1" = "" ] ; then
        Trace "Change_Dir : Directory argument missing"
        return 1
    fi

    if [ -d $1 ] ; then
        cd $1 >> $LOGFILE 2>&1

        if [ $? -ne 0 ] ; then
            Trace "Can not change to directory $1"
            return 1
        fi
    else
        Trace "$1 Is not a directory or it does not exist"
        return 1
    fi

    return 0
}

#
# Synopsis    : CopyFiles <file-list> <destination-directory>
#
# Description : Copies the list of files to destination directory
#
#
function CopyFiles
{
    if [ $# -ne 2 ] ; then
        Trace_Error "CopyFiles Invalid arguments. Argument count: $#"
        return 1
    fi

    if [ "$1" = "" ] ; then
        Trace_Error "CopyFiles Invalid argument. Empty file list"
        return 1
    fi
    FileList=$1

    if [ "$2" = "" ] ; then
        Trace_Error "CopyFiles Invalid argument. target-directory path is empty"
        return 1
    fi
    DestDir=$2

    Trace "Copying files $FileList to $DestDir"

    for file in $FileList
    do
        Trace_Cmd "$COPY -f $file $DestDir"
        $COPY -f $file $DestDir >> $LOGFILE 2>&1
        if [ $? -ne 0 ] ; then
            Trace_Error "Can not copy file $file to $DestDir"
            return 1
        fi
    done
}

function Extract_ZipFile_Using_Python
{
    # Create python script to extract the zip file.
    local unzip_py="${WORK_DIR}/unzip.py"
    echo '#!/usr/bin/python' > $unzip_py
    echo 'import sys' >> $unzip_py
    echo 'from zipfile import ZipFile' >> $unzip_py
    echo 'from zipfile import BadZipfile' >> $unzip_py
    echo 'try:' >> $unzip_py
    echo "    zip_file = \"$1\"" >> $unzip_py
    echo "    dest_dir = \"$2\"" >> $unzip_py
    echo '    pzf = ZipFile(zip_file)' >> $unzip_py
    echo '    pzf.extractall(dest_dir)' >> $unzip_py
    echo 'except BadZipfile:' >> $unzip_py
    echo '    print("Error: Bad zip file format.")' >> $unzip_py
    echo '    sys.exit(1)' >> $unzip_py
    echo 'else:' >> $unzip_py
    echo '    print("Successfully extracted the zip file.")' >> $unzip_py
    echo '    sys.exit(0)' >> $unzip_py

    # Run python script
    python3 $unzip_py >> $LOGFILE 2>&1

    return $?
}

#
# Synopsis    : Extract_ZipFile <zipfile_path> <target-directory>
#
# Description : Extracts the zip file content to target directory.
#
#
function Extract_ZipFile
{
    if [ $# -ne 2 ] ; then
        Trace_Error "Extract_ZipFile Invalid arguments. Argument count: $#"
        return 1
    fi

    if [ "$1" = "" ] ; then
        Trace_Error "Extract_ZipFile Invalid argument. zipfile path is empty"
        return 1
    fi

    if [ "$2" = "" ] ; then
        Trace_Error "Extract_ZipFile Invalid argument. target-directory path is empty"
        return 1
    fi

    Trace "Extracting $1 to $2"

    if [[ -f $UNZIP_CMD ]]; then
        Trace_Cmd "$UNZIP_CMD -oq $1 -d $2"
        $UNZIP_CMD -oq $1 -d $2 >> $LOGFILE 2>&1
    else
        Trace "Extracting zip file using python..."
        Extract_ZipFile_Using_Python $1 $2
    fi

    if [ $? -ne 0 ] ; then
        Trace_Error "Error extracting $1 to $2"
        return 1
    fi

    Trace "Unzip successful"
    return 0
}

#
# Synopsis    : ScanAllScsiHosts
#
# Description : Scans all the hosts buses available to the machine
#
function ScanAllScsiHosts
{
    for host in /sys/class/scsi_host/host*
    do
        Trace "Scanning the $host ..."
        echo "- - -" > $host/scan
    done
}

#
# Synopsis    : ScanLVM
#
# Description : Scans all the VGs
#
function ScanLVM
{
    # Scan PVs
    Trace "Scanning PVs ..."
    pvscan >> $LOGFILE 2>&1

    # Scan LVs
    Trace "Scanning VGs ..."
    vgscan >> $LOGFILE 2>&1
}

#
# Synopsis    : ActivateVGs
#
# Description : Activate all the VGs visible to the system.
#
function ActivateVGs
{
    for vg in $(vgs -o vg_name --noheadings)
    do
        Trace "Activating VG: $vg"
        vgchange -ay "$vg" >> $LOGFILE 2>&1
    done

    Trace "VG details:"
    vgs -o vg_name,vg_attr,lv_count >> $LOGFILE 2>&1 #Trace purpose.
}

#
# Synopsis    : VerifyFiles <file-list>
#
# Description : Verifies files existence
#
function VerifyFiles
{
    if [ $# -eq 0 ] ; then
        Trace_Error "VerifyFiles invalid argument: Argument missing or empty"
        return 1
    fi

    for file in $1
    do
        Trace "Verifying file : $file"

        if [ -f $file ] ; then
            Trace "File exist"
        else
            Trace_Error "File does not exist"
            return 1
        fi
    done

    return 0
}

#
# Synopsis    : EnableExe_Permissions Directory
#
# Description : Enables the execute permissions to all the files in Directory
#
function EnableExe_Permissions
{
    Trace "Setting execute permissions for the scripts ..."

    if [ $# -eq 0 ] ; then
        Trace_Error "EnableExe_Permissions invalid argument: Argument missing or empty"
        return 1
    fi

    for file in "$1"/*
    do
        if [ -f $file ] ; then
            Trace_Cmd "$SET_PERMS +x $file"
            $SET_PERMS +x $file >> $LOGFILE 2>&1
            if [ $? -ne 0 ] ; then
                 return 1
            fi
        else
            Trace_Error "$file is not a regular file or it does not exist"
        fi
    done

    Trace "Successfully enabled permissions."

    return 0
}

#
# Synopsis    : Update_Status
#
# Description : Invokes recovery utility to update the current status to blob.
#
#
function Update_Status
{
    Trace "Updating execution status : $EXEC_STATUS : $EXEC_TASK_DESC"

    StatusArgs="--operation updatestatus --recoveryinfofile $RECOVERY_INFO_FILE --status $EXEC_STATUS  --errorcode $EXEC_ERROR --progress $EXEC_PROGRESS"
    StatusCmd="$WORK_DIR/$AZURE_RECOVERY_UTIL"

    Trace_Cmd "$StatusCmd  $StatusArgs --taskdescription $EXEC_TASK_DESC --errormsg $EXEC_ERROR_MSG"

    $StatusCmd  $StatusArgs "--taskdescription" "$EXEC_TASK_DESC" "--errormsg" "$EXEC_ERROR_MSG" >> $LOGFILE 2>&1

    RetCode=$?

    if [ $RetCode -ne 0 ] ; then
        Trace_Error "Status update failed. Return code $RetCode"
        return 1
    else
        Trace "Successfully updated the status."
    fi

    return 0;
}

#
# Synopsis    : Update_Test_Status
#
# Description : Invokes recovery utility to update the current status to local file.
#
#
function Update_Test_Status
{
    Trace "Updating execution status : $EXEC_STATUS : $EXEC_TASK_DESC"

    StatusArgs="--operation statusupdatetest --recoveryinfofile $RECOVERY_INFO_FILE --status $EXEC_STATUS  --errorcode $EXEC_ERROR --progress $EXEC_PROGRESS"
    StatusCmd="$WORK_DIR/$AZURE_RECOVERY_UTIL"

    Trace_Cmd "$StatusCmd  $StatusArgs --taskdescription $EXEC_TASK_DESC --errormsg $EXEC_ERROR_MSG"

    $StatusCmd  $StatusArgs "--taskdescription" "$EXEC_TASK_DESC" "--errormsg" "$EXEC_ERROR_MSG" >> $LOGFILE 2>&1

    RetCode=$?

    if [ $RetCode -ne 0 ] ; then
        Trace_Error "Status update failed. Return code $RetCode"
        # Don't fail.
    else
        Trace "Successfully updated the status."
    fi

    return 0;
}

#
# Synopsis    : Upload_Log
#
# Description : Invokes recovery utility for uploading the execution log content to status blob
#
#
function Upload_Log
{
    Trace "Uploading log to status blob ..."

    UploadCmd="$WORK_DIR/$AZURE_RECOVERY_UTIL"
    UploadCmdArgs="--operation uploadlog --recoveryinfofile $RECOVERY_INFO_FILE --logfile $LOGFILE"

    Trace_Cmd "$UploadCmd $UploadCmdArgs"

    $UploadCmd $UploadCmdArgs >> $LOGFILE 2>&1
    if [ $? -ne 0 ] ; then
        Trace_Error "Log upload failed"
        return 1
    else
        Trace "Log upload successful"
    fi

    return 0;
}

#
# Synopsis    : Prepare_Env <host-id>
#
# Description : Prepare the environment for pre-recovery steps execution.
#
function Prepare_Env
{
    Trace "Preparing the environment for pre-recovery steps execution ..."

    HostInfoFile="$HOSTINFO_PREFIX-$_HOST_ID_.xml"
    RecInfoFile="$REC_INFO_PREFIX-$_HOST_ID_.conf"
    PWD=$(pwd)

    RECOVERY_INFO_FILE="$WORK_DIR/$RecInfoFile"
    HOSTINFO_FILE="$WORK_DIR/$HostInfoFile"

    #
    # Extract the zip file to working directory
    #
    Extract_ZipFile "$PWD/$RECOVERY_TOOLS_ZIPFILE" $WORK_DIR
    if [ $? -ne 0 ] ; then
        Trace_Error "Azure recovery files extraction failed."
        return 1
    fi

    #
    # Downlaod and extract Linux Guest Agent files.
    # Timeout: 300 seconds
    #

    if curl --silent -LO "https://github.com/Azure/WALinuxAgent/archive/master.zip" -m 300; then
        Trace "Successfully downloaded WALinuxAgent zip file."
        # Extract master.zip into WALinuxAgentASR
        Extract_ZipFile "$PWD/$LINUX_GA_TOOLS_ZIPFILE" $LINUX_GA_DIR
        if [ $? -ne 0 ] ; then
            Trace_Error "Linux guest agent binaries extraction failed."
        else
            # Enable execution permissions on downloaded guest agent files.
            EnableExe_Permissions  $LINUX_GA_DIR
            if [ $? -ne 0 ] ; then
                Trace_Error "Could not enable execute permission for one of the executables/scripts in Linux GA directory".
            fi
        fi
    else
        Trace_Error "Could not download WALinuxAgent zip file from github."
    fi

    #
    # Set execute permission to the executables/scripts after extraction
    #
    EnableExe_Permissions $WORK_DIR
    if [ $? -ne 0 ] ; then
        Trace_Error "Could not enable execute permission for one of the executables/scripts on working directory."
        return 1
    fi

    #
    # Verify the host-info, recovery-info & executables zip file.
    #
    Trace "Verifying extension files..."
    local ext_files="$PWD/$RECOVERY_TOOLS_ZIPFILE $PWD/$RecInfoFile"
    if [ "$_SCENARIO_" = "$_SCENARIO_RECOVERY_" ]; then
        ext_files="$ext_files $PWD/$HostInfoFile"
    fi

    VerifyFiles "$ext_files"
    if [ $? -ne 0 ] ; then
        Trace_Error "Required files are missing: $ext_files"
        return 1
    fi

    #
    # Copy host-info & recovery-info files to working directory
    #
    Trace "Copying configuration files to working directory ..."

    local config_files="$PWD/$RecInfoFile"
    if [ "$_SCENARIO_" = "$_SCENARIO_RECOVERY_" ]; then
        config_files="$config_files $PWD/$HostInfoFile"
    fi
    CopyFiles "$config_files" $WORK_DIR
    if [ $? -ne 0 ] ; then
        Trace_Error "Can not copy configuration files to $WORK_DIR"
        return 1
    fi

    #
    # Update Execution Status
    #
    Update_Status

    #
    # Change the directory to working directory
    #
    Trace "Changing current directory to working directory ..."
    Change_Dir $WORK_DIR
    if [ $? -ne 0 ] ; then
        EXEC_ERROR_MSG="Can not change to working directory $WORK_DIR. Error $?"
        EXEC_ERROR="2"
        EXEC_STATUS="Failed"

        Trace_Error "$EXEC_ERROR_MSG"

        Update_Status
        Upload_Log

        return 1
    fi

    #
    # Rescan all scsi host buses
    #
    ScanAllScsiHosts

    #
    # Rescan VGs
    #
    ScanLVM

    Trace "Successfully prepared the environment."

    return 0
}

#
# Synopsis    : StartRecovery
#
# Description : Start recovery utility to execute pre-recovery steps. (Failover and Test Failover)
#
function StartRecovery
{
    #
    # Update status with Initiating recovery status.
    #
    EXEC_TASK_DESC="Initiating recovery steps"
    EXEC_ERROR_MSG="Environment was prepared successfully"
    EXEC_PROGRESS="20"

    Update_Status
    #not considering update status return code

    Trace "Starting pre-recovery steps ..."

    RecCmd="$WORK_DIR/$AZURE_RECOVERY_UTIL"
    RecCmdArgs="--operation recovery --recoveryinfofile $RECOVERY_INFO_FILE --hostinfofile $HOSTINFO_FILE --workingdir $WORK_DIR --hydrationconfigsettings $HYDRATION_CONFIG_SETTINGS"

    Trace_Cmd "$RecCmd $RecCmdArgs"

    $RecCmd $RecCmdArgs >> $LOGFILE 2>&1

    RetCode=$?

    if (( $RetCode != 0 )) ; then
        EXEC_ERROR_MSG="Recovery tool exited unexpectedly with error code $RetCode"
        EXEC_ERROR="1"
        EXEC_STATUS="Failed"

        Trace_Error "$EXEC_ERROR_MSG"

        Update_Status
        Upload_Log

        return 1
    fi
    #
    # For recovery operation the tool returns 0 even on recovery failures if it can handle
    # the error status reporting. If its not returning 0 means something wrong happened
    # where the recovery tool was not able to update status to blob. So on non-zero return
    # code the script should attempt updating failure status to blob.
    #
    Trace "Pre-Recovery steps executed successfully"

    return 0;
}

#
# Synopsis    : StartRecoveryTest
#
# Description : Start recovery utility to execute pre-recovery steps.
#               [Note]: Not to be confused with Test Failover in Azure Site Recovery production environment.
#               Refer StartRecovery for TestFailover flow.
#
#
function StartRecoveryTest
{
    #
    # Update status with Initiating recovery status.
    #
    EXEC_TASK_DESC="Initiating recovery steps"
    EXEC_ERROR_MSG="Environment was prepared successfully"
    EXEC_PROGRESS="20"

    Trace "Starting pre-recovery steps ..."

    RecCmd="$WORK_DIR/$AZURE_RECOVERY_UTIL"
    RecCmdArgs="--operation recoverytest --recoveryinfofile $RECOVERY_INFO_FILE --hostinfofile $HOSTINFO_FILE --workingdir $WORK_DIR --hydrationconfigsettings $HYDRATION_CONFIG_SETTINGS"

    Trace_Cmd "$RecCmd $RecCmdArgs"

    $RecCmd $RecCmdArgs >> $LOGFILE 2>&1

    RetCode=$?

    if (( $RetCode != 0 )) ; then
        EXEC_ERROR_MSG="Recovery tool exited unexpectedly with error code $RetCode"
        EXEC_ERROR="1"
        EXEC_STATUS="Failed"

        Trace_Error "$EXEC_ERROR_MSG"

        Update_Test_Status

        return 1
    fi
    #
    # For recovery operation the tool returns 0 even on recovery failures if it can handle
    # the error status reporting. If its not returning 0 means something wrong happened
    # where the recovery tool was not able to update status to blob. So on non-zero return
    # code the script should attempt updating failure status to blob.
    #
    Trace "Pre-Recovery steps executed successfully"

    return 0;
}

#
# Synopsis    : StartMigration
#
# Description : Start recovery utility to execute migration steps. (Migration and Test Migration)
#
#
function StartMigration
{
    #
    # Update status with Initiating recovery status.
    #
    EXEC_TASK_DESC="Initiating migration steps"
    EXEC_ERROR_MSG="Environment was prepared successfully"
    EXEC_PROGRESS="20"

    Update_Status
    #not considering update status return code

    # Activate all the VGs visible to system.
    Trace "Activating VGs ..."
    ActivateVGs

    Trace "Starting migration steps ..."

    RecCmd="$WORK_DIR/$AZURE_RECOVERY_UTIL"
    RecCmdArgs="--operation migration --recoveryinfofile $RECOVERY_INFO_FILE --workingdir $WORK_DIR --hydrationconfigsettings $HYDRATION_CONFIG_SETTINGS"

    Trace_Cmd "$RecCmd $RecCmdArgs"

    $RecCmd $RecCmdArgs >> $LOGFILE 2>&1

    RetCode=$?

    if (( $RetCode != 0 )) ; then
        EXEC_ERROR_MSG="Recovery tool exited unexpectedly with error code $RetCode"
        EXEC_ERROR="1"
        EXEC_STATUS="Failed"

        Trace_Error "$EXEC_ERROR_MSG"

        Update_Status
        Upload_Log

        return 1
    fi

    Trace "Migration steps executed successfully"

    return 0;
}

#
# Synopsis    : StartMigrationTest
#
# Description : Dummy start recovery utility to execute migration steps.
#               [Note]: Not to be confused with Test Migration in Azure Migrate in production environment.
#               Refer StartMigration for TestMigration flow.
#
#
function StartMigrationTest
{
    #
    # Update status with Initiating recovery status.
    #
    EXEC_TASK_DESC="Initiating migration steps"
    EXEC_ERROR_MSG="Environment was prepared successfully"
    EXEC_PROGRESS="20"

    # Activate all the VGs visible to system.
    Trace "Activating VGs ..."
    ActivateVGs

    Trace "Starting migration steps ..."

    RecCmd="$WORK_DIR/$AZURE_RECOVERY_UTIL"
    RecCmdArgs="--operation migrationtest --recoveryinfofile $RECOVERY_INFO_FILE --workingdir $WORK_DIR --hydrationconfigsettings $HYDRATION_CONFIG_SETTINGS"

    Trace_Cmd "$RecCmd $RecCmdArgs"

    $RecCmd $RecCmdArgs >> $LOGFILE 2>&1

    RetCode=$?

    if (( $RetCode != 0 )) ; then
        EXEC_ERROR_MSG="Recovery tool exited unexpectedly with error code $RetCode"
        EXEC_ERROR="1"
        EXEC_STATUS="Failed"

        Trace_Error "$EXEC_ERROR_MSG"

        Update_Test_Status

        return 1
    fi

    Trace "Migration steps executed successfully"

    return 0;
}

#
# Synopsis    : Usage
#
# Description : Displays script usage
#
#
function Usage
{
    echo "Usage: $1 <recovery/migration> <host-id>"
}

#
# Synopsis    : ### Main ###
#
# Description : Entry point function which starts the work-flow
#
#
function Main
{
    if [ $# -eq 1 ] ; then
        # For backward compatibility.
        _SCENARIO_=$_SCENARIO_RECOVERY_
        _HOST_ID_=$1
    elif [ $# -eq 2 ] ; then
        _SCENARIO_=$1
        _HOST_ID_=$2
    elif [ $# -eq 3 ] ; then
        _SCENARIO_=$1
        _HOST_ID_=$2
        HYDRATION_CONFIG_SETTINGS=${3-emptyconfig}
    else
        Usage $0
        exit 1
    fi

    Create_Dir "$WORK_DIR"
    if [ $? -ne 0 ] ; then
        echo "Error: Can not create working directory $WORK_DIR"
        exit 1
    fi

    if [[ $HYDRATION_CONFIG_SETTINGS =~ .*$_ENABLE_LINUX_GA_CONFIG_.* ]]; then
        Create_Dir "$LINUX_GA_DIR"
        if [ $? -ne 0 ] ; then
            echo "Error: Can not create linux guest agent directory $LINUX_GA_DIR"
            #Don't fail
        fi
    fi

    Verify_User

    #
    # Don't use Trace before this point because the log file creation may fail
    # as log file will be created inside the working directory and the working
    # directory has been created just now.
    #

    Prepare_Env
    if [ $? -ne 0 ] ; then
        exit 1
    fi

    case "$_SCENARIO_" in
        $_SCENARIO_RECOVERY_)
            StartRecovery
            if [ $? -ne 0 ] ; then
                exit 1
            fi
            ;;
        $_SCENARIO_MIGRATION_)
            StartMigration
            if [ $? -ne 0 ] ; then
                exit 1
            fi
            ;;
        $_SCENARIO_MIGRATION_TEST_)
            StartMigrationTest
            if [ $? -ne 0 ] ; then
                exit 1
            fi
            ;;
        $_SCENARIO_RECOVERY_TEST_)
            StartRecoveryTest
            if [ $? -ne 0 ] ; then
                exit 1
            fi
            ;;
        *)
            Usage $0
            echo "$_SCENARIO_ is unsupported for Linux Hydration."
            exit 1
            ;;
    esac

    #
    # Normal exit
    #
    exit 0
}

#
# Calling Entry point function for script execution
#
Main "$@"


#! /bin/sh

################
#DEFAULT VALUES#
################

DIR=`pwd`
cd ${DIR}

###################
# CHECKING FOR ACE#
###################

echo "ACE" > thirdparty_components_check.log
echo "---------" >> thirdparty_components_check.log
find ${DIR}/ace-6.4.6/ACE_wrappers -name "*.a" -print >> thirdparty_components_check.log
echo " " >> thirdparty_components_check.log

##############################################
# CHECKING WHETHER ACE_HAS_AIO_CALLS SET TO 1#
##############################################

echo "CHECKING WHETHER ACE_HAS_AIO_CALLS SET TO 1 OR NOT FOR RELEASE" >> thirdparty_components_check.log
echo "-------------------------------------------------------------- " >> thirdparty_components_check.log
cat ${DIR}/ace-6.4.6/ACE_wrappers/ace/config.h | grep "ACE_HAS_AIO_CALLS*" >> thirdparty_components_check.log
echo " " >> thirdparty_components_check.log

echo "CHECKING WHETHER ACE_HAS_AIO_CALLS SET TO 1 OR NOT FOR DEBUG" >> thirdparty_components_check.log
echo "-------------------------------------------------------------- " >> thirdparty_components_check.log
cat ${DIR}/ace-6.4.6/ACE_wrappers/ace/config.h | grep "ACE_HAS_AIO_CALLS*" >> thirdparty_components_check.log
echo " " >> thirdparty_components_check.log

#####################
# CHECKING FOR BOOST#
#####################

echo "BOOST" >> thirdparty_components_check.log
echo "---------" >> thirdparty_components_check.log
find ${DIR}/boost -name "*.a" -print >> thirdparty_components_check.log
echo " " >> thirdparty_components_check.log

###################
# CHECKING FOR CDK#
###################

echo "CDK" >> thirdparty_components_check.log
echo "---------" >> thirdparty_components_check.log
find ${DIR}/cdk-5.0.4 -name "*.a" -print >> thirdparty_components_check.log
echo " " >> thirdparty_components_check.log

####################
# CHECKING FOR CURL#
####################

echo "CURL" >> thirdparty_components_check.log
echo "---------" >> thirdparty_components_check.log
find ${DIR}/curl-7.59.0 -name "*.a" -print >> thirdparty_components_check.log
echo " " >> thirdparty_components_check.log

#######################
# CHECKING FOR OPENSSL#
#######################

echo "OPENSSL" >> thirdparty_components_check.log
echo "---------" >> thirdparty_components_check.log
find ${DIR}/openssl-1.0.2p -name "*.a" -print >> thirdparty_components_check.log
echo " " >> thirdparty_components_check.log

######################
# CHECKING FOR SQLITE#
######################

echo "SQLITE" >> thirdparty_components_check.log
echo "---------" >> thirdparty_components_check.log
find ${DIR}/sqlite-3.8.2 -name "*.a" -print >> thirdparty_components_check.log
echo " " >> thirdparty_components_check.log

#########################
# CHECKING FOR SQLITE_3X#
#########################

echo "SQLITE3X" >> thirdparty_components_check.log
echo "---------" >> thirdparty_components_check.log
find ${DIR}/sqlite3x/ -name "*.a" -print >> thirdparty_components_check.log
echo " " >> thirdparty_components_check.log

####################
# CHECKING FOR ZLIB#
####################

echo "ZLIB" >> thirdparty_components_check.log
echo "---------" >> thirdparty_components_check.log
find ${DIR}/zlib-1.2.8 -name "*.a" -print >> thirdparty_components_check.log
echo " " >> thirdparty_components_check.log

#######################
# CHECKING FOR LIBSSH2#
#######################

echo "LIBSSH" >> thirdparty_components_check.log
echo "---------" >> thirdparty_components_check.log
find ${DIR}/libssh2-1.8.0 -name "*.a" -print >> thirdparty_components_check.log
echo " " >> thirdparty_components_check.log

#######################
# CHECKING FOR LIBXML2#
#######################

echo "LIBXML" >> thirdparty_components_check.log
echo "---------" >> thirdparty_components_check.log
find ${DIR}/libxml2/libxml2-2.9.1 -name "*.a" -print >> thirdparty_components_check.log


#!/bin/sh

# get configuration
[ -n "$WEBSTONEROOT" ] || WEBSTONEROOT=`pwd`/..
. $WEBSTONEROOT/conf/testbed

case $# in
  1)
     FILELIST=$1
     ;;
  *)
     FILELIST=$WEBSTONEROOT/conf/filelist
     ;;
esac

TIMESTAMP=`date +"%y%m%d_%H%M"`
mkdir $TMPDIR/webstone-genfiles.$TIMESTAMP
cd $TMPDIR/webstone-genfiles.$TIMESTAMP

cat $FILELIST |
nawk '
($3 ~ /^\#[0-9]*/) {
  sub(/^\#/, "", $3);
  cmd = WEBSTONEROOT "/bin/genrand " $3 " ."$1
  print cmd;
  system(cmd);
  cmd = RCP " ." $1 " " SERVER ":" WEBDOCDIR
  print cmd;
  system(cmd);
  cmd = "rm -f ." $1
  print cmd;
  system(cmd);
  next
}
' $* WEBSTONEROOT=$WEBSTONEROOT RCP=$RCP SERVER=$SERVER WEBDOCDIR=$WEBDOCDIR

cd $TMPDIR
rm -rf $TMPDIR/webstone-genfiles.$TIMESTAMP

#end


#!/bin/sh

# This is the UNIX version of the one-button ACE tests.
# Contributed by Michael Rueger <m_rueger@SYSCOMP.DE>
# mrm@cisco.com - Change to for loop  script could be more generic if we put
# this in the bin dir and fed it a file to read from

IFS="|"
tmp=/tmp

# these patterns should not be included in log file
ERROR_MSGS="assertion failed|not supported|No such file or directory|Invalid argument|timeout|Bad file number"

# these patterns must be included in log file
SUCCESS_MSGS="starting|Ending"

run()
{
  echo running $1
  /bin/rm -f core

  ./$1
  status=$?

  if [ $status -ne 0 ]; then
    echo \"$1\" FAILED with exit status $status!!!!
  fi

  if [ -f core ]; then
    echo \"$1\" dumped core!!!!
  fi

  for i in $SUCCESS_MSGS; do
    grep $i log/$1.log >/dev/null
    if [ $? -eq 1 ]; then
      echo Error in log file no line with $i
    fi
  done

  for i in $ERROR_MSGS; do
    grep $i log/$1.log
  done
}

echo "Starting tests..."
FILES=`ls *_Test 2>/dev/null`

if [ -z $FILES ]; then
  echo "ERROR: no test programs generated matching pattern *_Test."
  echo "ERROR: Try compiling the test programs first."
  exit 1
fi

for i in *_Test
do
  run $i
done

echo "Tests complete..."

# EOF


#!/bin/sh
# This script assumes it is being run by bash

# ======= needed functions ======
# abspath relpath curentpath
abspath ()
{
# treat "./" as a special case
if expr "$1" : '\./' >/dev/null; then
  b=`echo $1 | sed 's@\./@@'`
  echo $2/$b
  return 0
fi
b=$1
a=$2
# for each "../" we remove one directory from the current path
# and leading "../" from the relative path
# until we have the unique part in b and the abs prefix in a
while expr "$b" : '\.\./' >/dev/null
do
  b=`echo $b | sed 's@\.\./@@'`
  a=`echo $a | sed 's@/[^/]*$@@'`
done
# return the completed absolute path
echo $a/$b
}

# relpath abspath curentpath
relpath ()
{
# take "/" off beginning
a=`echo $1 | sed 's@^/@@'`
# take "/" off beginning and add to end
b=`echo $2 | sed 's@^/@@;s@$@/@'`
while true
do
  if [ "$b" = "" ]; then
    break;
  fi
  a1=`echo $a | sed 's@\([^/]*\)/.*@\1@'`
  b1=`echo $b | sed 's@\([^/]*\)/.*@\1@'`
  if [ "$a1" != "$b1" ]; then
    break;
  fi
  a=`echo $a | sed 's@[^/]*/@@'`
  b=`echo $b | sed 's@[^/]*/@@'`
done
# a now has the unique part of the path
c=""
# c will have the required number of "../"'s
while [ "$b" != "" ]
do
  c="../$c"
  b=`echo $b | sed 's@[^/]*/@@'`
done
# return the completed relative path
echo "$c$a"
}

# ====== MAIN ======
# Assume any relative path passed in is relative to the current directory
# Given $1 is a path to the source file
# Given $2 is a path of the link to be created
# Create a link that has the relative path to the source file
# That is, $1 converted relative to $2
# Check if $1 is absolute or already relative
#echo add_rel_link.sh $1 $2
if expr "$1" : '\/' >/dev/null; then
  # The source path is absolute, this is the expected case
  # Check if $2 is absolute or relative
  if expr "$2" : '\/' >/dev/null; then
    # The link path is already absolute, so just use it
    lpath=$2
  else
    # The link path is relative, this is the expected case
    # WARNING: don't use $PWD here, it won't work right
    # WARNING: pwd may be a shell alias.  Use /bin/pwd.
    cur=`/bin/pwd`
    lpath=`abspath $2 $cur`
  fi
  # take name off the end of the dest
  ldir=`echo $lpath | sed 's@/[^/]*$@@'`

  # If the original path and the ldir do not originate in the same
  # directory tree, we should just use absolute paths
  if [ "`echo $1 | cut -d/ -f2`" != "`echo $ldir | cut -d/ -f2`" ]; then
    spath=$1
  else
    spath=`relpath $1 $ldir`
  fi
  # use the completed relative path and the given designation path
  echo ln -s $spath $2
  ln -s $spath $2
else
  # The source path is already relative, so just use it
  echo ln -s $1 $2
  ln -s $1 $2
fi


#!/bin/sh

if test -z $1; then CURRENTDATE=YYYY_MM_DD; else CURRENTDATE=$1; fi

wget http://teststat.remedy.nl/teststat/cleanbuild_testfails-$CURRENTDATE.txt -O cleanbuild.txt
#
grep -h \!FIXED_BUGS_ONLY ${ACE_ROOT}/tests/*.lst ${ACE_ROOT}/bin/*.lst ${TAO_ROOT}/bin/*.lst ${CIAO_ROOT}/bin/*.lst ${DANCE_ROOT}/bin/*.lst | sed -e "s/^\([^\:]*\).*/\1/" | sed -e "s/\(\/run_test.pl\)\?\s*$//" > Ignore.txt
#
cat cleanbuild.txt | grep -v -f Ignore.txt | tee cleanbuildresults.txt


#!/bin/sh

SYSTEM=`uname -s`
IPCS="ipcs"
IPCRM="ipcrm -s"

if [ "$SYSTEM" = "Darwin" ]; then
  USER=`id | sed 's/(.*//; s/uid=//'`
  IPCS="ngvipc -s"
  IPCRM="ngvipc -s -R"
elif [ -z "$USER" ]; then
  USER=`id | sed 's/).*//; s/.*(//'`
fi

case "$SYSTEM" in
  "Linux" )
    ipcs -a | grep $USER | awk '{ print ($2) }' | xargs -r ipcrm sem;
    ;;
  * )
    semids=`$IPCS | grep "^s" | grep $USER | awk '{ print ($2) }'`
    for p in $semids
      do $IPCRM $p
    done
    ;;
esac


#!/bin/sh

for i in *.gz *.bz2 *.zip *.md5; do
  d=`echo $i | sed 's/\.[tz][ai][rp]/-$1&/'`
  echo "Copying $i to $d"
  cp -ip $i /export/www/download.dre/previous_versions/$d
done


#!/bin/sh

if test -z $1; then newdate=`date -u +%Y_%m_%d`; else newdate=$1; fi
if test -z $2; then prefix=`date -u +%Y%m%d%a`; else prefix=$2; fi
if test -z $3; then olddate=2017_09_07; else olddate=$3; fi
if test -z $ACE_ROOT; then ACE_ROOT=..; fi
if test -z $TAO_ROOT; then TAO_ROOT=${ACE_ROOT}/TAO; fi
if test -z $CIAO_ROOT; then CIAO_ROOT=${TAO_ROOT}/CIAO; fi
if test -z $DANCE_ROOT; then DANCE_ROOT=${TAO_ROOT}/DAnCE; fi
if test -z $DDS_ROOT; then DDS_ROOT=${TAO_ROOT}/DDS; fi
#
grep -h \!FIXED_BUGS_ONLY ${ACE_ROOT}/tests/*.lst ${ACE_ROOT}/bin/*.lst ${TAO_ROOT}/bin/*.lst ${CIAO_ROOT}/bin/*.lst ${DANCE_ROOT}/bin/*.lst ${DDS_ROOT}/bin/*.lst | sed -e "s/^\([^\:]*\).*/\1/" | sed -e "s/\(\/run_test.pl\)\?\s*$//" > ${prefix}-Ignore.txt
#
perl ${ACE_ROOT}/bin/diff-builds.pl -r -D $olddate -D $newdate | perl -ne 'print unless /^(\@\@|[ \-][a-zA-Z])/' | grep -v -f ${prefix}-Ignore.txt | tee ${prefix}-Builds.txt | grep '+[a-zA-Z]' | sort | uniq -c | sort -n -r -s | sort -k3 -r -s > ${prefix}-Tests.txt
perl ${ACE_ROOT}/bin/diff-builds.pl -D $olddate -D $newdate | perl -ne 'print unless /^(\@\@|[ \-][a-zA-Z])/' | grep -v -f ${prefix}-Ignore.txt | grep '+[a-zA-Z]' | sort | uniq -c | sort -n -r -s > ${prefix}-Tests-NoTestRev.txt


#!/bin/sh
#

if [ $# -lt 1 ]; then
  echo "Usage: $0 [DEST]"
  exit 0
fi

DEST=$1
DATE=`date +%Y/%m/%d-%H:%M`

BINS="$TAO_ROOT/tests/ORB_init/ORB_init $TAO_ROOT/tests/ORB_destroy/ORB_destroy"

LIBS="$ACE_ROOT/ace/libACE.a \
    $TAO_ROOT/tao/libTAO.a \
    $TAO_ROOT/tao/PortableServer/libTAO_PortableServer.a \
    $TAO_ROOT/tao/Strategies/libTAO_Strategies.a \
    $TAO_ROOT/tao/SmartProxies/libTAO_SmartProxies.a \
    $TAO_ROOT/tao/DynamicAny/libTAO_DynamicAny.a \
    $TAO_ROOT/tao/DynamicInterface/libTAO_DynamicInterface.a \
    $TAO_ROOT/tao/IFR_Client/libTAO_IFR_Client.a \
    $TAO_ROOT/tao/BiDir_GIOP/libTAO_BiDirGIOP.a \
    $TAO_ROOT/tao/IORManipulation/libTAO_IORManip.a \
    $TAO_ROOT/tao/IORTable/libTAO_IORTable.a \
    $TAO_ROOT/tao/TypeCodeFactory/libTAO_TypeCodeFactory.a \
    $TAO_ROOT/tao/RTCORBA/libTAO_RTCORBA.a \
    $TAO_ROOT/tao/IORInterceptor/libTAO_IORInterceptor.a \
    $TAO_ROOT/tao/Messaging/libTAO_Messaging.a \
    $TAO_ROOT/tao/ObjRefTemplate/libTAO_ObjRefTemplate.a \
    $TAO_ROOT/tao/Valuetype/libTAO_Valuetype.a \
    $TAO_ROOT/tao/RTScheduling/libTAO_RTScheduler.a \
    $TAO_ROOT/tao/AnyTypeCode/libTAO_AnyTypeCode.a \
    $TAO_ROOT/tao/PI/libTAO_PI.a \
    $TAO_ROOT/tao/PI_Server/libTAO_PI_Server.a \
    $TAO_ROOT/tao/Codeset/libTAO_Codeset.a \
    $TAO_ROOT/tao/CodecFactory/libTAO_CodecFactory.a \
    $TAO_ROOT/tao/RTPortableServer/libTAO_RTPortableServer.a"

mkdir -p $DEST/source
mkdir -p $DEST/data
mkdir -p $DEST/images

for i in $BINS; do
  b=`basename $i`
  if [ -x $i ]; then
    (
      echo -n $DATE " ";
      size $i |
      grep -v text |
      awk '{print $4}'
    ) >> $DEST/source/${b}_size.txt
  fi
done

for i in $LIBS; do
  b=`basename $i`;
  if [ -f $i ]; then
    (
      echo -n $DATE " ";
      size $i |
       awk '{s += $4} END {print s}'
    ) >> $DEST/source/${b}_size.txt
  fi
done

cd $DEST/source

for i in $LIBS $BINS; do
 b=`basename $i`
 /usr/bin/tac ${b}_size.txt > $DEST/data/${b}_size.txt
 /usr/bin/tail -5 ${b}_size.txt > $DEST/data/LAST_${b}_size.txt
 $ACE_ROOT/bin/generate_footprint_chart.sh ${b}_size.txt $DEST/images/${b}_size.png $b
done


#!/bin/sh
#
# This simple script is used to gather compile time metrics.  You can use
# it with make like this:
#
#  $ make CXX=g++_metric.sh
#

commandline=$@
# find the target and save it to a variable
until [ -z "$1" ] # test all command line parameters
do
  if [ "-o" = "$1" ]
  then
    shift
    target=$1
    break
  fi
  shift
done

# echo out "(%x)", the return value from g++, so the script processes the output
#  will only use times for successful compilations, i.e., "(0)".
/usr/bin/time -f "//compile time(%x): ${PWD#$ACE_ROOT/}/${target} %U %S" g++ $commandline

retval=$?

exit $retval


#! /bin/sh
#
# This script generate metrics html pages for either compile times or
# footprint.
#
# Compile times:
# Parse the build.txt file from an autobuild that was generated with the
# g++_metric.sh script, e.g., with CXX=g++_metric.sh which outputs
# compile times on a per object basis, and use the data to generate time
# series graphs with gnuplot.
#
# Footprint:
# Parse the build.txt file and and the *.map files, generated with LDFLAGS
# set to =-Xlinker -M -Xlinker -Map -Xlinker \$@.map and static_libs_only=1.
#
# For use with an autobuild, place a line something like this in the xml file,
# after the log file is closed, but before it's moved.
#
#  <command name="shell"  options="$ACE_ROOT/bin/generate_compile_stats.sh <path>/build.txt <destination> Footprint" />
#

###############################################################################
#
# usage
#
###############################################################################
usage ()
{
  echo "Usage: `basename $0` [--base=<dir>] [--name=<name>] [--compiler=compiler]"
  echo "       <input_file> <destination_directory> [target_file]"
  echo "       [Footprint|Compilation] [<date>] [<fudge_factor>]"
  echo ""
  echo "--base       This option can be used to set the base root directory to"
  echo "             something other than the default \$ACE_ROOT."
  echo "--name       This option can be used to set the software title to something"
  echo "             other than the default ACE+TAO+CIAO+DAnCE."
  echo "--compiler   This option can be used to set the compiler to something"
  echo "             other than the default gcc."
  echo "input_file   This is the compilation log file."
  echo "destination_directory This designates the location of the generated html."
  echo "target_file  This is similar to input_file, but should contain no errors."
  echo "date         Set the date used in all generated html pages."
  echo "fudge_factor Add the specified number of seconds to the compilation time"
  echo "             for each target."
  echo ""
  echo "Options must be specified in the order shown above."
  exit
}

###############################################################################
#
# parse_time
#
# this only works for english
# assumes the date is formatted like this:  Sat Apr 12 18:19:31 UTC 2003
# and outputs this: 2003/04/12-18:19
#
###############################################################################
parse_time ()
{
  # todo: add a format parameter
  local INDEX=0
  local PT_MONTH=""
  local PT_DAY=""
  local PT_YEAR=""
  local PT_HOUR=""
  local PT_MINUTE=""
  local PT_SECOND=""
  local PT_TIMEZONE=""

  read -a line
  for token in "${line[@]}"; do
    #echo "$INDEX = $token"
    case $INDEX in
      1 ) case $token in
            Jan ) PT_MONTH="01" ;;
            Feb ) PT_MONTH="02" ;;
            Mar ) PT_MONTH="03" ;;
            Apr ) PT_MONTH="04" ;;
            May ) PT_MONTH="05" ;;
            Jun ) PT_MONTH="06" ;;
            Jul ) PT_MONTH="07" ;;
            Aug ) PT_MONTH="08" ;;
            Sep ) PT_MONTH="09" ;;
            Oct ) PT_MONTH="10" ;;
            Nov ) PT_MONTH="11" ;;
            Dec ) PT_MONTH="12" ;;
          esac ;;
      2 ) PT_DAY="$token" ;;
      3 ) PT_HOUR="${token%%:*}"
          PT_MINUTE="${token%:*}"
          PT_MINUTE="${PT_MINUTE#*:}"
          PT_SECOND="${token##*:}" ;;
      4 ) PT_TIMEZONE="$token" ;;
      5 ) PT_YEAR="$token" ;;
    esac
    let INDEX=$INDEX+1
  done
  if [ "$1" = "debug" ]; then
    echo "month = $PT_MONTH"
    echo "day   = $PT_DAY"
    echo "year  = $PT_YEAR"
    echo "hour  = $PT_HOUR"
    echo "min   = $PT_MINUTE"
    echo "sec   = $PT_SECOND"
    echo "tz    = $PT_TIMEZONE"
  fi
  echo "$PT_YEAR/$PT_MONTH/$PT_DAY-$PT_HOUR:$PT_MINUTE"
}

###############################################################################
#
# strip_date
#
# grab date from line with following format:
# ################### End [Fri Apr 11 00:18:31 2003 UTC]
# and return it in this format: Fri Apr 11 00:18:31 UTC 2003 which is
# what parse_time() expects
#
###############################################################################
strip_date ()
{
  local INDEX=0
  local TEMP_DATE=""
  local DATE=""
  read -a line
  for token in "${line[@]}"; do
    #echo "$INDEX = $token"
    case $INDEX in
       2 ) DATE=${token#[} ;;
       7 ) DATE="$DATE ${token%]} $TEMP_DATE" ;;
       # this is a hack since the autobuild scripts don't format the date
       # correctly...  :-(
       6 ) TEMP_DATE=$token ;;
       * ) DATE="$DATE $token" ;;
    esac
    let INDEX=$INDEX+1
  done
  echo $DATE
}

###############################################################################
#
# parse
#
# Parse the commandline and validate the inputs
#
###############################################################################
parse ()
{
  echo "parse()"
  while [ $# -gt 1 ]; do
    if [ -n "`echo $1 | grep '^--base=.*'`" ]; then
      BASE_ROOT=`echo $1 | sed 's/^--base=//'`
      shift
    elif [ -n "`echo $1 | grep '^--name=.*'`" ]; then
      BASE_TITLE=`echo $1 | sed 's/^--name=//'`
      shift
    elif [ -n "`echo $1 | grep '^--compiler.*'`" ]; then
      COMPILER=`echo $1 | sed 's/^--compiler=//'`
      shift
    else
      break
    fi
  done

  # set input file and destination (required)
  if [ $# -gt 1 ]; then
    INFILE=$1
    DEST=$2

    if ! [ -e "$INFILE" ]; then
      echo "input_file $INFILE does not exist."
      usage
    fi
  else
    usage
  fi

  # set the target file from command line
  if [ $# -gt 2 ]; then
    TARGETS=$3
  else
   TARGETS=$INFILE
  fi

  # set type of metric from command line
  if [ $# -gt 3 ]; then
    METRIC=$4
  else
    METRIC="Compilation"
  fi
  echo "metric = ($METRIC)"

  # set the date from command line
  if [ $# -gt 4 ]; then
    DATE=$5
  else
    DATE=`tail -n 1 $INFILE | strip_date | parse_time`
  fi
  echo "date = ($DATE)"

  # set fudge factor from commandline (for testing)
  if [ $# -gt 5 ]; then
    FUDGE_FACTOR=$6
  else
    FUDGE_FACTOR=0
  fi
}

###############################################################################
#
# gen_chart
#
# Generate the actual charts and move them to ${DEST}
#
###############################################################################
gen_chart ()
{
  local object=$1
  local DEST=$2
  local TYPE=$3
  local EXT="txt"
  local YLABEL="Compile Time (Seconds)"
  local FACTOR=1
  local low=$4
  local high=$5

  if [ "$TYPE" = "Footprint" ]; then
    EXT="size"
    if [ ${high} -gt 1024 ]; then
      YLABEL="Footprint (KBytes)"
      FACTOR=1024
    else
      YLABEL="Footprint (Bytes)"
      FACTOR=1
    fi
  fi

  let low="${low}/${FACTOR}"
  let high="${high}/${FACTOR}"

  sort -t'/' -k1n -k2n -k3n ${DEST}/data/${object}.${EXT} | grep -E ^2 > tmp.txt

  gnuplot <<EOF
    set data style lp l
    set time "$DATE"
    set xdata time
    set timefmt "%Y/%m/%d-%H:%M"
    set format x "%Y/%m/%d"
    set xtics rotate
    set xlabel 'Date (YYYY/MM/DD)' 0,-3
    set ylabel "${YLABEL}"
    set terminal png small size 1024,768 color
    set yrange [0:]
    set output "${DEST}/images/${object}_${TYPE}.png"
    set title "${object//___//}"
    plot 'tmp.txt' using 1:(\$2/$FACTOR) notitle w points, 'tmp.txt' using 1:(\$2/$FACTOR) notitle w l lt 3 lw 4
    exit
EOF

  # here's how to reduce the scale
  #  plot '$1' using 1:(\$2/1024.0) title '$3' w l
}

###############################################################################
#
# create_dirs
#
# Make sure hidden directory tree exists, and create it if it doesn't
#
###############################################################################
create_dirs ()
{
  echo "create_dirs() '$1'"
  if ! [ -d "${1}" ]; then
    mkdir -p ${1}
  fi
  if ! [ -d "${1}data" ]; then
    mkdir -p ${1}data
  fi
  if ! [ -d "${1}images" ]; then
    mkdir -p ${1}images
  fi
}

###############################################################################
#
# process_file
#
# Process the the $INPUT file
#
###############################################################################
process_file ()
{
  echo "process_file()"

  local CURRENT_TIME=0
  local CURRENT_OBJECT=""
  local CURRENT_PATH=""
  local seconds=0
  local hundreths=0

  while read target usertime systemtime; do

    # get path
    CURRENT_PATH=${target%/*}

    # strip off the hidden directory if needbe
    CURRENT_PATH=${CURRENT_PATH%/.*}

    # replace all "/" with "___"
    # (so we can keep them all in the same directory)
    CURRENT_PATH=${CURRENT_PATH//\//___}

    # strip path off of target
    CURRENT_OBJECT=${CURRENT_PATH}___${target##*/}
    #echo "target = $target, object = $CURRENT_OBJECT,  path = $CURRENT_PATH"
    #echo "usertime = $usertime, systemtime = $systemtime"

    let seconds="${usertime%.*}+${systemtime%.*}"

    # it's just easier to grab the values first, since .0n causes problems...
    userdec="${usertime#*.}"
    userdec=${userdec#0}
    systemdec="${systemtime#*.}"
    systemdec=${systemdec#0}
    let hundreths="${userdec}+${systemdec}"

    let CURRENT_TIME="(${seconds}*100 + ${hundreths})+$FUDGE_FACTOR"
    echo $DATE $CURRENT_TIME >> ${DEST}/data/${CURRENT_OBJECT}.txt

  done # while
}

###############################################################################
#
# composite_list
#
###############################################################################
composite_list ()
{
  local FOUND_OBJ=0
  local BASE_OBJ_FLAG=0
  local BASE_OBJ=""
  local OBJ_LIST=""
  local DIR_LINE=0
  local DIR=""
  local INDEX=0

  while read -a line; do
    DIR_LINE=0
    INDEX=0

    for i in "${line[@]}"; do
      if [ $DIR_LINE -eq 1 ]; then

        # only process when entering a directory
        if [ $INDEX -eq 1 ] && [ "$i" = "Leaving" ]; then
          DIR=""
          break
        fi

        if [ $INDEX -eq 3 ]; then
          DIR="${i%?}"                        # strip off last "'"
          DIR="${DIR#*$BASE_ROOT/}"           # strip off $BASE_ROOT
          DIR="${DIR//\//___}___"             # replace "/" with "___"
          break
        else
          let INDEX="$INDEX+1"
          continue
        fi
      fi

      # if it was a "make" line then continue to the next token which will
      # continue to process above
      if [ "${i%[*}" = "make" ] || [ "${i%:*}" = "make" ]; then
        DIR=""
        let DIR_LINE=1
        let INDEX="$INDEX+1"
        continue
      fi

      # not an "make" line, so process it here.
      if [ $BASE_OBJ_FLAG -eq 1 ]; then
         BASE_OBJ="${DIR}${i##.*/}"
         # strip off lib numbers
         if [ "$BASE_OBJ" != "${BASE_OBJ%.so.*}" ]; then
           BASE_OBJ=${BASE_OBJ%.so.*}.so
         fi
         BASE_OBJ_FLAG=0
      elif [ "$i" = "-o" ]; then
        # found our base object, set flag so we can grab the next one
        BASE_OBJ_FLAG=1
      elif [ "$i" = "${i#-}" -a "$i" = "${i#/}" -a "$i" != "${i%.o}" ]; then
        OBJ_LIST="$OBJ_LIST ${DIR}${i##*/}"
        FOUND_OBJ=1
      fi
    done # for
    if [ $FOUND_OBJ -eq 1 ]; then
      echo "$BASE_OBJ : $OBJ_LIST"
      FOUND_OBJ=0
      OBJ_LIST=""
      BASE_OBJ=""
    fi
  done # while
}

###############################################################################
#
# create_composite_list
#
###############################################################################
create_composite_list ()
{
  echo "create_composite_list()"
  local INFILE=$1

  # create a pattern file
  echo "\-L" > ${DEST}/comp_match.txt
  echo "Entering directory" >> ${DEST}/comp_match.txt

  # grep out the entering directory line and all the link lines,
  # but only keep entering directory lines preceeding link lines.
  cat $INFILE | grep -f ${DEST}/comp_match.txt | grep -B1 "\-L" \
   | grep -ve "--" | composite_list > ${DEST}/composites.txt
}

###############################################################################
#
# library_list
#
###############################################################################
library_list ()
{
  local FOUND_OBJ=0
  local BASE_OBJ_FLAG=0
  local BASE_OBJ=""
  local OBJ_LIST=""
  local DIR_LINE=0
  local DIR=""
  local INDEX=0

  while read -a line; do
    DIR_LINE=0
    INDEX=0
    for i in "${line[@]}"; do
      if [ $DIR_LINE -eq 1 ]; then
        if [ $INDEX -eq 3 ]; then
          DIR="${i%?}"                        # strip off last "'"
          DIR="${DIR#*$BASE_ROOT/}"           # strip off $BASE_ROOT
          DIR="${DIR//\//___}___"             # replace "/" with "___"
          break
        else
          let INDEX="$INDEX+1"
          continue
        fi
      fi

      # if it was a "make" line then continue to the next token which will
      # continue to process above
      if [ "${i%[*}" = "make" ]; then
        let DIR_LINE=1
        let INDEX="$INDEX+1"
        continue
      fi

      # not a "make" line, so process it here.  We are interested in the
      # 3rd, and last,  token, i.e., lib*.a
      let INDEX="$INDEX+1"
      if [ $INDEX -eq 3 ]; then
        echo "$DIR$i"
      fi
    done # for
  done # while
}

###############################################################################
#
# create_library_list
#
###############################################################################
create_library_list ()
{
  echo "create_library_list()"
  local INFILE=$1

  # create a pattern file
  echo "chmod" > ${DEST}/lib_match.txt
  echo "Entering directory" >> ${DEST}/lib_match.txt

  # grep out the entering directory line and all the link lines,
  # but only keep entering directory lines preceeding link lines.
  cat $INFILE | grep -f ${DEST}/lib_match.txt | grep -B1 "chmod" \
   | grep -ve "--" | library_list > ${DEST}/libraries.txt
}

###############################################################################
#
# rollup_compile_times
#
###############################################################################
rollup_compile_times ()
{
  echo "process_composite_objects()"
  local TOTAL_TIME=0
  local temp
  local tdate=""
  local ttime=0
  local lpath="${DEST}/data/"

  # rollup compile times
  while read outfile colon infiles; do
    #echo "$outfile ----- $infiles"
    for i in $infiles; do
      temp=`head -n 1 ${lpath}${i}.txt`
      tdate=${temp%% *}
      let ttime="${temp##* }"

      if [ "$tdate" = "$DATE" ]; then
        let TOTAL_TIME="$TOTAL_TIME + ${ttime}"
      fi
    done # for
    echo "$DATE $TOTAL_TIME" >> ${lpath}${outfile}.txt
    let TOTAL_TIME=0
  done # while
}

###############################################################################
#
# footprint
#
###############################################################################
footprint ()
{
  echo "footprint()"
  local TYPE="$1"
  local fpath=""
  local lpath="${DEST}/data/"
  local FILE=""
  local SIZE=""

  # Remove the old size_composites.txt and create a new one since
  # we have all the info we need from the size command on a library.
  if [ "$TYPE" = "LIB" ] && [ -e ${DEST}/size_composites.txt ]; then
    rm ${DEST}/size_composites.txt
  fi

  # go through all the targets and get the sizes of the target and
  # each dependent object and write it to a *.size file.
  while read outfile colon infiles; do
    # reconstitue file name
    FILE="$BASE_ROOT/${outfile//___//}"

    if [ -e $FILE ]; then
      #echo "inside if"
      SIZE=`size $FILE | grep -v text | awk '{s += \$4} END {print s}'`
      echo "$DATE $SIZE" >> $lpath/${outfile}.size

      # only process the included objects if it's a library
      if [ "$TYPE" = "LIB" ]; then
        fpath=${FILE%/*}
        # now, do the same for all the objects in the file (if any)
        size $FILE |
        grep -v text |
        awk '{print $4 " : " $6}' | process_included $fpath $lpath $FILE
      fi
    fi

  done # while
}

###############################################################################
#
# process_included
#
###############################################################################
process_included ()
{
  echo "process_included()"
  local fpath=$1
  local lpath=$2
  local LIBRARY=$3
  local FILE=""
  local OUTFILE=""

  # while we are here, and have the info, go ahead and write out
  # size dependencies for each library.
  LIBRARY="${LIBRARY#*$BASE_ROOT/}"   # strip off $BASE_ROOT
  LIBRARY="${LIBRARY//\//___}"        # replace "/" with "___"
  echo -n  "$LIBRARY : " >> ${DEST}/size_composites.txt

  while read size colon file; do
    FILE=$fpath/$file
    OUTFILE="${FILE#*$BASE_ROOT/}"     # strip off $BASE_ROOT
    OUTFILE="${OUTFILE//\//___}"       # replace "/" with "___"
    #echo "size = ($size)"
    echo "$DATE $size" >> $lpath/${OUTFILE}.size

    # add the object
    echo -n "$OUTFILE " >> ${DEST}/size_composites.txt

  done
  # add newline
  echo "" >> ${DEST}/size_composites.txt

}

###############################################################################
#
# process_map_file
#
###############################################################################
process_map_file ()
{
  # this is way too noisy...
  #echo "process_map_file()"
  local index=0
  local INFILE=$1
  local FILE=""

  # Read in the map file.  The first section is all we are interested
  # in right now.  As soon as we see "Memory Configuration" we are done.
  while read line; do
    let index=$index+1
    # Skip the first 2 lines, then read in all the odd lines, they are the
    # objects that must be loaded.  The following line, even lines, is the
    # object that caused it to be loaded.
    if [ $index -lt 3 ] || [ "$line" = "" ]; then
      continue
    fi

    # The line looks like this:
    #/ace_root_path/ace/libACE.a(Malloc.o)
    # need to find the real library path, since these libs will
    # always be in ace/, but the objects will be in the original
    # location.
    lib="${line##/*/}"    # strip off path, but only if it starts a line
    lib="${lib%%.a*}"     # strip off rest of line
    lib="$lib.a"          # put back the .a to make it unambiguous
    libpath=`grep $lib ${DEST}/libraries.txt`
    path="${libpath%___lib*}"         # strip off libname
    FILE="${line#*(}"             # strip off everything up to object name
    FILE="${FILE%%)*}"            # strip off rest of line
    FILE="${path}___${FILE}"
    echo -n "$FILE " >> ${DEST}/size_composites.txt
  done

  echo "" >> ${DEST}/size_composites.txt

}

###############################################################################
#
# create_size_composites
#
###############################################################################
create_size_composites ()
{
  echo "create_size_composites()"
  local FILE=""

  while read outfile colon infiles; do
    # reconstitue file name
    FILE="$BASE_ROOT/${outfile//___//}.map"
    if [ -e $FILE ]; then
      echo -n "$outfile : " >> ${DEST}/size_composites.txt
      # only process lines that don't begin with a space
      cat $FILE | sed -e '/Memory Configuration/,$d' \
        | sed -e '/Allocating common symbols/,$d' \
        | grep -v "^ " | process_map_file $FILE
    fi
    #break
  done

}

###############################################################################
#
# create_images
#
###############################################################################
create_images ()
{
  echo "create_images()"

  local DEST=$1
  local TYPE=$2
  local LOW=0
  local HIGH=5000
  local STEP=0
  local TMP=0

  while read object; do
    if [ -e $object ] && [ `sort -t'/' -k1n -k2n -k3n $object | grep -E ^2 | tail -n 1 | cut -d' ' -f2` ]; then
      let TMP=`sort -t'/' -k1n -k2n -k3n $object | grep -E ^2 | tail -n 1 | cut -d' ' -f2`
      let TMP=$TMP*16/10
      STEP=100
      HIGH=0
      while [ $HIGH -eq 0 ]; do
        if [ $TMP -lt $STEP ]; then
          HIGH=$STEP
        fi
        let STEP=$STEP*15/10
      done

      if [ "$TYPE" = "Footprint" ]; then
        object="${object%.size}"
      else
        object="${object%.txt}"
      fi

      gen_chart "${object##*/}" ${DEST} ${TYPE} ${LOW} ${HIGH} >/dev/null 2>&1
    fi
  done

}

###############################################################################
#
# create_index_page
#
###############################################################################
create_index_page ()
{
  local TYPE="$1"
  local TITLE="$TYPE metrics for $BASE_TITLE"

  echo "<html>"
  echo "<head><title>$TITLE</title></head>"
  echo '<style><!--'
  echo 'body,td,a,p,.h{font-family:arial,sans-serif;}'
  echo '.h{font-size: 20px;}'
  echo '.q{text-decoration:none; color:#0000cc;}'
  echo '//-->'
  echo '</style>'
  echo '<body text = "#000000" link="#000fff" vlink="#ff0f0f" bgcolor="#ffffff">'
  echo "<br><center><h1>$TITLE</h1></center><br><hr>"
  if [ $BASE_TITLE = $DEFAULT_TITLE ]; then
    echo '<p>We are measuring ACE+TAO+CIAO+DAnCE metrics daily.'
  else
    echo '<p>'
  fi
  echo '   Metrics are gathered nightly on all
           objects in the '$BASE_TITLE' distribution and displayed here.'
  echo '<ul>'
  if [ $BASE_TITLE = $DEFAULT_TITLE ]; then
    echo "<li><a href=\"ace_${TYPE}.html\">ACE</a>"
    echo "<li><a href=\"tao_${TYPE}.html\">TAO</a>"
    echo "<li><a href=\"ciao_${TYPE}.html\">CIAO</a>"
    echo "<li><a href=\"dance_${TYPE}.html\">DAnCE</a>"
  else
    echo "<li><a href=\"all_${TYPE}.html\">ALL</a>"
  fi
  echo '</ul>'
  echo '<hr>'

  echo '<P>All the experiments run on the system described below. '
  echo 'The machine is running Linux ('

  if [ -e "/etc/SuSE-release" ]; then
    cat /etc/SuSE-release
  fi

  if [ -e "/etc/redhat-release" ]; then
    cat /etc/redhat-release
  fi

  echo "), and we use " $COMPILER " version "

  $COMPILER -dumpversion > ${DEST}/compilerversion.txt 2>&1
  cat ${DEST}/compilerversion.txt

  echo ' to compile '$BASE_TITLE'. </P>'

  if [ -z "$MPC_ROOT" ]; then
    MPC_ROOT=$ACE_ROOT/MPC
  fi

  CFG_FILES=$ACE_ROOT/ace/config.h
  if [ -r $ACE_ROOT/bin/MakeProjectCreator/config/default.features ]; then
    CFG_FILES="$CFG_FILES $ACE_ROOT/bin/MakeProjectCreator/config/default.features"
  elif [ -r $MPC_ROOT/config/default.features ]; then
    CFG_FILES="$CFG_FILES $MPC_ROOT/config/default.features"
  fi
  CFG_FILES="$CFG_FILES $ACE_ROOT/include/makeinclude/platform_macros.GNU"

  echo '<TABLE border="2"><TBODY>'
  for cfg_file in $CFG_FILES; do
    if [ -r $cfg_file ]; then
      echo "<TR><TD>ACE+TAO+CIAO+DAnCE Configuration</TD><TD>`basename $cfg_file`</TD></TR>"
      echo '<TR><TD colspan="2"><PRE>'
      cat $cfg_file
      echo '</PRE></TD></TR>'
    fi
  done

  echo '<TR><TD>CPU Information</TD><TD>/proc/cpuinfo</TD></TR>'
  echo '<TR><TD colspan="2"><PRE>'

  cat /proc/cpuinfo

  echo '</PRE></TD></TR><TR><TD>Available Memory</TD><TD>/proc/meminfo</TD></TR>'
  echo '<TR><TD colspan="2"><PRE>'

  cat /proc/meminfo

  echo '</PRE></TD></TR><TR><TD>OS Version</TD><TD>uname -a</TD></TR>'
  echo '<TR><TD colspan="2"><PRE>'

  /bin/uname -a

  echo '</PRE></TD></TR><TR><TD>Compiler Version</TD><TD>'$COMPILER' -v</TD></TR>'
  echo '<TR><TD colspan="2">'

  $COMPILER -v > ${DEST}/compiler.txt 2>&1
  cat ${DEST}/compiler.txt

  if [ -e "/lib/libc.so.6" ]; then
    echo '</TD></TR><TR><TD>Library Version</TD><TD>/lib/libc.so.6</TD></TR>'
    echo '<TR><TD colspan="2"><PRE>'

    /lib/libc.so.6 | sed -e 's/</\</g' -e 's/>/\>/g'
  fi

  echo '</PRE></TD></TR></TBODY></TABLE>'
  echo '</body></html>'
}

###############################################################################
#
# create_page
#
###############################################################################
create_page ()
{
  # always strip off "ACE___" / "TAO___" / "CIAO___"
  local BASE=$1
  local TYPE=$2
  local EXT=""
  local BASE_NAME=${BASE#ACE___}
  local BASE_NAME=${BASE#TAO___}
  local BASE_NAME=${BASE#CIAO___}
  local BASE_NAME=${BASE#DAnCE___}
  local TITLE="${TYPE} metrics for ${BASE_NAME//___//}"

  if [ "$TYPE" = "Compilation" ]; then
    EXT="txt"
    UNITS="100th's of seconds"
  else
    EXT="size"
    UNITS="Bytes"
  fi

  # header
  echo "<html>"
  echo "<head><title>$TITLE</title></head>"
  echo '<style><!--'
  echo 'body,td,a,p,.h{font-family:arial,sans-serif;}'
  echo '.h{font-size: 20px;}'
  echo '.q{text-decoration:none; color:#0000cc;}'
  echo '//-->'
  echo '</style>'
  echo '<body text = "#000000" link="#000fff" vlink="#ff0f0f" bgcolor="#ffffff">'
  echo "<br><center><h1>$TITLE</h1></center><br>"
  if [ -e "${DEST}/images/${BASE}_${TYPE}.png" ]; then
    echo '<DIV align="center"><P>'
    echo "<IMG alt=\"$BASE\" border=0 src=\"images/${BASE}_${TYPE}.png\""
    echo 'width="800" height="600"></P></DIV>'
  fi

  echo "<br><hr><br>"
  echo "<center><h2>Detail (${DATE})</h2></center>"

  echo '<TABLE border="2"><TBODY><TR><TD rowspan=2><b>Object</b></TD>'
  echo '<TD colspan="4" align=center><b>Last Compile</b></TD></TR>'
  echo "<TR><TD align=center><b>Date</b></TD><TD align=center><b>$UNITS</b></TD>"
  echo '<TD align=center><b>%chg</b></TD><TD align=center><b>Data</b></TD></TR>'
  while read i; do
    if [ -e "${DEST}/data/${i}.${EXT}" ]; then
      LAST=0 PRE=0 VAL_TMP=0 VAL_INT=0 VAL_SIGN="+"
      echo '<TR><TD>'
      if [ -e "${DEST}/${i}_${TYPE}.html" ]; then
        # strip off "ACE___" if it exists
        NAME=${i#ACE___}
        # strip off "TAO___" if it exists
        NAME=${i#TAO___}
        # strip off "CIAO___" if it exists
        NAME=${i#CIAO___}
        # strip off "DAnCE___" if it exists
        NAME=${i#DAnCE___}
        echo "<a href=\"${i}_${TYPE}.html\">${NAME//___//}</a>"
      elif [ -e "${DEST}/images/${i}_${TYPE}.png" ]; then
        # since you'll only have images if it's a composite, strip off the
        # path for the name
        if [ "$TYPE" = "Footprint" ]; then
          # if we are doing footprint, add library
          llib=`grep -e "lib.*\.a" ${DEST}/size_composites.txt | grep ${i} | awk '{print $1}'`
          #echo "lib $llib"
          #llib="${llib% :}"
          llib="${llib//___//}"
          NAME="${llib}(${i##*___})"
        else
          NAME="${i##*___}"
        fi
        echo "<a href=\"images/${i}_${TYPE}.png\">${NAME}</a>"
      else
        echo "${i##*___}"
      fi
      echo '</TD><TD>'
      echo `sort -t'/' -k1n -k2n -k3n  ${DEST}/data/${i}.${EXT} | grep -E ^2 | tail -n1  | cut -d" " -f1`
      let LAST=`sort -t'/' -k1n -k2n -k3n ${DEST}/data/${i}.${EXT} | grep -E ^2 | tail -n1 | cut -d" " -f2`
      echo "</TD><TD align=right>$LAST</TD>"
      let PRE=`sort -t'/' -k1n -k2n -k3n ${DEST}/data/${i}.${EXT} | grep -E ^2 | tail -n2 | head -n1 | cut -d" " -f2`
      let VAL_TMP="((($LAST+1)-($PRE+1))*1000)/($PRE+1)"
      if [ $VAL_TMP -lt 0 ]; then
        VAL_SIGN="-"
        let VAL_TMP="-1*$VAL_TMP"
      elif [ $VAL_TMP -eq 0 ]; then
        VAL_SIGN=
      fi
      let VAL_INT="$VAL_TMP/10"
      let VAL_TENTH="$VAL_TMP-($VAL_INT*10)"
      echo "<TD align=right>${VAL_SIGN}${VAL_INT}.${VAL_TENTH}</TD>"
      echo "<TD align=right><a href=\"data/${i}.${EXT}\">Data</a></TD>"
      echo "</TR>"
    else
      echo '<TR><TD>'
      echo "${i}"
      echo '</TD><TD>'
      echo '?'
      echo "</TD><TD align=right>?</TD>"
      echo "<TD align=right>?</TD><TD align=right>?</TD></TR>"
    fi
  done # for
  echo '</TBODY></TABLE>'

  # footer
  echo '</body></html>'

}

###############################################################################
#
# sort_list
#
###############################################################################
sort_list ()
{
  # sort the dependency files
  if [ -e ${DEST}/tmp_list ]; then
    rm ${DEST}/tmp_list
  fi

  touch ${DEST}/tmp_list
  for i in $@; do
    echo "$i" >> ${DEST}/tmp_list
    #echo $i
  done

  sort -f ${DEST}/tmp_list
}

###############################################################################
#
# create_html
#
###############################################################################
create_html ()
{
  echo "create_html()"

  local DEST=$1
  local TYPE=$2
  local ALL_OBJS=""
  local ACE_OBJS=""
  local TAO_OBJS=""
  local CIAO_OBJS=""
  local DAnCE_OBJS=""

  while read base colon files; do
    # create individual page for app/lib

    sort_list ${files} | create_page ${base} ${TYPE} \
      > ${DEST}/${base}_${TYPE}.html
    if [ "${base}" != "${base#DAnCE}" ]; then
      DAnCE_OBJS="${DAnCE_OBJS} ${base}"
    elif [ "${base}" != "${base#CIAO}" ]; then
      CIAO_OBJS="${CIAO_OBJS} ${base}"
    elif [ "${base}" != "${base#TAO}" ]; then
      TAO_OBJS="${TAO_OBJS} ${base}"
    elif [ "${base}" != "${base#ACE}" ]; then
      ACE_OBJS="${ACE_OBJS} ${base}"
    fi
    ALL_OBJS="${ALL_OBJS} ${base}"
  done

  # create main page
  create_index_page ${TYPE} > ${DEST}/index.html

  if [ "${TYPE}" = "Compilation" ] || [ "${TYPE}" = "Footprint" ]; then
    if [ $BASE_TITLE = $DEFAULT_TITLE ]; then
      name="ace_${TYPE}.html"
      sort_list ${ACE_OBJS} | create_page "ACE" ${TYPE} > ${DEST}/${name}

      name="tao_${TYPE}.html"
      sort_list ${TAO_OBJS} | create_page "TAO" ${TYPE} > ${DEST}/${name}

      name="ciao_${TYPE}.html"
      sort_list ${CIAO_OBJS} | create_page "CIAO" ${TYPE} > ${DEST}/${name}

      name="dance_${TYPE}.html"
      sort_list ${DAnCE_OBJS} | create_page "DAnCE" ${TYPE} > ${DEST}/${name}
    else
      name="all_${TYPE}.html"
      sort_list ${ALL_OBJS} | create_page $BASE_TITLE ${TYPE} > ${DEST}/${name}
    fi
  fi
}

###############################################################################
#
# main program
#
###############################################################################

INFILE=""
DEST=""
TARGETS=""
DATE=""
METRIC="Compilation"
FUDGE_FACTOR=0
BASE_ROOT=$ACE_ROOT
DEFAULT_TITLE=ACE+TAO+CIAO+DAnCE
BASE_TITLE=$DEFAULT_TITLE
COMPILER="gcc"

parse $@
create_dirs "${DEST}/"
create_dirs "${DEST}/"

if [ "$METRIC" = "Compilation" ]; then

  ########################################################
  # compile times

  # grab the compile time metrics for objects only and process them
  grep "compile time(0):" $INFILE | grep "\.o" | cut -d' ' -f3,4,5 | process_file

  # Create ${DEST}/composites.txt with entries like this:
  # tests___OS_Test :  tests___OS_Test.o tests___Main.o
  create_composite_list $TARGETS

  # compile times
  cat ${DEST}/composites.txt | rollup_compile_times
  find ${DEST}/data/ -name "*.txt" | create_images ${DEST} "Compilation"
  cat ${DEST}/composites.txt | create_html ${DEST} "Compilation"

elif [ "$METRIC" = "Footprint" ]; then

  ########################################################
  # footprint

  # Create ${DEST}/libraries.txt with entries like this:
  # ace___libACE.a
  create_library_list $TARGETS

  # Create ${DEST}/composites.txt with entries like this:
  # tests___OS_Test :  tests___OS_Test.o tests___Main.o
  create_composite_list $TARGETS

  # Run size on the executables and append results to *.size file.
  cat ${DEST}/composites.txt | footprint

  # Run size on the libraries and append results to *.size for the
  # library and each contained object.
  # It also creates ${DEST}/size_composites.txt based on size output for
  # libraries with entries like this:
  # ace___libACE.a : ace___ACE.o ace___Addr.o
  cat ${DEST}/libraries.txt | footprint LIB

  # Add executables to ${DEST}/size_composites.txt based on output
  # from the map files (created with LDFLAGS=-Xlinker -M -Xlinker
  # -Map -Xlinker $(@).map).  Find the map files of we want based on
  # entries in ${DEST}/composites.txt.
  cat ${DEST}/composites.txt | create_size_composites

  find ${DEST}/data/ -name "*.size" | create_images ${DEST} "Footprint"
  cat ${DEST}/size_composites.txt | create_html ${DEST} "Footprint"

else
  echo "metric type ($METRIC) not recognized"
  usage
fi


#!/bin/sh
#

gnuplot <<_EOF_ >/dev/null 2>&1
  set xdata time
  set xtics rotate
  set timefmt '%Y/%m/%d-%H:%M'
  set xlabel 'Date (MM/DD)'  0,-3
  set ylabel 'Size (KBytes)'
  set terminal png small size 1024,768 color
  set output "$2"
  plot '$1' using 1:(\$2/1024.0) title '$3' w l
  exit
_EOF_


#!/bin/sh
#

gnuplot <<_EOF_ >/dev/null 2>&1
    set xdata time
    set xtics rotate
    set format x "%Y/%m/%d"
    set timefmt '%Y/%m/%d-%H:%M'
    set xlabel 'Date (YYYY/MM/DD)' 0,-3
    set ylabel 'Throughput (Requests/Second)'
    set terminal png small size $4 color
    set yrange [0:]
    set output "$2"
    plot '$1' using 1:2 title '$3' w l
    exit
_EOF_


#!/bin/sh

gnuplot <<_EOF_ >/dev/null 2>&1
  set xdata time
  set xtics rotate
  set timefmt '%Y/%m/%d-%H:%M'
  set xlabel 'Date (MM/DD)'
  set ylabel 'Size (KBytes) $4'
  set terminal png small size 800,600 color
  set output "$2"
  plot '$1' using 1:2 title '$3' w l
  exit
_EOF_


#!/bin/sh

if test -e tmp; then unlink tmp; fi
if test -e tmp2; then unlink tmp2; fi
cat t.txt | grep '+[a-z|A-Z]' > tmp
sort tmp | uniq -c > tmp2
unlink tmp
sort -n -r tmp2 > uniq.txt
unlink tmp2
cat uniq.txt


#!/bin/sh

if test -z $1; then CURRENTDATE=`date -u +%Y_%m_%d`; else CURRENTDATE=$1; fi
if test -z $2; then PREFIX=`date -u +%Y%m%d%a`; else PREFIX=$2; fi
if test -z $3; then MAILTO="devo-group@list.isis.vanderbilt.edu"; else MAILTO=$3; fi

cd $ACE_ROOT/bin

./diff-builds-and-group-fixed-tests-only.sh $CURRENTDATE $PREFIX
./cleanbuilds.sh $CURRENTDATE

MAIL="mail -S smtp=mail.remedy.nl"
MAILFROM="jwillemsen@remedy.nl"

MAIL_ATTACHMENTS=
for fn in `ls *Tests.txt`; do
   MAIL_ATTACHMENTS=$MAIL_ATTACHMENTS+"-a $fn "
done
for fn in `ls *NoTestRev.txt`; do
   MAIL_ATTACHMENTS=$MAIL_ATTACHMENTS+"-a $fn "
done
mailfile="/tmp/rsmailfile"
{
   echo "Sending test statistics for" $CURRENTDATE
   echo
   cat *NoTestRev.txt
   echo
   echo "Sending with revision number"
   cat *Tests.txt
   echo
   echo "Sending results per build"
   cat *Builds.txt
} > $mailfile

$MAIL -v -r $MAILFROM -s "ACE/TAO/CIAO/DAnCE test statistics for $CURRENTDATE" $MAILTO < $mailfile

rm -f $mailfile

mailfile="/tmp/rsmailfile"
{
   echo "Sending failing tests for " $CURRENTDATE
   echo
   cat cleanbuildresults.txt
} > $mailfile

$MAIL -v -r $MAILFROM -s "ACE/TAO/CIAO/DAnCE failing tests for $CURRENTDATE" $MAILTO < $mailfile

rm -f $mailfile


#!/bin/sh
#

if [ $# -lt 1 ]; then
  echo "Usage: $0 <DEST>"
  exit 0
fi

DEST=$1
DATE=`date +%Y/%m/%d-%H:%M`

mkdir -p $DEST/images
mkdir -p $DEST/data
mkdir -p $DEST/source
COMPILER="gcc"

COMMON_TESTS="AMI DII DSI Deferred Single_Threaded Thread_Per_Connection Thread_Pool AMH_Single_Threaded"

SEQUENCE_TESTS="AMI DII DSI Deferred Single_Threaded Thread_Per_Connection Thread_Pool AMH_Single_Threaded"

SEQ_TEST_TYPE="octet long short char double longlong"

cd $DEST/source

/bin/sync
sleep 10
(
  cd $ACE_ROOT/performance-tests/TCP;
  ./run_test.pl
) >tcp_test.log 2>&1

if grep -q 'Client throughput: ' tcp_test.log; then
  (
    echo -n $DATE " ";
    awk '/^Client throughput:/ {print $3}' tcp_test.log
  ) >> TCP.txt;
fi

/bin/sync
sleep 10
(
   cd $TAO_ROOT/performance-tests/Latency/Single_Threaded;
   ./default_configuration.pl > $DEST/source/Default.log 2>&1
)
if grep -q 'Total throughput: ' Default.log; then
  (
    echo -n $DATE " ";
    awk '/^Total throughput:/ {print $3}' Default.log
  ) >> Default.txt
fi

/bin/sync
sleep 2
(
   cd $TAO_ROOT/performance-tests/Sequence_Latency/Single_Threaded;

   for i in $SEQ_TEST_TYPE; do
     (
       ./default_configuration.pl -t $i > $DEST/source/Sequence_Default_${i}.log 2>&1
       if grep -q 'Total throughput: ' $DEST/source/Sequence_Default_${i}.log; then
         (
           echo -n $DATE " ";
           awk '/^Total throughput:/ {print $3}' $DEST/source/Sequence_Default_${i}.log
         ) >> $DEST/source/Sequence_Default_${i}.txt
       fi
     )
   done

)

for i in $COMMON_TESTS; do
  /bin/sync
  sleep 10
  (
     cd $TAO_ROOT/performance-tests/Latency/${i};
     ./run_test.pl > $DEST/source/${i}.log 2>&1
  )
  if grep -q 'Total throughput: ' ${i}.log; then
    (
       echo -n $DATE " ";
       awk '/^Total throughput:/ {print $3}' $DEST/source/${i}.log
    ) >> ${i}.txt
  fi
done

for i in $SEQUENCE_TESTS; do
  /bin/sync
  sleep 10
  (
     cd $TAO_ROOT/performance-tests/Sequence_Latency/${i};
     for j in $SEQ_TEST_TYPE; do
         (
             ./run_test.pl -t $j > $DEST/source/Sequence_${i}_${j}.log 2>&1

             if grep -q 'Total throughput: ' $DEST/source/Sequence_${i}_${j}.log; then
                 (
                     echo -n $DATE " ";
                     awk '/^Total throughput:/ {print $3}' $DEST/source/Sequence_${i}_${j}.log
                 ) >> $DEST/source/Sequence_${i}_${j}.txt
             fi
         )
     done
  )

done

for i in $COMMON_TESTS TCP Default; do
  $ACE_ROOT/bin/generate_performance_chart.sh ${i}.txt ${i}.png "$i" 1024,768
  /bin/cp ${i}.png $DEST/images/${i}.png
  /usr/bin/tac ${i}.txt > $DEST/data/${i}.txt
  /usr/bin/tail -5 ${i}.txt > $DEST/data/LAST_${i}.txt
done

for i in $SEQ_TEST_TYPE ; do
  $ACE_ROOT/bin/generate_performance_chart.sh Sequence_Default_${i}.txt Sequence_Default_${i}.png "Default Configuration for $i sequences" 1024,768
  /bin/cp Sequence_Default_${i}.png $DEST/images/Sequence_Default_${i}.png
  /usr/bin/tac $DEST/source/Sequence_Default_${i}.txt > $DEST/data/Sequence_Default_${i}.txt
  /usr/bin/tail -5 $DEST/source/Sequence_Default_${i}.txt > $DEST/data/LAST_Sequence_Default_${i}.txt
done

for i in $SEQUENCE_TESTS; do
for j in $SEQ_TEST_TYPE; do
  $ACE_ROOT/bin/generate_performance_chart.sh Sequence_${i}_${j}.txt Sequence_${i}_${j}.png "Sequence_$i_$j" 1024,768
  /bin/cp Sequence_${i}_${j}.png $DEST/images/Sequence_${i}_${j}.png
  /usr/bin/tac Sequence_${i}_${j}.txt > $DEST/data/Sequence_${i}_${j}.txt
  /usr/bin/tail -5 Sequence_${i}_${j}.txt > $DEST/data/LAST_Sequence_${i}_${j}.txt
done
done

gnuplot <<_EOF_ >/dev/null 2>&1
    set xdata time
    set timefmt '%Y/%m/%d-%H:%M'
    set xlabel 'Date (YYYYMMDD)'
    set xtics rotate
    set ylabel 'Throughput (Requests/Second)'
    set yrange [0:]
    set terminal png small size 1024,768 color
    set output "/dev/null"
    plot 'AMI.txt' using 1:2 title 'AMI' w l
    replot 'DII.txt' using 1:2 title 'DII' w l
    replot 'DSI.txt' using 1:2 title 'DSI' w l
    replot 'Deferred.txt' using 1:2 title 'Deferred' w l
    replot 'Single_Threaded.txt' using 1:2 title 'Single_Threaded' w l
    replot 'Default.txt' using 1:2 title 'Single_Threaded (Defaults)' w l
    replot 'Thread_Per_Connection.txt' using 1:2 title 'Thread_Per_Connection' w l
    replot 'Thread_Pool.txt' using 1:2 title 'Thread_Pool' w l
    replot 'AMH_Single_Threaded.txt' using 1:2 title 'AMH' w l
    replot 'TCP.txt' using 1:2 title 'TCP/IP' w l
    set output "All.png"
    replot
    exit
_EOF_

gnuplot <<_EOF_ >/dev/null 2>&1
    set xdata time
    set timefmt '%Y/%m/%d-%H:%M'
    set xlabel 'Date (YYYYMMDD)'
    set xtics rotate
    set ylabel 'Throughput (Requests/Second)'
    set yrange [0:]
    set terminal png small size 1024,768 color
    set output "/dev/null"
    plot 'AMI.txt' using 1:2 title 'AMI' w l
    replot 'DII.txt' using 1:2 title 'DII' w l
    replot 'DSI.txt' using 1:2 title 'DSI' w l
    replot 'Deferred.txt' using 1:2 title 'Deferred' w l
    replot 'Single_Threaded.txt' using 1:2 title 'Single_Threaded' w l
    replot 'Default.txt' using 1:2 title 'Single_Threaded (Defaults)' w l
    replot 'Thread_Per_Connection.txt' using 1:2 title 'Thread_Per_Connection' w l
    replot 'Thread_Pool.txt' using 1:2 title 'Thread_Pool' w l
    replot 'AMH_Single_Threaded.txt' using 1:2 title 'AMH' w l
    set output "CORBA.png"
    replot
    exit
_EOF_

/bin/cp CORBA.png All.png $DEST/images/

cd $DEST/data
/bin/uname -a > uname.txt
$COMPILER -v > gcc.txt 2>&1
$COMPILER -dumpversion > gccversion.txt 2>&1
/lib/libc.so.6 | sed -e 's/</\</g' -e 's/>/\>/g' > libc.txt
cat /proc/cpuinfo > cpuinfo.txt
cat /proc/meminfo > meminfo.txt
if [ -e "/etc/SuSE-release" ]; then
  cat /etc/SuSE-release > linuxversion.txt
fi
if [ -e "/etc/redhat-release" ]; then
  cat /etc/redhat-release > linuxversion.txt
fi
if [ -e "/etc/fedora-release" ]; then
  cat /etc/fedora-release > linuxversion.txt
fi

cat $ACE_ROOT/ace/config.h > config.h.txt
cat $ACE_ROOT/include/makeinclude/platform_macros.GNU > platform_macros.GNU.txt
cat $ACE_ROOT/bin/MakeProjectCreator/config/default.features > default.features.txt
cp $ACE_ROOT/html/Stats/* $DEST


#!/bin/sh
#

if [ $# -lt 3 ]; then
  echo "Usage: $0 [DEST] [USER] [OPTIMIZED]"
  exit 0
fi

DEST=$1
US=$2
OPT=$3

DATE=`date +%Y/%m/%d-%H:%M`
cd $ACE_ROOT
LD_LIBRARY_PATH=$ACE_ROOT/ace
export LD_LIBRARY_PATH
PATH=/usr/bin:/bin:$PATH
export PATH
cd $TAO_ROOT/performance-tests/Memory/IORsize

# start the server. If OPT == 1 then start the optimized version, else
# the non-optimized version

if test $OPT == 1
    then ./server -ORBSvcConf server.conf &
    else ./server &
fi

s_id=$!;

server_start_size=`cat /proc/$s_id/status | grep VmRSS | awk '{print $2}'`;

# Just sleep for 2 seconds.
sleep 2;
# Check whether the server has started
file="test.ior"
if test -f $file
    then
    # start the client
    ./client &
    c_id=$!;
    # Wait till all the invocations are done
    sleep 30;
    # Get the size once the client has made sufficient invocations.
    s_invocations=`cat /proc/$s_id/status  | grep VmRSS | awk '{print $2}'`;
    let "actual_server_growth=${s_invocations}-${server_start_size}";
    if test $OPT == 1
        then
        echo $DATE $s_invocations >> $DEST/source/server_opt_ior_size.txt
        echo $DATE $actual_server_growth >> $DEST/source/opt_ior_size.txt
        else
        echo $DATE $s_invocations >> $DEST/source/server_ior_size.txt
        echo $DATE $actual_server_growth >> $DEST/source/actual_ior_size.txt
    fi

    # Kill the server and client. We will look at better ways of doing
    # this later.
    kill -9 $c_id;
    kill -9 $s_id;
    rm -f $file
else
    echo $file doesnt exist
fi

cd $DEST/source
STRING="for 50000 IORs"
FILES="server_opt opt server actual"
for i in $FILES ; do
/usr/bin/tac ${i}_ior_size.txt > $DEST/data/${i}_ior_size.txt
/usr/bin/tail -5 ${i}_ior_size.txt > $DEST/data/LAST_${i}_ior_size.txt
$ACE_ROOT/bin/generate_topinfo_charts.sh ${i}_ior_size.txt $DEST/images/${i}_ior_size.png ${i}_ior_size.txt
done


#!/bin/sh
#

if [ $# -lt 2 ]; then
  echo "Usage: $0 [DEST] [USER]"
  exit 0
fi

DEST=$1
US=$2

DATE=`date +%Y/%m/%d-%H:%M`
cd $ACE_ROOT
LD_LIBRARY_PATH=$ACE_ROOT/ace
export LD_LIBRARY_PATH
PATH=/usr/bin:/bin:$PATH
export PATH
cd $TAO_ROOT/performance-tests/Memory/Single_Threaded
# start the server
./server &
s_id=$!;
# Just sleep for 2 seconds.
sleep 2;
# Check whether the server has started
file="test.ior"
if test -f $file
    then
    # Just get the size as soon the server is started, ie. the vanilla
    # server.
    s_up=`cat /proc/$s_id/status | grep VmRSS | awk '{print $2}'`;

    # Write it a file
    echo $DATE $s_up >> $DEST/source/st_start_size.txt
    # start the client
    ./client &
    c_id=$!;
    # Wait till all the invocations are done
    sleep 10;
    # Get the size once the client has made sufficient invocations.
    s_invocations=`cat /proc/$s_id/status | grep VmRSS| awk '{print $2}'`;

    echo $DATE $s_invocations >> $DEST/source/st_after_invoke_size.txt

    # Get teh size of the client after all the invocations
    c_invocations=`cat /proc/$c_id/status | grep VmRSS | awk '{print $2}'`;
    echo $DATE $c_invocations >> $DEST/source/st_client_size.txt

    # Kill the server and client. We will look at better ways of doing
    # this later.
    kill -9 $c_id;

    # Just sleep for the server to release memory etc.
    sleep 5;

    # Get the size once the client is killed or crashed
    s_client_death=`cat /proc/$s_id/status | grep VmRSS | awk '{print $2}'`;
    echo $DATE $s_client_death  >> $DEST/source/st_after_peer_death_size.txt
    kill -9 $s_id;
    rm -f $file
else
    echo $file doesnt exist
fi

cd $DEST/source

FILES="start after_invoke client after_peer_death"
for i in $FILES ; do
/usr/bin/tac st_${i}_size.txt > $DEST/data/st_${i}_size.txt
/usr/bin/tail -5 st_${i}_size.txt > $DEST/data/LAST_st_${i}_size.txt
$ACE_ROOT/bin/generate_topinfo_charts.sh st_${i}_size.txt $DEST/images/st_${i}_size.png st_${i}_size.txt
done


#!/bin/sh
#

if [ $# -lt 2 ]; then
  echo "Usage: $0 [DEST] [USER]"
  exit 0
fi

DEST=$1
US=$2

DATE=`date +%Y/%m/%d-%H:%M`
cd $ACE_ROOT
LD_LIBRARY_PATH=$ACE_ROOT/ace
export LD_LIBRARY_PATH
PATH=/usr/bin:$PATH
export PATH
cd $TAO_ROOT/performance-tests/Memory/Single_Threaded
# start the server
./server &
s_id=$!;
# Just sleep for 2 seconds.
sleep 2;
# Check whether the server has started
file="test.ior"
if test -f $file
    then
    # Just get the size as soon the server is started, ie. the vanilla
    # server.
    s_up=`top -p $s_id -n 1 -b | grep $US| awk '{print $5}'`;

    # Write it a file
    echo $DATE $s_up >> $DEST/source/st_start_size.txt
    # start the client
    ./client &
    c_id=$!;
    # Wait till all the invocations are done
    sleep 10;
    # Get the size once the client has made sufficient invocations.
    s_invocations=`top -p $s_id -n 1 -b | grep $US| awk '{print $5}'`;

    echo $DATE $s_invocations >> $DEST/source/st_after_invoke_size.txt

    # Kill the server and client. We will look at better ways of doing
    # this later.
    kill -9 $c_id;

    # Just sleep for the server to release memory etc.
    sleep 5;

    # Get the size once the client is killed or crashed
    s_client_death=`top -p $s_id -n 1 -b | grep $US| awk '{print $5}'`;
    echo $DATE $s_client_death  >> $DEST/source/st_after_peer_death_size.txt
    kill -9 $s_id;
    rm -f $file
else
    echo $file doesnt exist
fi

cd $DEST/source
STRING=""
FILES="start after_invoke after_peer_death"
for i in $FILES ; do
/usr/bin/tac st_${i}_size.txt > $DEST/data/st_${i}_size.txt
/usr/bin/tail -5 st_${i}_size.txt > $DEST/data/LAST_st_${i}_size.txt
$ACE_ROOT/bin/generate_topinfo_charts.sh st_${i}_size.txt $DEST/images/st_${i}_size.png st_${i}_size.txt $STRING
done


#!/bin/sh
#
# This script compares autoconf-based installation against regular builds
# provided files.
#
# This script should be run after `make install DESTDIR=debian/tmp' has been
# run on autoconf-based build.
#

set -e

P1=ACE_wrappers
P2=debian/tmp/usr/include

# Find files
# ff <from>
ff() {
  find "$1" -name '*.h' -o -name '*.inl' -o -name '*.hpp' -o -name '*.ipp'
}

# Remove path with examples, tests and tutorial from STDIN
drop() {
  grep -E -v '(examples|tests|tutorials)/'
}

# Removed unused/unshipped stuff
unused() {
  grep -E -v '^/(ASNMP|TAO_IDL|ace/QoS|apps|contrib|utils)'
}

F1=`mktemp -t ace_regular.XXXXXXXXXX`
F2=`mktemp -t ace_autoconf.XXXXXXXXXX`
trap "rm $F1 $F2" 0

ff $P1 | sed -e "s@$P1@@" -e "s@/TAO@@" -e "s@/protocols@@" -e "s@^/orbsvcs@@" | drop | unused | sort >> $F1
ff $P2 | sed -e "s@$P2@@" | sort >> $F2
diff -u $F1 $F2


#!/bin/sh
#
# This script regenerates changes on the Doxygen templates.
#
silent_nothing_to_do() {
    test $? -eq 2 || false
}

set -e
export QUILT_PATCHES=debian/patches

quilt pop -a || silent_nothing_to_do
quilt delete reduce-doxygen-doc.diff
quilt new reduce-doxygen-doc.diff

for f in $(find $ACE_ROOT -name '*.doxygen')
do
    QUILT_PATCHES=debian/patches quilt add $f
    sed -e 's#COLLABORATION_GRAPH    = YES#COLLABORATION_GRAPH    = NO#' \
        -e 's#SEARCHENGINE           = YES#SEARCHENGINE           = NO#' \
        -e 's#DOT_GRAPH_MAX_NODES    = 50#DOT_GRAPH_MAX_NODES     = 15#' \
< $f > $f.new

    mv $f.new $f
done

quilt refresh --no-timestamps --no-index


#! /bin/sh
#
# Spawns CPP-inserver-fancy and CPP-inclient executables on a single host.

usage="usage: $0 #client_threads"

user=`whoami`
iterations=1000

if [ $# -ne 1 ]; then
  echo $usage;
  exit 1
fi
threads=$1;

########
######## Enable signal handler.
########
trap 'kill -1 $server_pid; ' 0 1 2 15

########
######## Start CPP-inserver-fancy and save its pid.
########
./CPP-inserver-fancy > \
  ${tmp}server.log 2>&1 &
server_pid=$!

sleep 2;

########
######## Start CPP-inclient.
########
./CPP-inclient -2 -T 100000 -m 69 -t $threads -i 100  > ${tmp}client-${threads}.log 2>&1


#!/bin/sh

# ******************************************************************
#      Author: Chad Elliott
#        Date: 8/13/2009
# Description: Create an MPC rpm based on the current version number.
# ******************************************************************

## First find out where this script is located
if [ "$0" != "`basename $0`" ]; then
  if [ "`echo $0 | cut -c1`" = "/" ]; then
    loc="`dirname $0`"
  else
    loc="`pwd`/`dirname $0`"
  fi
else
  ## Do my own 'which' here
  loc="."
  for i in `echo $PATH | tr ':' '\012'`; do
    if [ -x "$i/$0" -a ! -d "$i/$0" ]; then
      loc="$i"
      break
    fi
  done
fi

## Now, get back to where the main MPC script is located
while [ ! -x $loc/mpc.pl ]; do
  loc=`dirname $loc`
done

## Build up the packager name and email address
if [ -z "$REPLYTO" ]; then
  DOMAIN=`hostname | sed 's/[^\.][^\.]*\.//'`
  FULLDOMAIN=`echo $DOMAIN | grep '\.'`
  if [ -z "$DOMAIN" -o -z "$FULLDOMAIN" ]; then
    RESOLVDOMAIN=`grep '^search' /etc/resolv.conf | sed 's/.*\s//'`
    FULLDOMAIN=`echo $RESOLVDOMAIN | grep '\.'`
    if [ -z "$DOMAIN" -o -n "$FULLDOMAIN" ]; then
      DOMAIN=$RESOLVDOMAIN
    fi
  fi
  REPLYTO="$LOGNAME@$DOMAIN"
fi
PACKAGER=`getent passwd $LOGNAME | cut -d: -f5`
if [ -z "$PACKAGER" ]; then
  PACKAGER=$CL_USERNAME
fi
if [ -z "$PACKAGER" ]; then
  PACKAGER="<$REPLYTO>"
else
  PACKAGER="$PACKAGER <$REPLYTO>"
fi

## Save the MPC version
VERSION=`$loc/mpc.pl --version | sed 's/.*v//'`

## This is where we'll create the spec file and do the work
WDIR=/tmp/mpc.$$

## This is the directory name that RPM expects
MDIR=MPC-$VERSION

## This corresponds to BuildRoot in MPC.spec
BDIR=/tmp/mpc

## This is the final install directory and corresponds to the %files section
## of MPC.spec
FDIR=/usr/lib/MPC

##Check if build and work directory already exist
if [ -d "$BDIR" -o -f "$BDIR" ]; then
  echo "Necessary directory $BDIR already exists."
  echo "Exiting."
  exit
fi

if [ -d "$WDIR" -o -f "$WDIR" ]; then
  echo "Necessary directory $WDIR already exists."
  echo "Exiting."
  exit
fi

## Create our working directory
mkdir -p $WDIR

## The directory where RPM will place the resulting file
if [ -x /usr/src/redhat -a -w /usr/src/redhat ]; then
  RPMLOC=/usr/src/redhat
elif [ -x /usr/src/packages -a -w /usr/src/packages ]; then
  RPMLOC=/usr/src/packages
else
  RPMLOC=$WDIR/rpmbuild
  mkdir -p $RPMLOC
  mkdir -p $RPMLOC/BUILD
  mkdir -p $RPMLOC/RPMS
  mkdir -p $RPMLOC/SOURCES
fi

## Make the spec file
cd $WDIR
sed "s/VERSION/$VERSION/; s/PACKAGER/$PACKAGER/; s!FINALDIR!$FDIR!" $loc/rpm/MPC.templ > MPC.spec

## Make a copy of the original MPC source to the new directory
mkdir -p $MDIR/$FDIR
cd $loc
tar --exclude=.svn -cf - . | (cd $WDIR/$MDIR/$FDIR; tar -xf -)

## Create the build source tar.bz2
cd $WDIR
tar --owner root --group root -cf $RPMLOC/SOURCES/$MDIR.tar $MDIR
bzip2 -9f $RPMLOC/SOURCES/$MDIR.tar

## Perform the RPM creation step
rm -rf $BDIR
mkdir -p $BDIR
rpmbuild --define "_topdir $RPMLOC" --define "_buildrootdir $BDIR" --define "buildroot $BDIR" --define "__arch_install_post %{nil}" -bb MPC.spec

if [ "$RPMLOC" = "$WDIR/rpmbuild" ]; then
  echo "Copying rpm to $loc/rpm"
  cp $RPMLOC/RPMS/*/*.rpm $loc/rpm
fi

## Clean everything up
cd ..
rm -rf $WDIR $BDIR


#!/bin/sh
#

for s in 0 25 50 75 100; do
  for w in 1 2 3 4 5 6; do
    echo ================ WORK: $s 1>&2
    echo ================ THREADS: $w 1>&2
    ./Queue_Based_Workers/workers -m 100000 -b 100000 -s $s -w $w
    ./Leader_Follower/leader_follower -m 100000 -b 100000 -s $s -w $w
  done
done


#!/bin/sh
# Copyright 2019-2021 RenÃ© Ferdinand Rivera Morell
# Copyright (C) 2005, 2006 Douglas Gregor.
# Copyright (C) 2006 The Trustees of Indiana University
#
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt)

# boostinspect:notab - Tabs are required for the Makefile.

BJAM=""
TOOLSET=""
BJAM_CONFIG=""
BUILD=""
PREFIX=/usr/local
EPREFIX=
LIBDIR=
INCLUDEDIR=
LIBS=""
PYTHON=python
PYTHON_VERSION=
PYTHON_ROOT=
ICU_ROOT=

# Handle case where builtin shell version of echo command doesn't
# support -n.  Use the installed echo executable if there is one
# rather than builtin version to ensure -n is supported.
ECHO=`which echo`
if test "x$ECHO" = x; then
  ECHO=echo
fi

# Internal flags
flag_no_python=
flag_icu=
flag_show_libraries=

for option
do
    case $option in

    -help | --help | -h)
      want_help=yes ;;

    -prefix=* | --prefix=*)
      PREFIX=`expr "x$option" : "x-*prefix=\(.*\)"`
      ;;

    -exec-prefix=* | --exec-prefix=*)
      EPREFIX=`expr "x$option" : "x-*exec-prefix=\(.*\)"`
      ;;

    -libdir=* | --libdir=*)
      LIBDIR=`expr "x$option" : "x-*libdir=\(.*\)"`
      ;;

    -includedir=* | --includedir=*)
      INCLUDEDIR=`expr "x$option" : "x-*includedir=\(.*\)"`
      ;;

    -show-libraries | --show-libraries )
      flag_show_libraries=yes
      ;;

    -with-bjam=* | --with-bjam=* )
      BJAM=`expr "x$option" : "x-*with-bjam=\(.*\)"`
      ;;

    -with-icu | --with-icu )
      flag_icu=yes
      ;;

    -with-icu=* | --with-icu=* )
      flag_icu=yes
      ICU_ROOT=`expr "x$option" : "x-*with-icu=\(.*\)"`
      ;;

    -without-icu | --without-icu )
      flag_icu=no
      ;;

    -with-libraries=* | --with-libraries=* )
      library_list=`expr "x$option" : "x-*with-libraries=\(.*\)"`
      if test "$library_list" != "all"; then
          old_IFS=$IFS
          IFS=,
          for library in $library_list
          do
              LIBS="$LIBS --with-$library"

              if test $library = python; then
                  requested_python=yes
              fi
          done
          IFS=$old_IFS

          if test "x$requested_python" != xyes; then
              flag_no_python=yes
          fi
      fi
      ;;

    -without-libraries=* | --without-libraries=* )
      library_list=`expr "x$option" : "x-*without-libraries=\(.*\)"`
      old_IFS=$IFS
      IFS=,
      for library in $library_list
      do
          LIBS="$LIBS --without-$library"

          if test $library = python; then
              flag_no_python=yes
          fi
      done
      IFS=$old_IFS
      ;;

    -with-python=* | --with-python=* )
      PYTHON=`expr "x$option" : "x-*with-python=\(.*\)"`
      ;;

    -with-python-root=* | --with-python-root=* )
      PYTHON_ROOT=`expr "x$option" : "x-*with-python-root=\(.*\)"`
      ;;

    -with-python-version=* | --with-python-version=* )
      PYTHON_VERSION=`expr "x$option" : "x-*with-python-version=\(.*\)"`
      ;;

    -with-toolset=* | --with-toolset=* )
      TOOLSET=`expr "x$option" : "x-*with-toolset=\(.*\)"`
      ;;

    -*)
      { echo "error: unrecognized option: $option
Try \`$0 --help' for more information." >&2
      { (exit 1); exit 1; }; }
      ;;

    esac
done

if test "x$want_help" = xyes; then
  cat <<EOF
\`./bootstrap.sh\' builds the Boost build system B2 and prepares Boost for
building. This includes setting defaults in the project-config.jam which you
can adjust prior to invoking B2.

Usage: $0 [OPTION]...

Defaults for the options are specified in brackets.

Configuration:
  -h, --help                display this help and exit
  --with-bjam=BJAM          use existing Boost.Jam executable (bjam)
                            [automatically built]
  --with-toolset=TOOLSET    use specific TOOLSET to build B2 and as default
                            for building Boost
                            [automatically detected]
  --show-libraries          show the set of libraries that require build
                            and installation steps (i.e., those libraries
                            that can be used with --with-libraries or
                            --without-libraries), then exit
  --with-libraries=list     build only a particular set of libraries,
                            describing using either a comma-separated list of
                            library names or "all"
                            [all]
  --without-libraries=list  build all libraries except the ones listed []
  --with-icu                enable Unicode/ICU support in Regex
                            [automatically detected]
  --without-icu             disable Unicode/ICU support in Regex
  --with-icu=DIR            specify the root of the ICU library installation
                            and enable Unicode/ICU support in Regex
                            [automatically detected]
  --with-python=PYTHON      specify the Python executable [python]
  --with-python-root=DIR    specify the root of the Python installation
                            [automatically detected]
  --with-python-version=X.Y specify the Python version as X.Y
                            [automatically detected]

Installation directories:
  --prefix=PREFIX           install Boost into the given PREFIX
                            [/usr/local]
  --exec-prefix=EPREFIX     install Boost binaries into the given EPREFIX
                            [PREFIX]

More precise control over installation directories:
  --libdir=DIR              install libraries here [EPREFIX/lib]
  --includedir=DIR          install headers here [PREFIX/include]

EOF
fi
test -n "$want_help" && exit 0

my_dir=$(dirname "$0")

# Determine the toolset, if not already decided
if test "x$TOOLSET" = x; then
  guessed_toolset=`CXX= CXXFLAGS= $my_dir/tools/build/src/engine/build.sh --guess-toolset`
  case $guessed_toolset in
    acc | clang | gcc | como | mipspro | pathscale | pgi | qcc | vacpp )
    TOOLSET=$guessed_toolset
    ;;

    intel-* )
    TOOLSET=intel
    ;;

    mingw )
    TOOLSET=gcc
    ;;

    sun* )
    TOOLSET=sun
    ;;

    * )
    # Not supported by B2
    ;;
  esac
fi

rm -f config.log

# Build bjam
if test "x$BJAM" = x; then
  $ECHO "Building B2 engine.."
  pwd=`pwd`
  CXX= CXXFLAGS= "$my_dir/tools/build/src/engine/build.sh" ${TOOLSET}
  if [ $? -ne 0 ]; then
      echo
      echo "Failed to build B2 build engine"
      exit 1
  fi
  cd "$pwd"
  BJAM="$my_dir/tools/build/src/engine/b2"
  echo "tools/build/src/engine/b2"
  cp "$BJAM" .

fi

# TBD: Turn BJAM into an absolute path

# If there is a list of libraries
if test "x$flag_show_libraries" = xyes; then
  cat <<EOF

The following Boost libraries have portions that require a separate build
and installation step. Any library not listed here can be used by including
the headers only.

The Boost libraries requiring separate building and installation are:
EOF
  $BJAM -d0 --show-libraries | grep '^[[:space:]]*-'
  exit 0
fi

# Setup paths
if test "x$EPREFIX" = x; then
  EPREFIX="$PREFIX"
fi

if test "x$LIBDIR" = x; then
  LIBDIR="$EPREFIX/lib"
fi

if test "x$INCLUDEDIR" = x; then
  INCLUDEDIR="$PREFIX/include"
fi

# Find Python
if test "x$flag_no_python" = x; then
  result=`$PYTHON -c "exit" > /dev/null 2>&1`
  if [ "$?" -ne "0" ]; then
    flag_no_python=yes
  fi
fi

if test "x$flag_no_python" = x; then
    if test "x$PYTHON_VERSION" = x; then
        $ECHO -n "Detecting Python version... "
        PYTHON_VERSION=`$PYTHON -c "import sys; print (\"%d.%d\" % (sys.version_info[0], sys.version_info[1]))"`
        echo $PYTHON_VERSION
    fi

    if test "x$PYTHON_ROOT" = x; then
        $ECHO -n "Detecting Python root... "
        PYTHON_ROOT=`$PYTHON -c "import sys; print(sys.prefix)"`
        echo $PYTHON_ROOT
    fi
fi

# Configure ICU
$ECHO -n "Unicode/ICU support for Boost.Regex?... "
if test "x$flag_icu" != xno; then
  if test "x$ICU_ROOT" = x; then
    if command -v pkg-config > /dev/null && pkg-config icu-uc ; then
      ICU_ROOT=`pkg-config --variable=prefix icu-uc`
    fi
  fi
  if test "x$ICU_ROOT" = x; then
    COMMON_ICU_PATHS="/usr /usr/local /sw"
    for p in $COMMON_ICU_PATHS; do
      if test -r $p/include/unicode/utypes.h; then
        ICU_ROOT=$p
      fi
    done

    if test "x$ICU_ROOT" = x; then
      echo "not found."
    else
      BJAM_CONFIG="$BJAM_CONFIG -sICU_PATH=$ICU_ROOT"
      echo "$ICU_ROOT"
    fi
  else
    BJAM_CONFIG="$BJAM_CONFIG -sICU_PATH=$ICU_ROOT"
    echo "$ICU_ROOT"
  fi
else
  echo "disabled."
fi

# Backup the user's existing project-config.jam
JAM_CONFIG_OUT="project-config.jam"
if test -r "project-config.jam"; then
  counter=1

  while test -r "project-config.jam.$counter"; do
    counter=`expr $counter + 1`
  done

  echo "Backing up existing B2 configuration in project-config.jam.$counter"
  mv "project-config.jam" "project-config.jam.$counter"
fi

# Generate user-config.jam
echo "Generating B2 configuration in project-config.jam for $TOOLSET..."
cat > project-config.jam <<EOF
# B2 Configuration
# Automatically generated by bootstrap.sh

import option ;
import feature ;

# Compiler configuration. This definition will be used unless
# you already have defined some toolsets in your user-config.jam
# file.
if ! $TOOLSET in [ feature.values <toolset> ]
{
    using $TOOLSET ;
}

project : default-build <toolset>$TOOLSET ;
EOF

#  - Python configuration
if test "x$flag_no_python" = x; then
  cat >> project-config.jam <<EOF

# Python configuration
import python ;
if ! [ python.configured ]
{
    using python : $PYTHON_VERSION : "$PYTHON_ROOT" ;
}
EOF
fi

if test "x$ICU_ROOT" != x; then
  cat >> project-config.jam << EOF

path-constant ICU_PATH : $ICU_ROOT ;

EOF
fi

cat >> project-config.jam << EOF

# List of --with-<library> and --without-<library>
# options. If left empty, all libraries will be built.
# Options specified on the command line completely
# override this variable.
libraries = $LIBS ;

# These settings are equivalent to corresponding command-line
# options.
option.set prefix : $PREFIX ;
option.set exec-prefix : $EPREFIX ;
option.set libdir : $LIBDIR ;
option.set includedir : $INCLUDEDIR ;

# Stop on first error
option.set keep-going : false ;
EOF

cat << EOF

Bootstrapping is done. To build, run:

    ./b2

To generate header files, run:

    ./b2 headers

The configuration generated uses ${TOOLSET} to build by default. If that is
unintended either use the --with-toolset option or adjust configuration, by
editing 'project-config.jam'.

Further information:

   - Command line help:
     ./b2 --help

   - Getting started guide:
     http://www.boost.org/more/getting_started/unix-variants.html

   - B2 documentation:
     http://www.boost.org/build/

EOF


#!/bin/sh
#
# Copyright (C) 2000 Stephen Cleary
#
# Distributed under the Boost Software License, Version 1.0. (See accompany-
# ing file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#
# See http://www.boost.org for updates, documentation, and revision history.
#

m4 -P -E -DNumberOfArguments=$1 pool_construct.m4 > pool_construct.ipp


#!/bin/sh
#
# Copyright (C) 2001 Stephen Cleary
#
# Distributed under the Boost Software License, Version 1.0. (See accompany-
# ing file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#
# See http://www.boost.org for updates, documentation, and revision history.
#

m4 -P -E -DNumberOfArguments=$1 pool_construct_simple.m4 > pool_construct_simple.ipp