#!/bin/bash
# Purpose: search for existing .tt2 (template toolkit) files
#          and generate configuration files based on ngcpcfg's config
################################################################################

set -e
set -u

# support testsuite
FUNCTIONS="${FUNCTIONS:-/usr/share/ngcp-ngcpcfg/functions/}"
HELPER="${HELPER:-/usr/share/ngcp-ngcpcfg/helper/}"
SCRIPTS="${SCRIPTS:-/usr/share/ngcp-ngcpcfg/scripts/}"

if ! [ -r "${FUNCTIONS}"/main ] ; then
  printf "Error: %s/main could not be read. Exiting.\n" "${FUNCTIONS}" >&2
  exit 1
fi

. "${FUNCTIONS}"/main

MODIFIED_ONLY=false
check_args=()
if [ -n "${1:-}" ] ; then
  case "$1" in
    *--modified-only*) MODIFIED_ONLY=true ; shift ;;
    *--ignore-branch-check*) check_args+=( --ignore-branch-check ) ; shift ;;
    *--ignore-shared-storage-check*) check_args+=( --ignore-shared-storage-check ) ; shift ;;
  esac
fi

# Sanity check the YAML and schema files.
# NOTE: we can't blindly pass "$@" to the check script,
#       so explicitly check and add option as needed
"${SCRIPTS}"/check "${check_args[@]}"

"${SCRIPTS}"/patch "$@"

# Kill all previous started tt2-daemon Perl processes if they were not stopped properly
killall tt2-daemon 2>/dev/null || true

if [ -n "${NGCP_SOCKETFILE:-}" ] ; then
  log_debug "Using $NGCP_SOCKETFILE as tt2-daemon socket file as set via 'NGCP_SOCKETFILE'."
else
  NGCP_SOCKETFILE='/var/run/ngcpcfg.socket'
fi

rm -f "${NGCP_SOCKETFILE}"

# Start new tt2-daemon Perl process
"${HELPER}"/tt2-daemon

# Load all the configs in proper order and check their avialability and valid YAML syntax
for f in ${NGCPCTL_CONFIG:-} ${HOST_CONFIG:-} ${LOCAL_CONFIG:-} ${NETWORK_CONFIG:-} "${EXTRA_CONFIG_FILES[@]}" ${CONSTANTS_CONFIG:-} ; do
  if [ -r "$f" ] ; then
    if ! "${HELPER}/tt2-wrapper" "/dev/null" "${f}" ; then
      log_error "tt2-daemon cannot load ${f}:"
      "${HELPER}/tt2-wrapper" "/dev/null" "${f}"
      exit 1
    fi
  fi
done

