#!/bin/bash
# Purpose: shortcut for build, services, commit in one run
################################################################################

set -e
set -u
set -o pipefail

# 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

# shellcheck source=./functions/main
. "${FUNCTIONS}"/main

# based on check_local_state() from scripts/status
check_for_outstanding_commits()  {
  log_debug "cd $NGCPCTL_MAIN"
  cd "$NGCPCTL_MAIN"

  if is_git_clean ; then
    return 1 # nothing to commit
  else
    return 0 # outstanding commits
  fi
}

build_args=()
check_args=()
services_args=()
export DRYRUN='false'
export NO_DB_SYNC=${NO_DB_SYNC:-}
export DRYRUN_DIRECTORY=''
export OUTPUT_DIRECTORY=${OUTPUT_DIRECTORY:-}
TEMP_DIRECTORY=''
while [ -n "${1:-}" ]; do
  case "$1" in
    *--modified-only*) build_args+=( --modified-only ) ; shift ;;
    *--ignore-branch-check*) check_args+=( --ignore-branch-check ) ; shift ;;
    *--ignore-shared-storage-check*) check_args+=( --ignore-shared-storage-check ) ; shift ;;
    *--dry-run*)
      services_args+=( --dry-run )
      DRYRUN='true'
      NO_DB_SYNC=1
      DRYRUN_DIRECTORY=$OUTPUT_DIRECTORY
      TEMP_DIRECTORY=$(mktemp -d -t ngcpcfg-apply-dry-run.XXXXXXXXXX)
      OUTPUT_DIRECTORY=$TEMP_DIRECTORY
      shift
      ;;
    *--force-all-services*) services_args+=( --force-all-services ) ; shift ;;
    *) break  ;;
  esac
done

if ! ${DRYRUN} && check_for_outstanding_commits && [ -z "${1:-}" ] ; then
  log_error "Uncommitted configuration files found."
  log_info  "Please provide commit message, like: $PN apply 'summary of your changes'"
  exit 1
fi

"${SCRIPTS}"/build "${build_args[@]}" "${check_args[@]}"
"${SCRIPTS}"/services "${services_args[@]}"

if ! ${DRYRUN} ; then
  "${SCRIPTS}"/commit "${1:-}"

  # We "commit" AFTER we "build", therefore the state information is out of date
  # and would be marked as "dirty". As we have full control over this during the
  # "apply" run let's ensure it's not marked as dirty.
  record_commit_id
fi

if [ -n "${TEMP_DIRECTORY}" ]; then
  # Clean up
  rm -rf "${TEMP_DIRECTORY}"
fi

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