#!/bin/sh

echo "+++++ Checking current user rights..."

if [ "$(id -u root)" = "$(id -u)" ] ; then
    echo "Passed..."
else
    echo "ERROR: The current user id is not root (`id|awk '{print $1}'`)."
    exit 1
fi
echo

if [ "X$ACTIANZEN_ROOT" = "X" ] ; then
    ACTIANZEN_ROOT=/usr/local/actianzen
fi
export ACTIANZEN_ROOT

LIBDIR=lib64

PATH=$ACTIANZEN_ROOT/bin:$PATH

# PSQL-6827: For restoring legacy v13 or earlier dbnames.cfg.
if [ "X$PVSW_ROOT" = "X" ] ; then
    PVSW_ROOT=/usr/local/psql
fi

if [ $(uname -s) = "Darwin" ]
then
    #DYLD_LIBRARY_PATH=$ACTIANZEN_ROOT/bin:$ACTIANZEN_ROOT/lib:$ACTIANZEN_ROOT/lib64:$DYLD_LIBRARY_PATH
    DYLD_LIBRARY_PATH=$ACTIANZEN_ROOT/lib64:$ACTIANZEN_ROOT/bin:$DYLD_LIBRARY_PATH
    export DYLD_LIBRARY_PATH
    SO_EXTENSION="dylib"
    SU_ARGS="-l"
else
    LD_LIBRARY_PATH=$ACTIANZEN_ROOT/bin:$ACTIANZEN_ROOT/$LIBDIR:$LD_LIBRARY_PATH
    export LD_LIBRARY_PATH
    SO_EXTENSION="so"
    SU_ARGS=
fi

### License check after paths established
if [ "X$1" = "X--accept_LICENSE" ] ; then
    shift
else
    echo -n "Do you accept the terms of the Zen 'LICENSE' file in $ACTIANZEN_ROOT (y/n)? "
    read yn
    case $yn in
      [yY] ) echo "Proceeding..." ;;
      [yY][eE][sS] ) echo "Proceeding..." ;;
      *    ) echo "License not accepted, exiting.";
             exit ;;
    esac
fi

# PSQL-6812 - v14 or later incompatible with v13 and earlier.
echo "+++++ Checking for previous installs..."
if [ -f /usr/local/psql/lib64/libpsqlmif.${SO_EXTENSION} ] ; then
    echo "ERROR: An incompatible version of PSQL is currently installed.  Please uninstall the incompatible version before installing Zen."
    exit 1
fi
echo "Passed..."
echo

# PSQL-6981 - Cannot install v14 or later if legacy username is running any process.
echo "+++++ Checking for running processes owned by user 'psql'..."
PROC_LIST_HEADERS=`ps -ef | head -n1`
LEGACY_OWNER_PROCS=`ps -fu psql 2>/dev/null | grep psql | grep -v grep`
if [ "X$LEGACY_OWNER_PROCS" != "X" ] ; then
    echo "ERROR: One or more processes owned by user 'psql' is currently running. Please stop all processes owned by user 'psql' prior to installing Zen."
    echo "Running processes owned by user 'psql':"
    echo "$PROC_LIST_HEADERS"
    echo "$LEGACY_OWNER_PROCS"
    echo
    exit 1
fi
echo "Passed..."
echo

if [ $(uname -s) != "Darwin" ]
then
    echo "+++++ Checking for system dependencies..."

    # PSQL-8641: Remove use of 'file -L'. Makefile updates placeholder tags
    # dynamically at build time.
    if [ ! -e "/lib/ld-linux-aarch64.so.1" ] && [ ! -e "/lib64/ld-linux-aarch64.so.1" ]; then
        echo "ERROR: ld-linux-aarch64.so.1 not found. This package requires this version of ld-linux."
        exit 1
    fi
fi

if [ $(uname -s) != "Darwin" ]; then

    check_deplib() {
        LIB_FILE=$1              # name of lib to check.
        ZEN_FILE_TO_CHECK=$2     # binary to use for check e.g. $ACTIANZEN_ROOT/bin/psregsvr
        SYS_INSTALLED_LIB_PATH=`ldd $ZEN_FILE_TO_CHECK | grep $LIB_FILE | cut -d " " -f 3`
        if [ ! -f "$SYS_INSTALLED_LIB_PATH" ]; then
            echo "ERROR: $LIB_FILE not found. This package requires this library."
            exit 1
        fi
    }

    for FILE in $ACTIANZEN_ROOT/$LIBDIR/libcsi100.${SO_EXTENSION}.[0-9]*
    do
        if [ \( -f $FILE \) -a \( ! -h $FILE \) ]; then
            CHECK_LIB=$FILE
            break
        fi
    done
    if [ "$CHECK_LIB" ]; then
        check_deplib libcrypt.so.1 $CHECK_LIB
    fi

fi # not Darwin

echo "Passed..."
echo

# Done with checks. Begin using installed files

# Determine if system libs (libstdc++, libgcc_s) meets Zen version requirements and remove
# bundled version if it does.
if [ $(uname -s) != "Darwin" ]; then

    # Function: check_lib(LIB_PATH, ZEN_REQUIRED_LIB_VER, ZEN_FILE_TO_CHECK)
    # requires: readelf command
    check_lib() {
        LIB_PATH=$1              # path of lib to check relative to $ACTIANZEN_ROOT
                                 # e.g. lib64/libstdc++.so.6
        ZEN_REQUIRED_LIB_VER=$2  # version tag e.g GLIBCXX_N.N.N
        ZEN_FILE_TO_CHECK=$3     # binary to use for check e.g. $ACTIANZEN_ROOT/bin/psregsvr

        LIB_FILE=`basename $LIB_PATH`         # e.g. libsdtc++.so.6
        LIB_DIR_REL=`dirname $1`              # e.g. lib or lib64
        LIB_DIR=$ACTIANZEN_ROOT/$LIB_DIR_REL  # e.g. /usr/local/actianzen/lib64

        echo "+++++ Checking version support for file $LIB_PATH ..."
        # Verify readelf is available.
        # Note: It is assumed that caller will warn if readelf is not available.
        READELF=`which readelf`
        if [ -f "$READELF" ]; then
            # First rename the bundled lib in case $ACTIANZEN_ROOT is
            # already in the path so the ldd check below will locate the system
            # library instead of the Zen-provided library (or not find it at all).
            if [ -f $LIB_DIR/$LIB_FILE ]; then
                mv $LIB_DIR/$LIB_FILE $LIB_DIR/$LIB_FILE.zen
            fi

            # Now locate system library path from file dependencies for $ZEN_FILE_TO_CHECK.
            if [ -f $ZEN_FILE_TO_CHECK ]; then
                echo "Obtaining $LIB_PATH dependencies from $ZEN_FILE_TO_CHECK"
                SYS_INSTALLED_LIB_PATH=`ldd $ZEN_FILE_TO_CHECK | grep $LIB_FILE | cut -d " " -f 3`
                if [ -f "$SYS_INSTALLED_LIB_PATH" ]; then
                    echo "Checking for required version info in $SYS_INSTALLED_LIB_PATH"
                    FOUND_ZEN_LIB_DEP=`readelf -V $SYS_INSTALLED_LIB_PATH | grep $ZEN_REQUIRED_LIB_VER`
                    if [ "X$FOUND_ZEN_LIB_DEP" = "X" ]; then
                        echo "Required version support not found, Zen will use $LIB_FILE from install."
                        # Revert previous rename of libraries bundled with Zen install.
                        if [ -f $LIB_DIR/$LIB_FILE.zen ]; then
                            # Revert previous rename of libraries bundled with Zen install.
                            mv $LIB_DIR/$LIB_FILE.zen $LIB_DIR/$LIB_FILE
                        fi
                    else
                        echo "Required version support found, Zen will use $SYS_INSTALLED_LIB_PATH"
                        # Must also remove previously renamed file or it will get a symlink created
                        # for it later in this script.
                        if [ -f $LIB_DIR/$LIB_FILE.zen ]; then
                            rm -f $LIB_DIR/$LIB_FILE.zen
                        fi
                    fi
                else
                    echo "Required version support not found, Zen will use $LIB_FILE from install."
                    # Revert previous rename of libraries bundled with Zen install.
                    if [ -f $LIB_DIR/$LIB_FILE.zen ]; then
                        # Revert previous rename of libraries bundled with Zen install.
                        mv $LIB_DIR/$LIB_FILE.zen $LIB_DIR/$LIB_FILE
                    fi
                fi
            else
                echo "The file $ZEN_FILE_TO_CHECK is not present in the Zen install package, skipping dependency check."
            fi

        fi
    }

    # Verify readelf is available.
    READELF=`which readelf`
    if [ ! -f "$READELF" ]; then
        echo "WARNING: Unable to determine versioning information of system libraries"
        echo "libstdc++.so.6 and libgcc_s.so.1 (missing readelf command)."
        echo "Libraries bundled with the Zen installation will be used."
        echo "These may not be compatible with other utilities."
    else
        check_lib "lib64/libstdc++.so.6" "GLIBCXX_3.4.28" "$ACTIANZEN_ROOT/bin/mkded"
        check_lib "lib64/libgcc_s.so.1" "GCC_7.0.0" "$ACTIANZEN_ROOT/bin/mkded"
    fi
fi # not Darwin

if [ -f $ACTIANZEN_ROOT/etc/postinstall.cfg ] ; then
    . $ACTIANZEN_ROOT/etc/postinstall.cfg
fi
SU="su -"
BASH_ENV=
USERNAME=zen-svc
GROUPNAME=zen-data
ADMGROUPNAME=zen-adm
# PSQL-6827: If legacy v13 or earlier previously installed and then uninstalled,
#            the legacy groups still exists with the same IDs.
LEGACY_USERNAME=psql
LEGACY_GROUPNAME=pvsw
LEGACY_ADMGROUPNAME=pvsw-adm
LEGACY_HOMEDIR=`grep "^$LEGACY_USERNAME:" /etc/passwd | cut -d: -f6`
PS=/bin/ps
PSPARAMS=ax
if ! $PS $PSPARAMS >/dev/null 2>&1; then
   PSPARAMS=