build_config_files() {
  # prepare tmp file to be reused hundred times inside "${HELPER}/build_config"
  tmp_output_dir="$(mktemp -d --tmpdir ngcpcfg.PID"${NGCPCFG_PID}".XXXXXXXXXX)"
  tmp_output_file="${tmp_output_dir}/tmp_output_file"

  for input_file in $(generate_template_list "$@") ; do

    log_debug "calculate output file" # {{{
    x=${input_file##${NGCPCTL_MAIN}/templates/}         # drop leading /etc/ngcp-config
    y=${x%%.tt2}                                        # drop trailing suffix '.tt2'
    [ -n "${HA_FILE:-}" ]   && y=${y%%.tt2${HA_FILE}}   # drop trailing suffix '.tt2.sp{1,2}'
    [ -n "${PAIR_FILE:-}" ] && y=${y%%.tt2${PAIR_FILE}} # drop trailing suffix '.tt2.pairname'
    [ -n "${HOST_FILE:-}" ] && y=${y%%.tt2${HOST_FILE}} # drop trailing suffix '.tt2.hostname'
    output_file=${y%%.customtt}                         # drop trailing suffix '.customtt'
    # }}}

    log_debug "${HELPER}/build_config ${input_file} ${output_file}"
    "${HELPER}/build_config" "${input_file}" "${output_file}" "${tmp_output_file}"
  done

  record_commit_id

  rm -f "${tmp_output_file}"
  rmdir "${tmp_output_dir}"
}

# main script

if ! $MODIFIED_ONLY ; then
  build_config_files "$@"
else
  log_info "Considering modified files only due to --modified-only option."

  if is_git_clean ; then
    log_info "No changes found, nothing to do."
    exit 0
  fi

  trigger_rebuild=false

  for file in "${EXTRA_CONFIG_FILES[@]}" ; do
    if git diff-index --name-only HEAD | grep -qe -- "$(basename "$file")" ; then
      log_debug "modification in EXTRA_CONFIG_FILES file ${file} found"
      trigger_rebuild=true
      break # no reason for further checks
    fi
  done

  if git diff-index --name-only HEAD | grep -q \
         -e "$(basename "$NGCPCTL_CONFIG")" \
         -e "$(basename "$HOST_CONFIG")" \
         -e "$(basename "$LOCAL_CONFIG")" \
         -e "$(basename "$NETWORK_CONFIG")" \
         -e "$(basename "$CONSTANTS_CONFIG")" ; then
    log_debug "modification in main configuration file found"
    trigger_rebuild=true
  fi

  if $trigger_rebuild ; then
    log_info "Main configuration file(s) has been changed, running full rebuild."
    log_debug "Executing: build_config_files $*"
    build_config_files "$@"
  fi

  if git diff-index --name-only HEAD | grep -q templates/ || \
     git status --porcelain | awk '/^\?\? / {print $2}' 2>/dev/null | grep -q templates/ ; then
     log_debug "Template config changed, identifying files."
     for file in $(git diff-index --name-only HEAD) \
                 $(git status --porcelain | awk '/^\?\? / {print $2}') ; do
        build_file="${file##templates/}"
        build_file="${build_file%%.services}"
        build_file="${build_file%%.customtt}"

        # drop HA file suffix of all registered nodes
        if [ -r /etc/ngcp-config/systems.cfg ] ; then
          while IFS= read -r host ; do
            build_file="${build_file%%.${host}}"
          done < /etc/ngcp-config/systems.cfg
        fi

        build_file="${build_file%%.tt2}"
        build_file="/${build_file}"

        # generate file list
        case "${file_list:-}" in
          # avoid duplicates
          *"${build_file}"*) # do nothing
            ;;
          # append to file list
          *) file_list=" ${file_list:-} $build_file"
            ;;
        esac
     done

     log_debug "Executing: build_config_files ${file_list}"
     build_config_files "${file_list}"
  fi
fi

# Kill all previous started tt2-daemon Perl processes
killall tt2-daemon 2>/dev/null || true
rm -f "${NGCP_SOCKETFILE}"

# Apply configured file ownership and permissions
for f in ${NGCPCTL_CONFIG:-} ${HOST_CONFIG:-} ${LOCAL_CONFIG:-} "${EXTRA_CONFIG_FILES[@]}" ; do
  if [ ! -f "${f}" ]; then
    continue
  fi
  if [ -n "${CONFIG_USER}" ]; then
    chown "${CONFIG_USER}" "${f}"
  fi
  if [ -n "${CONFIG_GROUP}" ]; then
    chgrp "${CONFIG_GROUP}" "${f}"
  fi
  if [ -n "${CONFIG_CHMOD}" ]; then
    chmod "${CONFIG_CHMOD}" "${f}"
  fi
done
if [ -f "${NETWORK_CONFIG:-}" ]; then
  if [ -n "${NETWORK_CONFIG_USER}" ]; then
    chown "${NETWORK_CONFIG_USER}" "${NETWORK_CONFIG}"
  fi
  if [ -n "${NETWORK_CONFIG_GROUP}" ]; then
    chgrp "${NETWORK_CONFIG_GROUP}" "${NETWORK_CONFIG}"
  fi
  if [ -n "${NETWORK_CONFIG_CHMOD}" ]; then
    chmod "${NETWORK_CONFIG_CHMOD}" "${NETWORK_CONFIG}"
  fi
fi
if [ -f "${CONSTANTS_CONFIG:-}" ]; then
  if [ -n "${CONSTANTS_CONFIG_USER}" ]; then
    chown "${CONSTANTS_CONFIG_USER}" "${CONSTANTS_CONFIG}"
  fi
  if [ -n "${CONSTANTS_CONFIG_GROUP}" ]; then
    chgrp "${CONSTANTS_CONFIG_GROUP}" "${CONSTANTS_CONFIG}"
  fi
  if [ -n "${CONSTANTS_CONFIG_CHMOD}" ]; then
    chmod "${CONSTANTS_CONFIG_CHMOD}" "${CONSTANTS_CONFIG}"
  fi
fi

exit 0

## END OF FILE #################################################################
