#!/bin/bash
# Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved.
#
# This script is run by rpm after the rpm is installed.
# It should do any special setup that needs to be done for the serverconfig
# components for an install or an upgrade.
# Usage: postinstall install_flag
# Where install_flag is a number that tells you if this is a fresh installation
# or an upgrade. 
# install_flag == 1 - Initial install
# install_flag == 2 - Upgrade

#
# Exit codes
#
OK=0
FAIL=1

#
# Check we have the necessary arguments.
# 

if [ $# -lt 1 -o $# -gt 1 ]
then
    echo "Usage: $0 install_flag"
    exit $FAIL
fi

if [ -z "${INSTDIR}" ]
then
    echo "INSTDIR not set"
    exit $FAIL
fi

INSTALL_FLAG="$1"
UPGRADE="false"
if [ ${INSTALL_FLAG} -eq 2 ]
then
    UPGRADE="true"
elif [ ${INSTALL_FLAG} -ne 1 ]
then
    echo "Invalid install_flag: ${INSTALL_FLAG}"
    exit $FAIL
fi

SERVERCONFIG_TEMPLATES="${INSTDIR}/etc/templates/var/serverconfig"
VAR_DIR="${INSTDIR}/var"
SERVERCONFIG_DIR="${VAR_DIR}/serverconfig"

MODE=027

# If there is no existing config (left from an erased install or on upgrade)
# then create one
if [ ! -d "${SERVERCONFIG_DIR}" ]
then
    umask $MODE
    cp -pr "${SERVERCONFIG_TEMPLATES}" "${VAR_DIR}"

  peerdns=""
  _localbootprops="${INSTDIR}/var/serverconfig/local/bootstrap.properties"
  [ -s "${_localbootprops}" ] && peerdns=`sed -n '/server\.dns\.peer=/s/.*=//p' "${_localbootprops}" | tail -1`
  [ -z "${peerdns}" ] && peerdns=`${INSTDIR}/bin/bin/ttahostname`

    EXTNAMES="--tarantella-config-server-netservice-proxy-externalnames"
    $INSTDIR/bin/tarantella config edit $EXTNAMES "*:$peerdns" &> /dev/null
    BINDADDR="--tarantella-config-server-bindaddresses-external"
    $INSTDIR/bin/tarantella config edit $BINDADDR "*" &> /dev/null
else
    # Copy over any new property files

    # Find property files in the "pristine" directory that do not
    # exist in the SGD Admin var/serverconfig directory
    find "${SERVERCONFIG_TEMPLATES}" "${SERVERCONFIG_DIR}" "${SERVERCONFIG_DIR}" -name "*.properties" -printf '%P\n' | sort | uniq -u | while IFS= read -r FILE; do
        cp -p "${SERVERCONFIG_TEMPLATES}/$FILE" "${SERVERCONFIG_DIR}/$FILE"
    done

    # Add any new values to the existing configuration
    # Parse all the pristine property files for the properties and make sure
    # the property exists in the file in the SGD serverconfig dir
    find "${SERVERCONFIG_TEMPLATES}" -maxdepth 2 -type f -name "*.properties"  -printf '%P\n' | while IFS= read -r FILE; do
        while IFS="=" read -r attr value; do
            case "${attr}" in
              '#'*) ;;
              *)
                  if ! grep -q "${attr}=" "${SERVERCONFIG_DIR}/${FILE}"
                  then
                       echo "${attr}=${value}" >> "${SERVERCONFIG_DIR}/${FILE}"
                  fi
              ;;
            esac
        done < "${SERVERCONFIG_TEMPLATES}/${FILE}"
    done
fi

exit $OK