fi
ECHO=/bin/echo
GRPFLAG="-g 5000"
ADMGRPFLAG="-g 5001"
USERSHL=/bin/bash
USERSHLPROFILE1=.bash_profile
USERSHLPROFILE2=.bashrc
SORT=/bin/sort
if [ ! -x $SORT ] ; then
    SORT=/usr/bin/sort
fi
LDCONFIG=/sbin/ldconfig
if [ ! -x $LDCONFIG ] ; then
    LDCONFIG=/usr/sbin/ldconfig
fi
CHKCONFIG="# chkconfig: 2345 92 92"
USERSHLPROFILE3=.cshrc
TEMPDBLOCATION=$ACTIANZEN_ROOT/data/TEMPDB
SELINUX_ENABLED=/usr/sbin/selinuxenabled

find_required() {
    COUNT=0
    for D in bin lib lib64 ; do
        if [ -d "$ACTIANZEN_ROOT/$D" ] ; then
            for F in `ls -1A $ACTIANZEN_ROOT/$D | grep -v "jar$"` ; do
                REQUIREDEXISTS=`ldd -v $ACTIANZEN_ROOT/$D/$F 2>&1 | grep required`
                if [ "X$REQUIREDEXISTS" != "X" ] ; then
                    COUNT="$(($COUNT + 1))"
                    if [ $# -ne 0 ] ; then
                        echo $REQUIREDEXISTS
                    fi
                fi
                unset REQUIREDEXISTS
            done
            unset F
        fi
    done
    unset D
    return $COUNT
}

echo ""

echo "+++++ Checking user and group configuration..."
# PSQL-6827/PSQL-8447: Move up checks for legacy and current user/groups. The Legacy user
# and groups will only be migrated to current user and groups if both don't already exist.
if [ $(uname -s) = "Darwin" ]
then
    LEGACY_PUSER_FOUND=`dscl . -list /Users UniqueID | awk '($1 == "'"$LEGACY_USERNAME"'")'`
    LEGACY_PVSW_GRP_FOUND=`dscl . -list /Groups PrimaryGroupID | awk '($1 == "'"$LEGACY_GROUPNAME"'")'`
    LEGACY_ADM_GRP_FOUND=`dscl . -list /Groups PrimaryGroupID | awk '($1 == "'"$LEGACY_ADMGROUPNAME"'")'`
    UPVSWEXISTS=`dscl . -list /Users UniqueID | awk '($1 == "'"$USERNAME"'")'`
    GPVSWEXISTS=`dscl . -list /Groups PrimaryGroupID | awk '($1 == "'"$GROUPNAME"'")'`
    GPVSWADMEXISTS=`dscl . -list /Groups PrimaryGroupID | awk '($1 == "'"$ADMGROUPNAME"'")'`
else
    LEGACY_PUSER_FOUND=`grep "^$LEGACY_USERNAME:" /etc/passwd`
    LEGACY_PVSW_GRP_FOUND=`grep "^$LEGACY_GROUPNAME:" /etc/group`
    LEGACY_ADM_GRP_FOUND=`grep "^$LEGACY_ADMGROUPNAME:" /etc/group`
    UPVSWEXISTS=`grep "^$USERNAME:" /etc/passwd`
    GPVSWEXISTS=`grep "^$GROUPNAME:" /etc/group`
    GPVSWADMEXISTS=`grep "^$ADMGROUPNAME:" /etc/group`
fi
# PSQL-8447: Databases don't get created during upgrade from legacy version if
# both users exist. Also check groups.
# -- Both users exist.
if [ "X$UPVSWEXISTS" != "X" ] && [ "X$LEGACY_PUSER_FOUND" != "X" ] ; then
    echo "ERROR: The legacy user $LEGACY_USERNAME was found but cannot be"
    echo "converted to new user $USERNAME because $USERNAME already exists."
    echo "Please delete one of the users and then restart the installation."
    exit 1 ;
fi
# -- Both groups exist.
if [ "X$GPVSWEXISTS" != "X" ] && [ "X$LEGACY_PVSW_GRP_FOUND" != "X" ] ; then
    echo "ERROR: The legacy group $LEGACY_GROUPNAME was found but cannot be"
    echo "converted to new group $GROUPNAME because $GROUPNAME already exists."
    echo "Please delete one of the groups and then restart the installation."
    exit 1 ;
fi
# -- Both admin groups exist.
if [ "X$GPVSWADMEXISTS" != "X" ] && [ "X$LEGACY_ADM_GRP_FOUND" != "X" ] ; then
    echo "ERROR: The legacy group $LEGACY_ADMGROUPNAME was found but cannot be"
    echo "converted to new group $ADMGROUPNAME because $ADMGROUPNAME already exists."
    echo "Please delete one of the groups and then restart the installation."
    exit 1 ;
fi
echo

echo "+++++ Setting up $GROUPNAME group and admgroup..."
if [ "X$GPVSWEXISTS" != "X" ] ; then
    echo "An existing group $GROUPNAME was found."
else
    # PSQL-6827: If legacy group found then change just group name.
    if [ "X$LEGACY_PVSW_GRP_FOUND" != "X" ] ; then
        echo "Changing legacy group $LEGACY_GROUPNAME to $GROUPNAME..."

        if [ $(uname -s) = "Darwin" ]
        then
            dscl . -change /Groups/"$LEGACY_GROUPNAME" RecordName "$LEGACY_GROUPNAME" "$GROUPNAME"
        else
            groupmod -n $GROUPNAME $LEGACY_GROUPNAME
        fi
    else
        echo "Creating group $GROUPNAME..."
        if [ $(uname -s) = "Darwin" ]
        then
            groupid="$(($(dscl . -list /Groups PrimaryGroupID | awk '{print $2}' | sort -n | tail -n 1) + 1))"
            dscl . -create /Groups/"$GROUPNAME" PrimaryGroupID "$groupid"
        else
            /usr/sbin/groupadd $GRPFLAG $GROUPNAME
        fi
    fi
fi

if [ "X$GPVSWADMEXISTS" != "X" ] ; then
    echo "An existing group $ADMGROUPNAME was found."
else
    # PSQL-6827: If legacy admin group found then just change group name.
    if [ "X$LEGACY_ADM_GRP_FOUND" != "X" ] ; then
        echo "Changing legacy group $LEGACY_ADMGROUPNAME to $ADMGROUPNAME..."

        if [ $(uname -s) = "Darwin" ]
        then
            dscl . -change /Groups/"$LEGACY_ADMGROUPNAME" RecordName "$LEGACY_ADMGROUPNAME" "$ADMGROUPNAME"
        else
            groupmod -n $ADMGROUPNAME $LEGACY_ADMGROUPNAME
        fi
    else
        echo "Creating group $ADMGROUPNAME..."
        if [ $(uname -s) = "Darwin" ]
        then
            dscl . -create /Groups/"$ADMGROUPNAME" PrimaryGroupID "$(($(dscl . -list /Groups PrimaryGroupID | awk '{print $2}' | sort -n | tail -n 1) + 1))"
        else
            /usr/sbin/groupadd $ADMGRPFLAG $ADMGROUPNAME
        fi
    fi
fi
echo


# Create the root, bin and log folders if they don't exist
if [ ! -d "$ACTIANZEN_ROOT" ] ; then
    mkdir $ACTIANZEN_ROOT
fi
if [ ! -d "$ACTIANZEN_ROOT/bin" ] ; then
    mkdir $ACTIANZEN_ROOT/bin
fi
if [ ! -d "$ACTIANZEN_ROOT/log" ] ; then
    mkdir $ACTIANZEN_ROOT/log
fi
if [ ! -d "$TEMPDBLOCATION" ] ; then
    mkdir $TEMPDBLOCATION
fi

echo "+++++ Setting up user $USERNAME..."
if [ "X$UPVSWEXISTS" != "X" ] ; then
    echo "An existing user $USERNAME was found."
	
    # check if there are any problems with the existing user
    if [ $(uname -s) = "Darwin" ]
    then
        CPVSWSHELL=`dscl . -list /Users UserShell | awk '($1 == "'"$USERNAME"'")' | grep $USERSHL`
    else
        CPVSWSHELL=`echo $UPVSWEXISTS|grep $USERSHL`
    fi

    if [ "X$CPVSWSHELL" = "X" ] ; then
        echo "ERROR: Existing user $USERNAME has shell other than $USERSHL."
        exit 1 ;
    fi
else
    # PSQL-6827: If legacy user found then just change user name and update home directory.
    if [ "X$LEGACY_PUSER_FOUND" != "X" ] ; then
        echo "Changing legacy user $LEGACY_USERNAME to $USERNAME and updating users home directory..."

        if [ $(uname -s) = "Darwin" ]
        then
            dscl . -change /Users/"$LEGACY_USERNAME" RecordName "$LEGACY_USERNAME" "$USERNAME"
            mkdir -p "/Users/$USERNAME"
            chown -Rf $USERNAME:$GROUPNAME "/Users/$USERNAME"
            dscl . -change /Users/"$USERNAME" NFSHomeDirectory "/Users/$LEGACY_USERNAME" "/Users/$USERNAME"
        else
            NEWHOMEDIR=/home/$USERNAME
            usermod -l $USERNAME $LEGACY_USERNAME
            mkdir -p $NEWHOMEDIR
            chown -R $USERNAME:$GROUPNAME $NEWHOMEDIR
            usermod -d /home/$USERNAME $USERNAME
        fi
    else
        echo "Creating user $USERNAME"

        if [ $(uname -s) = "Darwin" ]
        then
            HOMEDIR=/Users/"$USERNAME"
            dscl . -create "$HOMEDIR" UniqueID "$(($(dscl . -list /Users UniqueID | awk '{print $2}' | sort -n | tail -n 1) + 1))"
            dscl . -create "$HOMEDIR" RealName "ActianZen"
            dscl . -create "$HOMEDIR" UserShell "$USERSHL"
            dscl . -create "$HOMEDIR" PrimaryGroupID "$(dscl . -list /Groups PrimaryGroupID | awk '($1 == "'"$GROUPNAME"'") { print $2 }')"
            dscl . -create "$HOMEDIR" NFSHomeDirectory "$HOMEDIR"
            defaults write /Library/Preferences/com.apple.loginwindow HiddenUsersList -array-add "$USERNAME"
            mkdir -p "$HOMEDIR"
            chown $USERNAME:$GROUPNAME "$HOMEDIR"
            chmod 755 "$HOMEDIR"
            unset HOMEDIR
        else
            /usr/sbin/useradd -c "ActianZen" -m -g $GROUPNAME -s $USERSHL $USERNAME
        fi

        if [ "$?" != "0" ]; then
            echo "ERROR: The user $USERNAME could not be created."
            exit 1;
        fi
        sleep 2

        TEMPFILE=/tmp/actianzen.tmp
        touch $TEMPFILE
        chown $USERNAME $TEMPFILE
        if [ "$?" != "0" ]; then
            echo "ERROR: The user $USERNAME could not be created."
            exit 1;
        fi
        rm -f $TEMPFILE
    fi
fi

echo "Configuring user $USERNAME environment..."
if [ $(uname -s) = "Darwin" ]
then
    HOMEDIR=/Users/"$USERNAME"
else
	# If there's an xhost command in our path.
	if which xhost >/dev/null 2>&1
	then
		if [ -f $ACTIANZEN_ROOT/bin/zencc ] ; then
			xhost local:$USERNAME
		fi
	fi

    HOMEDIR=`grep "^$USERNAME:" /etc/passwd | cut -d: -f6`
fi

PROFILE1=$HOMEDIR/$USERSHLPROFILE1
PROFILE2=$HOMEDIR/$USERSHLPROFILE2
PROFILE3=$HOMEDIR/$USERSHLPROFILE3

if [ $(uname -s) = "Darwin" ]
then
    if [ "$LANG" = "" ]
    then
        LANG="ja_JP.UTF-8"
    fi

    echo "User $USERNAME LANG environment variable will be set to \"$LANG\"."
fi

cat > $PROFILE1 << EOPF
#!/bin/sh
umask 022
export ACTIANZEN_ROOT=$ACTIANZEN_ROOT
export PATH=\$ACTIANZEN_ROOT/bin:/bin:/usr/bin
if [ \$(uname -s) = "Darwin" ]
then
    export DYLD_LIBRARY_PATH=\$ACTIANZEN_ROOT/lib64:\$ACTIANZEN_ROOT/bin:/usr/lib
    export LANG=$LANG
else
    export LD_LIBRARY_PATH=\$ACTIANZEN_ROOT/$LIBDIR:\$ACTIANZEN_ROOT/bin:/usr/lib:/usr/lib64
fi
export MANPATH=\$ACTIANZEN_ROOT/man:\$MANPATH
export BREQ=\$ACTIANZEN_ROOT/lib
export LD_BIND_NOW=1

EOPF

cp -f $PROFILE1 $PROFILE2
if [ ! -f $PROFILE3 ] ; then
cat > $PROFILE3 <<EOPF2
#!/bin/sh
setenv ACTIANZEN_ROOT $ACTIANZEN_ROOT
if [ \$(uname -s) = "Darwin" ]
then
    setenv DYLD_LIBRARY_PATH \$ACTIANZEN_ROOT/lib64:\$DYLD_LIBRARY_PATH
    setenv LANG $LANG
else
    setenv LD_LIBRARY_PATH \$ACTIANZEN_ROOT/$LIBDIR:\$LD_LIBRARY_PATH
fi
setenv MANPATH \$ACTIANZEN_ROOT/man:\$MANPATH
set path = (\$ACTIANZEN_ROOT/bin $path)
setenv BREQ \$ACTIANZEN_ROOT/lib
setenv LD_BIND_NOW 1

EOPF2
fi
echo


echo "+++++ Setting up symbolic links for libraries..."

chmod 755 $ACTIANZEN_ROOT/etc/pipe

if [ -x $SELINUX_ENABLED ] && $SELINUX_ENABLED; then
    /sbin/restorecon -R $ACTIANZEN_ROOT
    #/usr/bin/chcon -t textrel_shlib_t "$ACTIANZEN_ROOT"/lib/*.so "$ACTIANZEN_ROOT"/lib/*.so.*

    if [ -d "$ACTIANZEN_ROOT/$LIBDIR" ]
    then
        /usr/bin/chcon -t textrel_shlib_t "$ACTIANZEN_ROOT"/lib64/*.so "$ACTIANZEN_ROOT"/lib64/*.so.*
    fi
fi

for FILE in $ACTIANZEN_ROOT/$LIBDIR/libpsqlmif.${SO_EXTENSION}.[0-9]*
do
    if [ \( -f $FILE \) -a \( ! -h $FILE \) ]; then
        MIF_FILE=$FILE
        break
    fi
done
if [ "$MIF_FILE" ]; then
    # ..../libpsqlmif.so.15.10.NNN.MMM --> 15
    # ..../libpsqlmif.so.15 -> 15
    PSQL_VER=`echo $MIF_FILE | sed -e 's/^.*\.'"${SO_EXTENSION}"'\.\([0-9]*\).*$/\1/'`
else
    if [ $(uname -s) = "Darwin" ]; then
        # ..../libpsqlmif.15.dylib --> 15
        for FILE in $ACTIANZEN_ROOT/$LIBDIR/libpsqlmif.[0-9]*.dylib
        do
            if [ \( -f $FILE \) -a \( ! -h $FILE \) ]; then
                MIF_FILE=$FILE
                break
            fi
        done
        PSQL_VER=`echo $MIF_FILE | sed -e 's/^.*\.\([0-9]*\)\.dylib$/\1/'`
    fi
fi
echo "++++ MIF_FILE: $MIF_FILE (PSQL_VER=$PSQL_VER)"
PS_VER=$PSQL_VER

if [ ! $(uname -s) = "Darwin" ]
then
    # Use ldconfig to create links to major versions
    # selinux: ldconfig runs in its own domain and may not have
    # permissions to write to tty.
    $LDCONFIG -n $ACTIANZEN_ROOT/$LIBDIR 2>&1 | cat

    # PSQL-5733: If this is the community edition we need to rename the symlink for
    #            liblegacylm created with the wrong name by the $LDCONFIG command.
    if [ "$ProductType" = "COMMUNITY" ]
    then
        mv $ACTIANZEN_ROOT/$LIBDIR/liblegacylmce.${SO_EXTENSION}.$PSQL_VER $ACTIANZEN_ROOT/$LIBDIR/liblegacylm.${SO_EXTENSION}.$PSQL_VER
    fi

    dso_symlink () {
        dso=$1
        ver=$2
        # libmkc3.so.15.10.NNN.000 <-- libmkc3.so.15 [ldconfig for compmake]
        # libmkc3.so.15 <-- libmkc3.so [compmake; cmake]
        if [ -f $ACTIANZEN_ROOT/$LIBDIR/$dso.$ver ]; then
            (cd $ACTIANZEN_ROOT/$LIBDIR; ln -sf $dso.$ver $dso )
        fi
    }
else

    dso_symlink () {
      dso=$1
      ver=$2
      # libmkc3.dylib.15.10.NNN.000 <-- libmkc3.dylib.15 [compmake]
      # libmkc3.dylib.15 <-- libmkc3.dylib [compmake]
      if [ -f $ACTIANZEN_ROOT/$LIBDIR/$dso.$ver.[0-9]*.* ]; then
          (cd $ACTIANZEN_ROOT/$LIBDIR;
           ln -sf $dso.$ver.[0-9]*.* $dso.$ver;
           ln -sf $dso.$ver $dso)
      fi
      dso=`basename $1 .${SO_EXTENSION}`
      # libmkc3.15.dylib <-- libmkc3.dylib [cmake]
      if [ -f $ACTIANZEN_ROOT/$LIBDIR/$dso.$ver.${SO_EXTENSION} ]; then
          (cd $ACTIANZEN_ROOT/$LIBDIR;
           ln -sf $dso.$ver.${SO_EXTENSION} $dso.${SO_EXTENSION})
      fi
    }
fi

dso_symlink libbdulb.${SO_EXTENSION} $PSQL_VER
dso_symlink libclientrb.${SO_EXTENSION} $PSQL_VER
dso_symlink libcobolschemaexecmsgrb.${SO_EXTENSION} $PSQL_VER
dso_symlink libcsi100.${SO_EXTENSION} $PSQL_VER
dso_symlink libdbcsipxy.${SO_EXTENSION} $PSQL_VER
dso_symlink libdcm100.${SO_EXTENSION} $PSQL_VER
dso_symlink libenginelm.${SO_EXTENSION} $PSQL_VER
dso_symlink libexp010.${SO_EXTENSION} $PSQL_VER
dso_symlink liblegacylm.${SO_EXTENSION} $PSQL_VER
# PSQL-5733: If this is the community edition we need to rename the symlink for
#            liblegacylm created with the wrong name by the $LDCONFIG command.
if [ "$ProductType" = "COMMUNITY" ]
then
    mv $ACTIANZEN_ROOT/$LIBDIR/liblegacylmce.${SO_EXTENSION}.$PSQL_VER $ACTIANZEN_ROOT/$LIBDIR/liblegacylm.${SO_EXTENSION}.$PSQL_VER
fi
dso_symlink liblicmgrrb.${SO_EXTENSION} $PSQL_VER
dso_symlink libmkc3.${SO_EXTENSION} $PSQL_VER
dso_symlink libmkderb.${SO_EXTENSION} $PSQL_VER
dso_symlink libodbccr.${SO_EXTENSION} 1
dso_symlink libpceurop.${SO_EXTENSION} $PS_VER
dso_symlink libpctlgrb.${SO_EXTENSION} $PSQL_VER
dso_symlink libpscl.${SO_EXTENSION} $PS_VER
dso_symlink libpscore.${SO_EXTENSION} $PS_VER
dso_symlink libpscp932.${SO_EXTENSION} $PS_VER
dso_symlink libpsdom.${SO_EXTENSION} $PS_VER
dso_symlink libpseucjp.${SO_EXTENSION} $PS_VER
dso_symlink libpssax.${SO_EXTENSION} $PS_VER
dso_symlink libpsutilrb.${SO_EXTENSION} $PS_VER
dso_symlink libsrderb.${SO_EXTENSION} $PSQL_VER
dso_symlink libupiapirb.${SO_EXTENSION} $PSQL_VER
dso_symlink libxlate.${SO_EXTENSION} $PSQL_VER

cd $ACTIANZEN_ROOT/$LIBDIR
if [ -f $ACTIANZEN_ROOT/$LIBDIR/libodbc.${SO_EXTENSION}.1*0 ]; then
    if [ ! -f $ACTIANZEN_ROOT/$LIBDIR/libodbc.${SO_EXTENSION}.1 ]; then
        ln -sf libodbc.${SO_EXTENSION}.1*0 libodbc.${SO_EXTENSION}.1
    fi
elif [ -f $ACTIANZEN_ROOT/$LIBDIR/libodbc.1.0.dylib ]; then
    if [ ! -f $ACTIANZEN_ROOT/$LIBDIR/libodbc.1.dylib ]; then
        ln -sf libodbc.1.0.${SO_EXTENSION} libodbc.1.dylib
    fi
fi
cd $ACTIANZEN_ROOT
dso_symlink libodbc.${SO_EXTENSION} 1

dso_symlink libpsqldti.${SO_EXTENSION} $PSQL_VER
dso_symlink libclientlm.${SO_EXTENSION} $PSQL_VER
dso_symlink libbtrieveC.${SO_EXTENSION} $PSQL_VER
dso_symlink libbtrieveCpp.${SO_EXTENSION} $PSQL_VER
dso_symlink libeasysyncapi.${SO_EXTENSION} $PSQL_VER
dso_symlink libpsqlmif.${SO_EXTENSION} $PSQL_VER
dso_symlink libpsqlnsl.${SO_EXTENSION} $PSQL_VER
dso_symlink libpsxdebug.${SO_EXTENSION} $PSQL_VER
dso_symlink libpsqlcsm.${SO_EXTENSION} $PSQL_VER
dso_symlink libpsqlcsp.${SO_EXTENSION} $PSQL_VER
dso_symlink libsrde.${SO_EXTENSION} $PSQL_VER
dso_symlink libpsqlcobolschemaexec.${SO_EXTENSION} $PSQL_VER
dso_symlink libsqlmgr.${SO_EXTENSION} $PSQL_VER
dso_symlink libdbuxlt.${SO_EXTENSION} $PSQL_VER
dso_symlink libodbcci.${SO_EXTENSION} $PSQL_VER
dso_symlink libpvisr.${SO_EXTENSION} $PSQL_VER
dso_symlink libpvmsgrb.${SO_EXTENSION} $PSQL_VER
dso_symlink libmkdemd.${SO_EXTENSION} $PSQL_VER
dso_symlink libpsqlmpm.${SO_EXTENSION} $PSQL_VER
dso_symlink libpvisr.${SO_EXTENSION} $PSQL_VER

dso_symlink libels.${SO_EXTENSION} $PSQL_VER

if [ ! -f $ACTIANZEN_ROOT/$LIBDIR/pam_pvsw.${SO_EXTENSION}  ] ; then
    cd $ACTIANZEN_ROOT/$LIBDIR
    if [ -f pam_pvsw.${SO_EXTENSION}.1.0 ]; then
        ln -sf pam_pvsw.${SO_EXTENSION}.1.0 pam_pvsw.${SO_EXTENSION}
    elif [ -f pam_pvsw.1.0.${SO_EXTENSION} ]; then
        ln -sf pam_pvsw.1.0.${SO_EXTENSION} pam_pvsw.${SO_EXTENSION}
    fi
    cd $ACTIANZEN_ROOT
fi

cd $ACTIANZEN_ROOT/bin
if [ -f psregedit64 ]; then
    ln -sf psregedit64 psregedit
fi    
if [ -f clilcadm64 ]; then
    ln -sf clilcadm64 clilcadm
fi
if [ -f clipaadm64 ]; then
    ln -sf clipaadm64 clipaadm
fi
if [ -f licgetauth64 ]; then
    ln -sf licgetauth64 licgetauth
fi
if [ -f isql64 ]; then
    ln -sf isql64 isql
fi
cd $ACTIANZEN_ROOT

echo "Making user $USERNAME owner of all files in $ACTIANZEN_ROOT..."

chown -R $USERNAME:$GROUPNAME $ACTIANZEN_ROOT
chmod -R ug+w $ACTIANZEN_ROOT/etc $ACTIANZEN_ROOT/data $ACTIANZEN_ROOT/schemas $ACTIANZEN_ROOT/log
# install-related scripts remain owned by root so zen cannot uninstall (which fails)
if [ $(uname -s) = "Darwin" ]
then
    chown root:wheel $ACTIANZEN_ROOT/etc/*install.sh
else
    chown root:root $ACTIANZEN_ROOT/etc/*install.sh
fi
chmod 770 $ACTIANZEN_ROOT/etc/*install.sh
echo


SVCFILE=/etc/services
echo "+++++ Setting up entries in $SVCFILE..."

BTRSERVICE=btrieve
BSTRING=`grep "^$BTRSERVICE" $SVCFILE`
if [ "X$BSTRING" = "X" ] ; then
    BSTRING="$BTRSERVICE		3351/tcp		# Zen MKDE daemon"
    sync
    sleep 2
    echo $BSTRING >> $SVCFILE
    echo "The following line added to $SVCFILE:"
else
    echo "The following line found in $SVCFILE:"
fi
echo $BSTRING
echo


echo "+++++ Registering the PCOM libraries..."

PSREGSVR=psregsvr
if [ "$LIBDIR" = "lib64" ]; then
    PSREGSVR=psregsvr64
fi

# Sym links must already exist
dso_register () {
    dso=$1
    if [ -f $ACTIANZEN_ROOT/$LIBDIR/$dso ]; then
        $ACTIANZEN_ROOT/bin/$PSREGSVR $ACTIANZEN_ROOT/$LIBDIR/$dso
        if [ $? -ne 0 ]; then
            echo "ERROR: PCOM registration failed for $dso."
            exit 1;
        fi
    fi
}

dso_register libpseucjp.${SO_EXTENSION}
dso_register libmkc3.${SO_EXTENSION}
dso_register libexp010.${SO_EXTENSION}
dso_register liblicmgrrb.${SO_EXTENSION}
dso_register liblegacylm.${SO_EXTENSION}
dso_register libmkderb.${SO_EXTENSION}
dso_register libpctlgrb.${SO_EXTENSION}
dso_register libcobolschemaexecmsgrb.${SO_EXTENSION}
dso_register libpsqlcobolschemaexec.${SO_EXTENSION}
# dso_register libpvmdconvmsgrb.${SO_EXTENSION}
dso_register libpceurop.${SO_EXTENSION}
dso_register libpssax.${SO_EXTENSION}
dso_register libpsdom.${SO_EXTENSION}
dso_register libpsutilrb.${SO_EXTENSION}
dso_register libclientrb.${SO_EXTENSION}
dso_register libupiapirb.${SO_EXTENSION}
dso_register libpvmsgrb.${SO_EXTENSION}
dso_register libpsqlcsm.${SO_EXTENSION}
dso_register libpsqlcsp.${SO_EXTENSION}
dso_register libdbcsipxy.${SO_EXTENSION}
dso_register libdcm100.${SO_EXTENSION}
dso_register libcsi100.${SO_EXTENSION}
dso_register libpsqlmpm.${SO_EXTENSION}
dso_register libpscp932.${SO_EXTENSION}
dso_register libsrderb.${SO_EXTENSION}

# Reset owner to zen-svc:zen-data
if [ -e "$ACTIANZEN_ROOT/etc/.PSRegistry" ]
then
    chown -R $USERNAME:$GROUPNAME $ACTIANZEN_ROOT/etc/.PSRegistry
fi

PS_SEM_IPC_SEM_ID="/tmp/PS_sem_*_IPC_SEM.id"
PS_SHM_IPC_SHARED_MEM_ID="/tmp/PS_shm_*_IPC_SHARED_MEM.id"

# If there are any PS_SEM_IPC_SEM_ID files.
if ls $PS_SEM_IPC_SEM_ID > /dev/null 2>&1 ; then
	chown $USERNAME:$GROUPNAME $PS_SEM_IPC_SEM_ID
fi

# If there are any PS_SHM_IPC_SHARED_MEM_ID files.
if ls $PS_SHM_IPC_SHARED_MEM_ID > /dev/null 2>&1 ; then
	chown $USERNAME:$GROUPNAME $PS_SHM_IPC_SHARED_MEM_ID
fi

# Empty all permissions.
if [ -e "$ACTIANZEN_ROOT/etc/.PSRegistry" ]
then
    chmod -R a-rwx  $ACTIANZEN_ROOT/etc/.PSRegistry
fi

# Add read only for everybody.
if [ -e "$ACTIANZEN_ROOT/etc/.PSRegistry" ]
then
    chmod -R a+rx   $ACTIANZEN_ROOT/etc/.PSRegistry
fi

# Add full control for user and group.
if [ -e "$ACTIANZEN_ROOT/etc/.PSRegistry" ]
then
    chmod -R ug+rwx  $ACTIANZEN_ROOT/etc/.PSRegistry
fi

echo


echo "+++++ Migrating engine settings from previous versions ..."

if [ -r $ACTIANZEN_ROOT/etc/bti.ini.rpmsave ] ; then
    echo "$ACTIANZEN_ROOT/bin/confmig -ini $ACTIANZEN_ROOT/etc/uxpscfg.ini -log $ACTIANZEN_ROOT/etc/confmig.log -source $ACTIANZEN_ROOT/etc/bti.ini.rpmsave -from 8 -to 10" | $SU $USERNAME $SU_ARGS
else
   if [ -r $ACTIANZEN_ROOT/etc/bti.ini.rpmorig ] ; then
      echo "$ACTIANZEN_ROOT/bin/confmig -ini $ACTIANZEN_ROOT/etc/uxpscfg.ini -log $ACTIANZEN_ROOT/etc/confmig.log -source $ACTIANZEN_ROOT/etc/bti.ini.rpmorig -from 8 -to 10" | $SU $USERNAME $SU_ARGS
   else
      echo "$ACTIANZEN_ROOT/bin/confmig -ini $ACTIANZEN_ROOT/etc/uxpscfg.ini -log $ACTIANZEN_ROOT/etc/confmig.log -from 9 -to 10" | $SU $USERNAME $SU_ARGS
   fi
fi

echo "Restoring the configuration from previous install..."
ETCDIR=$ACTIANZEN_ROOT/etc
ODBCINI=$ETCDIR/odbc.ini
SAVESUFFIX=rpmsave
for cfgfile in dbnames.cfg bti.ini odbc.ini btpasswd els.ini idshosts odbcinst.ini psql uxpscfg.ini; do
    if [ -f $ETCDIR/$cfgfile.$SAVESUFFIX ] ; then
        if [ -f $ETCDIR/$cfgfile ] ; then
            echo "Archiving $cfgfile to $ETCDIR/$cfgfile.org"
            mv $ETCDIR/$cfgfile $ETCDIR/$cfgfile.org
        fi
        echo "Restoring previous $cfgfile.$SAVESUFFIX to $ETCDIR/$cfgfile"
        mv $ETCDIR/$cfgfile.$SAVESUFFIX $ETCDIR/$cfgfile
    fi
done
if [ -f $ODBCINI ] ; then
    chmod a-wrx $ODBCINI
    chmod a+r $ODBCINI
    chmod ug+w $ODBCINI
fi
# PSQL-6827: If v13 or earlier RPM previously uninstalled, restore dbnames.cfg.
if [ -f $PVSW_ROOT/etc/dbnames.cfg.$SAVESUFFIX ] ; then
    echo "Restoring legacy dbnames.cfg.$SAVESUFFIX to $PVSW_ROOT/etc/dbnames.cfg"
    mv $PVSW_ROOT/etc/dbnames.cfg.$SAVESUFFIX $PVSW_ROOT/etc/dbnames.cfg
fi
echo


################# RunDaemons Section ###########################################

RUNDAEMONFILE="$ACTIANZEN_ROOT/etc/init.d/actianzen"

OCF_RESOURCE_AGENT=/usr/lib/ocf/resource.d/heartbeat/actianzen

# check if the lock file directory exists (Debian Linux uses a different lock
# file directory then the other flavors of Linux)
if [ -d /var/lock/subsys ] ; then
    LOCKFILE=/var/lock/subsys/actianzen
else
    if [ $(uname -s) = "Darwin" ]
    then
        LOCKFILE=/var/tmp/actianzen
    else
        LOCKFILE=/var/state/actianzen
    fi
fi


echo "+++++ Setting up daemon $ACTIANZEN_ROOT/etc/init.d/actianzen ..."

mkdir -p "$ACTIANZEN_ROOT/etc/init.d"

cat > $ACTIANZEN_ROOT/etc/init.d/actianzen << EORDF
#!/bin/sh
#
# description: Starts and stops the Zen mkded and sqlmgr daemons

$CHKCONFIG
# description: The Zen database engine ranges from embedded to enterprise.

# Comments to support LSB init script conventions
# We've added various binders, time services and samba to the "should" list
# to aid in dependency ordering.  They are not required.
### BEGIN INIT INFO
# Provides: actianzen
# Required-Start: \$local_fs \$network \$remote_fs \$syslog
# Should-Start: ypbind nscd ldap ntpd xntpd smb smbfs
# Required-Stop: \$local_fs \$network \$remote_fs \$syslog
# Default-Start:  2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: start and stop Zen daemons
# Description: The Zen database engine ranges from embedded to enterprise.
### END INIT INFO

# Include source function library
status(){
    local base=\${1##*/}
    local pid

    # Test syntax.
    if [ \$# = 0 ] ; then
        echo "Usage: status {program}"
        return 1
    fi

    if [ \$(uname -s) = "Darwin" ]
    then
        pid="\$(/bin/ps -e | awk '(\$4 ~ /[\/]?'\$base'\$/) { print \$1 }')"
    else
        pid=\`pidof -o \$\$ -o \$PPID -o %PPID -x \$1 || pidof -o \$\$ -o \$PPID -o %PPID -x \${base}\`
    fi

    if [ "\$pid" != "" ] ; then
        echo "\${base} (pid \$pid) is running..."
        return 0
    fi

    # Next try "/var/run/*.pid" files
    if [ -f /var/run/\${base}.pid ] ; then
        read pid < /var/run/\${base}.pid
        if [ "\$pid" != "" ] ; then
            echo "\${base} dead but pid file exists"
            return 1
        fi
    fi
    # See if /var/lock/subsys/${base} exists
    if [ -f /var/lock/subsys/\${base} ]; then
        echo "\${base} dead but subsys locked"
        return 2
    fi
    echo "\${base} is stopped"

    # If running in OCF mode.
    if [ "\$ocf" -eq 1 ]
    then
        # OCF states that monitoring a stopped resource must return 7.
        return 7
    fi

    return 3
}

start_zen(){
    echo "Starting Zen services: "

    BTRID=\`$PS $PSPARAMS | grep -v grep | grep mkded | awk '{print \$1}'\`
    if [ "X\$BTRID" != "X" ] ; then
        echo Warning: the following service is running
        echo mkded
        echo
    else
        echo mkded
        ULIMIT_N=\$(ulimit -n)

        if [ \$(uname -s) = "Darwin" ]
        then
            KERN_MAXFILES_MIN=65535

            if [ "\$(sysctl kern.maxfiles | awk '{ print \$NF }')" -lt "\$KERN_MAXFILES_MIN" ]
            then
                sysctl -w kern.maxfiles="\$KERN_MAXFILES_MIN"
            fi

            ulimit -n "\$(sysctl kern.maxfiles | awk '{ print \$NF }')"
            KERN_SYSV_SHMALL_MIN=4096
            KERN_SYSV_SHMMAX_MIN=8388608

            if [ "\$(sysctl kern.sysv.shmall | awk '{ print \$NF }')" -lt "\$KERN_SYSV_SHMALL_MIN" ]
            then
                sysctl -w kern.sysv.shmall="\$KERN_SYSV_SHMALL_MIN"
            fi

            if [ "\$(sysctl kern.sysv.shmmax | awk '{ print \$NF }')" -lt "\$KERN_SYSV_SHMMAX_MIN" ]
            then
                sysctl -w kern.sysv.shmmax="\$KERN_SYSV_SHMMAX_MIN"
            fi
        else
            # If the current "ulimit -n" is less than our required minimum.
            if [ "\$ULIMIT_N" -lt 65535 ]
            then
                ulimit -n 65535 || exit 1
            fi
        fi

        if [ "\$SYSINIT" = "systemd" ] ; then
            systemctl start actianzen.service
        else
            echo "cd \$ACTIANZEN_ROOT/bin; ./mkded -start" | $SU zen-svc $SU_ARGS || exit 1
        fi
        ulimit -n "\$ULIMIT_N" || exit 1
    fi
    touch $LOCKFILE
    echo ""
    # LSB states that successfully starting a resource must return 0.
    return 0
}

stop_zen(){
    # Note: previously this included clean_zen after stopping mkded.
    echo "Shutting down Zen services: "
    if [ "\$SYSINIT" = "systemd" ] ; then
        systemctl stop actianzen.service
    else
        BTRID=\`$PS $PSPARAMS | grep -v grep | grep mkded | awk '{print \$1}'\`
        if [ "X\$BTRID" != "X" ] ; then
            echo mkded
            if [ -x $ACTIANZEN_ROOT/bin/mkded ] ; then
                echo "cd \$ACTIANZEN_ROOT/bin; ./mkded -stop" | $SU zen-svc $SU_ARGS
            else
                kill -9 \$BTRID
            fi
        fi
    fi
}

clean_zen(){
    # Was previously a part of stop_zen.
    # Separated out for use in a systemd environment
    rm -f $LOCKFILE

    if [ -x \$ACTIANZEN_ROOT/bin/mkded ] ; then
        echo "Clearing Zen shared memory: "
        cd \$ACTIANZEN_ROOT/bin; ./mkded -force
    fi

    MEMORY=\`ipcs -m | grep zen-svc | awk '{print \$2}' \`
    if [ "X\$MEMORY" != "X" ] ; then
        for i in \$MEMORY ; do
            ipcrm -m \$i
        done
    fi

    echo "Clearing semaphores: "
    SEMAFORES=\`ipcs -s | grep zen-svc | awk '{print \$2}' \`
    if [ "X\$SEMAFORES" != "X" ] ; then
        for i in \$SEMAFORES ; do
            ipcrm -s \$i
        done
    fi
    
    rm -f $PS_SEM_IPC_SEM_ID $PS_SHM_IPC_SHARED_MEM_ID

    echo ""
}

# called by "force" command after stop_zen
force_zen(){
    BTRID=\`$PS $PSPARAMS | grep -v grep | grep mkded | awk '{print \$1}'\`

    if [ "X\$BTRID" != "X" ] ; then
        echo mkded
        kill -9 \$BTRID
    fi
    echo ""
}

usage()
{
    echo "Usage: actianzen [ --ocf ] {start|stop|clean|force|restart|status}"
    exit 1
}

# Setting up environment
ACTIANZEN_ROOT=$ACTIANZEN_ROOT
PATH=\$ACTIANZEN_ROOT/bin:\$PATH
if [ \$(uname -s) = "Darwin" ]
then
    DYLD_LIBRARY_PATH=\$ACTIANZEN_ROOT/lib:\$ACTIANZEN_ROOT/lib64
    export DYLD_LIBRARY_PATH
else
    LD_LIBRARY_PATH=\$ACTIANZEN_ROOT/lib:\$ACTIANZEN_ROOT/$LIBDIR
fi
SYSINIT=other
if [ \$(uname -s) != "Darwin" ]
then
    if [ -d /run/systemd/system ]
    then
        SYSINIT=systemd
    fi
fi
cd \$ACTIANZEN_ROOT/bin

RETVAL=0
TMPVAL=0
ocf=0

if [ "\$#" -lt 1 ]
then
    usage
fi

while [ "\$#" -gt 0 ]
do
    case "\$1" in
    start)
        start_zen
        ;;
    clean)
        clean_zen
        ;;
    stop)
        stop_zen
        clean_zen
        ;;
    force)
        stop_zen
        clean_zen
        force_zen
        ;;
    restart)
        echo "Restarting Zen services: "
        stop_zen
        clean_zen
        start_zen
        echo "done."
        ;;
    status)
        echo "Status Zen services: "
        status mkded
        RETVAL=\$?
        exit \$RETVAL
        ;;
    --ocf)
        ocf=1
        ;;
    *)
    usage
    ;;
    esac

    shift
done
EORDF

# PSQL-9715: Create symlink to daemon script generated in Zen etc folder.
if [ ! $(uname -s) = "Darwin" ]
then
    chmod -R a+rx $ACTIANZEN_ROOT/etc/init.d
fi
echo

if [ $(uname -s) = "Darwin" ]
then
    chown root:wheel $RUNDAEMONFILE
else
    chown root:root $RUNDAEMONFILE
fi

chmod 755 $RUNDAEMONFILE

echo "+++++ Setting up the OCF Resource Agent $OCF_RESOURCE_AGENT ..."
# Only create OCF Resource Agent if /usr/lib is writable.
if [ -w /usr/lib ]
then
    mkdir -p "$(dirname $OCF_RESOURCE_AGENT)"

cat > "$OCF_RESOURCE_AGENT" <<EOF_OCF_RESOURCE_AGENT
#!/bin/sh

. /usr/lib/heartbeat/ocf-shellfuncs

usage()
{
    echo "Usage: \$0 {start|stop|monitor|meta-data|validate-all}" 2>&1
    echo "  Note 'validate-all' is a no-op." 2>&1
    exit "\$OCF_ERR_ARGS"
}

if [ "\$#" -ne 1 ]
then
    usage
fi

case "\$1" in
meta-data)	
    cat <<EOF
<resource-agent name="actianzen">
<shortdesc lang="en">Zen OCF Resource Agent</shortdesc>
<longdesc lang="en">
Zen Open Clustering Framework Resource Agent.
</longdesc>
<actions>
<action name="start" />
<action name="stop" />
<action name="monitor" />
<action name="meta-data" />
</actions>
</resource-agent>
EOF
    exit "\$OCF_SUCCESS"
    ;;
monitor)	
    exec "$RUNDAEMONFILE" --ocf status
    ;;
start)
    exec "$RUNDAEMONFILE" --ocf start
    ;;
stop)
    "$RUNDAEMONFILE" --ocf stop >/dev/null 2>&1 &
    pid="\$!"
    count=0

    # While "mkded" is still running.
    while ! ps -e | awk '(\$4 == "mkded") { rc=1 } END { exit rc }'
    do
        sleep 1
        count="\$((\$count + 1))"

        # Wait for approximately 15 seconds.
        if [ "\$count" -gt 15 ]
        then
            # Send a catchable signal.
            kill "\$pid" 2>/dev/null
            sleep 1
            # Send an uncatchable signal.
            kill -9 "\$pid" 2>/dev/null
            sleep 1
            break
        fi
    done

    wait "\$pid"
    exec "$RUNDAEMONFILE" --ocf force
    ;;
validate-all)	
    exit "\$OCF_SUCCESS"
    ;;
demote|migrate_to|notify|promote|reload)
    exit "\$OCF_ERR_UNIMPLEMENTED";;
*)
    usage
    ;;
esac
EOF_OCF_RESOURCE_AGENT
else
    echo "WARNING: /usr/lib is not writable - the OCF Resource Agent $OCF_RESOURCE_AGENT will not be available."
fi

# Do not create OCF Resource Agent if /usr/lib is not writable.
if [ -w /usr/lib ]
then
    if [ $(uname -s) = "Darwin" ]
    then
        chown root:wheel "$OCF_RESOURCE_AGENT"
    else
        chown root:root "$OCF_RESOURCE_AGENT"
    fi
    chmod 755 "$OCF_RESOURCE_AGENT"
fi

echo
echo "Creating the daemon links..."

if [ $(uname -s) = "Darwin" ]
then
    /bin/launchctl stop com.actian.mkde > /dev/null 2>&1

    if cd "$ACTIANZEN_ROOT/bin"
    then
        cat > launchdscript <<EOF
#!/bin/sh

trap "$RUNDAEMONFILE force ; exit 0" EXIT

$RUNDAEMONFILE start || exit 1

# Wait to be signaled.
while true
do
    sleep 1
done
EOF

        chmod 755 launchdscript
        cd - > /dev/null
    fi

    if cd /Library/LaunchDaemons
    then
        /bin/launchctl unload com.actian.mkde.plist > /dev/null 2>&1

        cat > com.actian.mkde.plist <<EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN"
    "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
    <dict>
    <key>Label</key>
        <string>com.actian.mkde</string>
    <key>Program</key>
        <string>$ACTIANZEN_ROOT/bin/launchdscript</string>
    <key>RunAtLoad</key>
        <true/>
    </dict>
</plist>
EOF

        chmod 644 com.actian.mkde.plist
        /bin/launchctl load com.actian.mkde.plist
        # Ensure engine is not running to eliminate interference with
        # engine start later in this script.
        /bin/launchctl stop com.actian.mkde
        cd - > /dev/null
    fi
else
    SYSTEMD_VER=$(systemctl --version | head -1 | cut -d" " -f2)
    echo "Systemd version: $SYSTEMD_VER"
    # ExecStopPost command is used to clean SHM/IPC resources
    # in case of abnormal termination of the engine.
    # It must be executed as root.
    if [ $SYSTEMD_VER -lt 235 ]; then
        # ! prefix  was introduced in version 235
        EXEC_PREFIX=""
        # This setting informs systemd that User/Group settings are
        # to be applied to the ExecStart command only.
        PERMS_START_ONLY="PermissionsStartOnly=true"
    else
        # Use ! prefix on command (ExecStopPost) to run as root (albeit sandboxed).
        EXEC_PREFIX="!"
        # PermissionsStartOnly is deprecated from version 240.
        PERMS_START_ONLY=""
    fi
    cat > /usr/lib/systemd/system/actianzen.service <<EOF
[Unit]
Description=Actian Zen Database Engine
After=network-online.target

[Service]
Type=simple
User=zen-svc
Group=zen-data
Environment=ACTIANZEN_ROOT=$ACTIANZEN_ROOT
Environment=PATH=$ACTIANZEN_ROOT/bin:/bin:/usr/bin
Environment=LD_LIBRARY_PATH=$ACTIANZEN_ROOT/lib64:$ACTIANZEN_ROOT/lib:/usr/lib:/usr/lib64
ExecStart=$ACTIANZEN_ROOT/bin/mkded -nofork
ExecStopPost=$EXEC_PREFIX$ACTIANZEN_ROOT/etc/init.d/actianzen clean
WorkingDirectory=$ACTIANZEN_ROOT/data
LimitNOFILE=65535
UMask=0022
$PERMS_START_ONLY

[Install]
WantedBy=multi-user.target
EOF
    chmod 644 /usr/lib/systemd/system/actianzen.service
    systemctl enable actianzen.service
fi

echo +++++ Setting up support for PAM authentication...
PWDBLIB=
PWDBLIBPARAM="shadow nullok"
SECDIR=
SECDIR1=/$LIBDIR/security

if [ $(uname -s) = "Darwin" ]
then
    PWDBLIB1=libpam.dylib
    PWDBLIB2=libpam.2.dylib
    PWDBLIB3=libpam.1.dylib
    # must match location of above dylibs and path in btrieve\unix\pam\pam_pvsw\src\pam_pvsw.c
    SECDIR1=/usr/lib   
    SECDIR2=/usr/lib/pam
else
    PWDBLIB1=pam_unix2.so
    PWDBLIB2=pam_unix.so
    PWDBLIB3=pam_pwdb.so
    SECDIR2=/usr/lib64/security
fi

if [ -d "$SECDIR1" ] ; then
    SECDIR=$SECDIR1
else    
    if [ -d "$SECDIR2" ] ; then
        SECDIR=$SECDIR2
    else
        SECDIR=
    fi
fi
if [ -f $SECDIR/$PWDBLIB1 ] ; then
    PWDBLIB=$PWDBLIB1
else
    if [ -f $SECDIR/$PWDBLIB2 ] ; then
        PWDBLIB=$PWDBLIB2
    else
        if [ -f $SECDIR/$PWDBLIB3 ] ; then
             PWDBLIB=$PWDBLIB3
        else
            PWDBLIB=
            SECDIR=
        fi
    fi
fi
if [ "X$SECDIR" != "X" ] ; then
    # Only copy PAM files if $SECDIR is writable.
    if [ -w $SECDIR ] ; then
        echo "Copying PAM files..."
        cp -f $ACTIANZEN_ROOT/bin/pvswauth $SECDIR
        cp -f $ACTIANZEN_ROOT/$LIBDIR/pam_pvsw* $SECDIR
        chown root:$GROUPNAME $SECDIR/pvswauth
        chmod 4750 $SECDIR/pvswauth
        chmod 755 $SECDIR/pam_pvsw*

        # configure pam using the .conf file or the pam.d directory
        PAMCONF=/etc/pam.conf
        PAMDIR=/etc/pam.d
        CONFIGURED=FALSE
        if [ -f $PAMCONF ] ; then
            FOUND=`grep "^pvsw64" $PAMCONF`
            if [ "X$FOUND" = "X" ] ; then
                echo "Configuring PAM file..."
                echo "pvsw64	auth	required	$SECDIR/pam_pvsw.${SO_EXTENSION}"		>> $PAMCONF
                echo "pvswauth auth	required	$SECDIR/$PWDBLIB $PWDBLIBPARAM" >> $PAMCONF
            fi
            CONFIGURED=TRUE
        fi
        if [ -d "$PAMDIR" ] ; then
            echo "Configuring PAM directory..."
            echo "auth	required	$SECDIR/pam_pvsw.${SO_EXTENSION}"		> $PAMDIR/pvsw64
            echo "auth	required	$SECDIR/$PWDBLIB $PWDBLIBPARAM" > $PAMDIR/pvswauth
            CONFIGURED=TRUE
        fi
        if [ "X$CONFIGURED" = "XFALSE" ] ; then
            echo WARNING: The PAM configuration file $PAMCONF or the directory $PAMDIR could
            echo          not be found. PAM authentication will not be available.
        fi

        # If "/$LIBDIR/libpam.${SO_EXTENSION}.0" exists and "$ACTIANZEN_ROOT/$LIBDIR" exists and
        # "$ACTIANZEN_ROOT/$LIBDIR/libpam.${SO_EXTENSION}" doesn't exist.
        if [ -e /$LIBDIR/libpam.${SO_EXTENSION}.0 -a -e "$ACTIANZEN_ROOT/$LIBDIR" -a \
            ! -e "$ACTIANZEN_ROOT/$LIBDIR/libpam.${SO_EXTENSION}" ]
        then
            $SU zen-svc $SU_ARGS -c "ln -s /$LIBDIR/libpam.${SO_EXTENSION}.0 $ACTIANZEN_ROOT/$LIBDIR/libpam.${SO_EXTENSION}"
        fi
    else
        echo "WARNING: $SECDIR is not writable - the PAM authentication mode will not be available."
    fi
else
    echo "WARNING: PAM library not found - the PAM authentication mode will not be available."
fi
echo

echo "+++++ Adding InstallInfo key and value settings to Zen Registry..."
# Populate the InstallInfo registry settings.
PRODUCT_VER=`egrep 'ProductVer=?' $ACTIANZEN_ROOT/etc/postinstall.cfg | cut -d= -f2`
VERSION_LEVEL=`egrep 'VersionLevel=?' $ACTIANZEN_ROOT/etc/postinstall.cfg | cut -d= -f2`
IS_VX=`egrep 'IsVx=?' $ACTIANZEN_ROOT/etc/postinstall.cfg | cut -d= -f2`
IS_EDGE=`egrep 'IsEdge=?' $ACTIANZEN_ROOT/etc/postinstall.cfg | cut -d= -f2`

PSREGEDIT=psregedit
if [ -f $ACTIANZEN_ROOT/bin/psregedit64 ] ; then
    PSREGEDIT=psregedit64
fi
$PSREGEDIT -set -key "PS_HKEY_CONFIG/SOFTWARE/Actian/Zen/InstallInfo/Server" -value VersionLevel $VERSION_LEVEL
$PSREGEDIT -set -key "PS_HKEY_CONFIG/SOFTWARE/Actian/Zen/InstallInfo/Server" -value InstallDir "$ACTIANZEN_ROOT"
$PSREGEDIT -set -key "PS_HKEY_CONFIG/SOFTWARE/Actian/Zen/InstallInfo/Server" -value InstallData "$ACTIANZEN_ROOT"
if [ "X$IS_VX" != "X" ] ; then
    $PSREGEDIT -set -key "PS_HKEY_CONFIG/SOFTWARE/Actian/Zen/InstallInfo/Server" -value IsVx -type PS_REG_UINT32 "$IS_VX"
fi
if [ "X$IS_EDGE" != "X" ] ; then
    $PSREGEDIT -set -key "PS_HKEY_CONFIG/SOFTWARE/Actian/Zen/InstallInfo/Server" -value IsEdge -type PS_REG_UINT32 "$IS_EDGE"
fi
$PSREGEDIT -set -key "PS_HKEY_CONFIG/SOFTWARE/Actian/Zen/InstallInfo/Server" -value ProductVersion $PRODUCT_VER

# PSQL-6827: If legacy v13 or earlier previously uninstalled, use legacy dbnames.cfg unless it is empty.
if [ -f $PVSW_ROOT/etc/dbnames.cfg ] ; then
    # Delete it if it is empty.
    if [ -f $PVSW_ROOT/etc/dbnames.cfg -a ! -s $PVSW_ROOT/etc/dbnames.cfg ]; then
        rm -f $PVSW_ROOT/etc/dbnames.cfg
    else
        echo ""
        echo "+++++ Setting DBNamesDirectory registry value to legacy location $PVSW_ROOT/etc..."
        $PSREGEDIT -set -key "PS_HKEY_CONFIG/SOFTWARE/Actian/Zen/Database Names" -value DBNamesDirectory "$PVSW_ROOT/etc"
    fi
fi

if [ -e "$ACTIANZEN_ROOT/etc/.PSRegistry" ]
then
    chown -R $USERNAME:$GROUPNAME $ACTIANZEN_ROOT/etc/.PSRegistry
fi

# PSQL-6969: If v13 or earlier previously uninstalled, export the legacy registry to registry_export_pre-zen.txt.
# Note psregedit recognizes ACTIANZEN_ROOT so we need to temporarily change it to the legacy PVSW_ROOT value.
if [ -e "$PVSW_ROOT/etc/.PSRegistry" ] ; then
   echo "Exporting legacy registry to $ACTIANZEN_ROOT/etc/registry_export_pre-zen.txt"
   TEMP_PATH=$ACTIANZEN_ROOT
   ACTIANZEN_ROOT=$PVSW_ROOT $PSREGEDIT -export -key "PS_HKEY_CONFIG/SOFTWARE/Pervasive Software" -file $TEMP_PATH/etc/registry_export_pre-zen.txt
   chown $USERNAME:$GROUPNAME $TEMP_PATH/etc/registry_export_pre-zen.txt
   chmod 664 $TEMP_PATH/etc/registry_export_pre-zen.txt
fi

# PSQL-6969: If v13 or earlier previously uninstalled, copy content from legacy odbc.ini,
# updating driver paths to new location.
ACTIANZEN_ODBCINI=$ACTIANZEN_ROOT/etc/odbc.ini
LEGACY_ODBCINI=$PVSW_ROOT/etc/odbc.ini
if [ -e "$LEGACY_ODBCINI.rpmsave" ] ; then
   if [ -f $ACTIANZEN_ODBCINI ] ; then
      echo "Archiving $ACTIANZEN_ODBCINI to $ACTIANZEN_ODBCINI.org"
      mv $ACTIANZEN_ODBCINI $ACTIANZEN_ODBCINI.org
   fi
   echo "Restoring the odbc configuration from legacy install..."
   sed -e '/^Driver/s/psql/actianzen/' $LEGACY_ODBCINI.rpmsave > $ACTIANZEN_ODBCINI
   chown $USERNAME:$GROUPNAME $ACTIANZEN_ODBCINI
fi
if [ -e "$LEGACY_ODBCINI" ] ; then
   if [ -f $ACTIANZEN_ODBCINI ] ; then
      echo "Archiving $ACTIANZEN_ODBCINI to $ACTIANZEN_ODBCINI.org"
      mv $ACTIANZEN_ODBCINI $ACTIANZEN_ODBCINI.org
   fi
   echo "Restoring the odbc configuration from legacy install..."
   sed -e '/^Driver/s/psql/actianzen/' $LEGACY_ODBCINI > $ACTIANZEN_ODBCINI
   chown $USERNAME:$GROUPNAME $ACTIANZEN_ODBCINI
fi

echo

echo "+++++ Starting the Zen daemon..."

$RUNDAEMONFILE force
$RUNDAEMONFILE start

if [ -f $ACTIANZEN_ROOT/bin/clilcadm64 ] ; then
    CLILCADM="$ACTIANZEN_ROOT/bin/clilcadm64"
else
    CLILCADM="$ACTIANZEN_ROOT/bin/clilcadm"
fi

echo "+++++ Waiting for Zen daemon to respond..."

i=0

while ! echo "$CLILCADM -i >/dev/null 2>&1" | $SU zen-svc $SU_ARGS 
do
    sleep 1
    i="$(($i + 1))"

    # If it's been over 2 minutes.
    if [ "$i" -gt 120 ]
    then
        echo "Error: Zen daemon not responding. Giving up."
        exit 1
    fi
done

sleep 1

# Install temporary license only if PVSW_PSQL_LICENSE_KEY defined in postinstall.cfg.
echo
if [ "X$PVSW_PSQL_LICENSE_KEY" = "X" ]
then
    if [ "$ProductType" = "COMMUNITY" ]
    then
        echo "+++++ Zen Server Community Edition, skipping installation of temp license..."
    else
        echo "+++++ Skipping installation of temp license: no license specified in postinstall.cfg..."
    fi
else
    echo "+++++ Installing temporary Zen license..."

    echo "$CLILCADM -a $PVSW_PSQL_LICENSE_KEY" | $SU zen-svc $SU_ARGS 
    RETVAL=$?
    if [ "$RETVAL" != "0" ]; then
        # If this is Darwin, the temporary license is already installed,
        # and there's at least one active license.
        # if [ $(uname -s) = "Darwin" ] && \
        if echo "$CLILCADM -a $PVSW_PSQL_LICENSE_KEY 2>&1 | grep '^7112: .*' > /dev/null 2>&1" | $SU zen-svc $SU_ARGS && \
            [ $(echo "$CLILCADM -i 2>&1 | grep Active | wc -l" | $SU zen-svc $SU_ARGS) -gt 0 ]
        then
            echo "The temporary Zen license is already installed and"
            echo "there's at least one active license.  Continuing..."
	    else
		    echo "Unable to install temporary Zen license, exiting installation script."
		    exit $RETVAL
	    fi
    fi
fi

if [ -e "$ACTIANZEN_ROOT/etc/.PSRegistry" ]
then
    chown -R $USERNAME:$GROUPNAME $ACTIANZEN_ROOT/etc/.PSRegistry
fi

echo



# Create the system databases
DEMODATADB="DEMODATA"
DEFAULTDB="DEFAULTDB"
SYSTEMDB="PERVASIVESYSDB"
TEMPDB="TEMPDB"
DSNNAME=DEMODATA
DBLOCATION=$ACTIANZEN_ROOT/data/$DEMODATADB
DEFAULTDBLOCATION=$ACTIANZEN_ROOT/data/samples
DEFAULTSYSDBLOCATION=$ACTIANZEN_ROOT/data/system

# If an empty dbnames.cfg exists, remove it.
if [ -f $ACTIANZEN_ROOT/etc/dbnames.cfg -a ! -s $ACTIANZEN_ROOT/etc/dbnames.cfg ]; then
    rm -f $ACTIANZEN_ROOT/etc/dbnames.cfg
fi
PVSWLOGFILE=$ACTIANZEN_ROOT/pvinst.log
echo Actian Zen Install Log File > $PVSWLOGFILE

cd $ACTIANZEN_ROOT/data
mkdir defaultdb
chown -Rf zen-svc:zen-data defaultdb
chmod -Rf 775 defaultdb
cd ../bin

echo "+++++ Creating System Databases..."
echo "setupdbcli -dir $ACTIANZEN_ROOT/data -f $ACTIANZEN_ROOT/data/w32setupdb.cfg" | $SU $USERNAME $SU_ARGS >> $PVSWLOGFILE

# Setup credentials for local access.
if [ $(uname -s) = "Darwin" ]
then
    PSWD=`od -x < /dev/urandom | awk '{ $1="" ; gsub(/ /,""); print }' |  head -c8`
else
    PSWD=`dd if=/dev/urandom count=1 2>/dev/null | tr -dc _A-Za-z0-9 |  cut -b 1-8`
fi

HOST_NAME=`uname -n`
if [ $? -ne 0 ] ; then 
    HOST_NAME=localhost
fi
echo "$ACTIANZEN_ROOT/bin/pvnetpass -a $HOST_NAME -u zen-svc -p $PSWD"  | $SU $USERNAME $SU_ARGS 
echo "$ACTIANZEN_ROOT/bin/btadmin -p $PSWD zen-svc" | $SU $USERNAME $SU_ARGS

echo


# Control Center, Builder and Docs configurations
if [ -f $ACTIANZEN_ROOT/bin/zencc -o -f $ACTIANZEN_ROOT/bin/builder ] ; then
    if [ -f $ACTIANZEN_ROOT/bin/zencc ] ; then
        echo Initializing Control Center...

        # If this is Darwin.
        if [ $(uname -s) = "Darwin" ]
        then
            $ACTIANZEN_ROOT/bin/Zen\ Control\ Center.app/Contents/MacOS/zencc -clean -initialize
        else
            echo "$ACTIANZEN_ROOT/bin/zencc -clean -initialize" | $SU $USERNAME $SU_ARGS
        fi

        echo 
    fi
    if [ -f $ACTIANZEN_ROOT/bin/builder ] ; then
        echo Initializing builder...

        # If this is Darwin.
        if [ $(uname -s) = "Darwin" ]
        then
            $ACTIANZEN_ROOT/bin/Zen\ DDF\ Builder.app/Contents/MacOS/builder -clean -initialize
        else
            echo "$ACTIANZEN_ROOT/bin/builder -clean -initialize" | $SU $USERNAME $SU_ARGS
        fi

        echo 
    fi
fi

if [ -d "$ACTIANZEN_ROOT/bin/configuration" ] ; then
    rm -Rf $ACTIANZEN_ROOT/bin/configuration/org.eclipse.help.base/index
    chmod 775 -Rf $ACTIANZEN_ROOT/bin/configuration 2>/dev/null
    chown -R $USERNAME:$GROUPNAME $ACTIANZEN_ROOT/bin/configuration
fi
if [ -d "$ACTIANZEN_ROOT/docs" ] ; then
    chmod -R 555 $ACTIANZEN_ROOT/docs
fi
PSQLHOME=`$SU $USERNAME -c "echo ~"`
chown -R $USERNAME:$GROUPNAME $PSQLHOME

# If this is Darwin.
if [ $(uname -s) = "Darwin" ]
then
    APPLICATIONS="/Applications"

    # If there is an applications directory.
    if [ -d "$APPLICATIONS" ]
    then
        ACTIAN_ZEN_15="$APPLICATIONS/Actian Zen 15"
        UTILITIES="$ACTIAN_ZEN_15/Utilities"
        SCRIPTS="$ACTIAN_ZEN_15/Scripts"
        echo "+++++ Populating the \"$ACTIAN_ZEN_15\" directory...."

        # If all of this succeeds.
        if (test -d "$ACTIAN_ZEN_15" || mkdir "$ACTIAN_ZEN_15") && \
            chmod 755 "$ACTIAN_ZEN_15" && \
            (test -d "$UTILITIES" || mkdir "$UTILITIES") && \
            chmod 755 "$UTILITIES" && \
            cp -r "$ACTIANZEN_ROOT/bin/scripts/Zen Uninstall.app" "$ACTIAN_ZEN_15" && \
            chmod -R 755 "$ACTIAN_ZEN_15/Zen Uninstall.app" && \
            cp "$ACTIANZEN_ROOT/bin/scripts/messages" "$ACTIAN_ZEN_15/.messages" && \
            chmod 644 "$ACTIAN_ZEN_15/.messages" && \
            cp "$ACTIANZEN_ROOT/bin/scripts/uninstall" "$ACTIAN_ZEN_15/.uninstall" && \
            chmod 755 "$ACTIAN_ZEN_15/.uninstall" && \
            cp -r "$ACTIANZEN_ROOT/bin/Zen Control Center.app" "$ACTIAN_ZEN_15" && \
            chmod -R 755 "$ACTIAN_ZEN_15/Zen Control Center.app" && \
            cp -r "$ACTIANZEN_ROOT/bin/Zen DDF Builder.app" "$UTILITIES" && \
            chmod -R 755 "$UTILITIES/Zen DDF Builder.app" && \
            cp -r "$ACTIANZEN_ROOT/bin/Zen Notification Viewer.app" "$UTILITIES" && \
            chmod -R 755 "$UTILITIES/Zen Notification Viewer.app" && \
            cp -r "$ACTIANZEN_ROOT/bin/Zen Phone Authorization.app" "$UTILITIES" && \
            chmod -R 755 "$UTILITIES/Zen Phone Authorization.app" && \
            (test -d "$SCRIPTS" || mkdir "$SCRIPTS") && \
            chmod 755 "$SCRIPTS" && \
            cp -r "$ACTIANZEN_ROOT/bin/scripts/Zen Repair.app" "$SCRIPTS" && \
            chmod -R 755 "$SCRIPTS/Zen Repair.app" && \
            cp "$ACTIANZEN_ROOT/bin/scripts/repair" "$SCRIPTS/.repair" && \
            cp -r "$ACTIANZEN_ROOT/bin/scripts/Zen Authorize.app" "$SCRIPTS" && \
            chmod -R 755 "$SCRIPTS/Zen Authorize.app" && \
            cp "$ACTIANZEN_ROOT/bin/scripts/authorize" "$SCRIPTS/.authorize" && \
            chmod 755 "$SCRIPTS/.authorize" && \
            cp -r "$ACTIANZEN_ROOT/bin/scripts/Zen Licenses.app" "$SCRIPTS" && \
            chmod -R 755 "$SCRIPTS/Zen Licenses.app" && \
            cp "$ACTIANZEN_ROOT/bin/scripts/licenses" "$SCRIPTS/.licenses" && \
            chmod 755 "$SCRIPTS/.licenses" && \
            cp -r "$ACTIANZEN_ROOT/bin/scripts/Zen Deauthorize.app" "$SCRIPTS" && \
            chmod -R 755 "$SCRIPTS/Zen Deauthorize.app" && \
            cp "$ACTIANZEN_ROOT/bin/scripts/deauthorize" "$SCRIPTS/.deauthorize" && \
            chmod 755 "$SCRIPTS/.deauthorize" && \
            cp -r "$ACTIANZEN_ROOT/bin/scripts/Zen Start.app" "$SCRIPTS" && \
            chmod -R 755 "$SCRIPTS/Zen Start.app" && \
            cp "$ACTIANZEN_ROOT/bin/scripts/start" "$SCRIPTS/.start" && \
            chmod 755 "$SCRIPTS/.start" && \
            cp -r "$ACTIANZEN_ROOT/bin/scripts/Zen Status.app" "$SCRIPTS" && \
            chmod -R 755 "$SCRIPTS/Zen Status.app" && \
            cp "$ACTIANZEN_ROOT/bin/scripts/status" "$SCRIPTS/.status" && \
            chmod 755 "$SCRIPTS/.status" && \
            cp -r "$ACTIANZEN_ROOT/bin/scripts/Zen Stop.app" "$SCRIPTS" && \
            chmod -R 755 "$SCRIPTS/Zen Stop.app" && \
            cp "$ACTIANZEN_ROOT/bin/scripts/stop" "$SCRIPTS/.stop" && \
            chmod 755 "$SCRIPTS/.stop" && \
            cp -r "$ACTIANZEN_ROOT/bin/scripts/Zen Restart.app" "$SCRIPTS" && \
            chmod -R 755 "$SCRIPTS/Zen Restart.app" && \
            cp "$ACTIANZEN_ROOT/bin/scripts/restart" "$SCRIPTS/.restart" && \
            chmod 755 "$SCRIPTS/.restart" && \
            cp "$ACTIANZEN_ROOT/bin/scripts/messages" "$SCRIPTS/.messages" && \
            chmod 644 "$SCRIPTS/.messages"
        then
            :
        else
            echo "Error: Unable to correctly populate the \"$ACTIAN_ZEN_15\" directory."
            exit 1
        fi

        echo
    fi
fi

# Displaying info about the license agreement
LICFILE=$ACTIANZEN_ROOT/LICENSE
if [ -f $LICFILE ] ; then
cat << EOMSG
Please read the license agreement in file $LICFILE.
Using this product indicates that you agree with all terms and
conditions stated therein. If you do not agree, you must uninstall
the product now.
EOMSG
fi
echo


echo
#display readme_zen.htm
if [ -f $ACTIANZEN_ROOT/docs/readme_zen*.htm ] ; then
echo View the README file located at:
ls $ACTIANZEN_ROOT/docs/readme_zen*.htm
echo
fi
if [ -f $ACTIANZEN_ROOT/bin/plugins/com.pervasive.psql.doc_1.0.0.jar ] ; then
echo From the Zen Control Center, you may browse the complete Zen documentation by running:
echo "    $ACTIANZEN_ROOT/bin/zencc"
echo
fi
echo Register your Zen product at:
echo "    http://www.actian.com"
echo

echo "+++++ Install has successfully completed."
echo
