#!/bin/bash
# Filename:      /usr/share/ngcp-ngcpcfg/helper/restore-permissions
# Purpose:       restore file/directory permissions after git clone
################################################################################

set -e
set -u

if [ "${#:-}" -ne 1 ] ; then
  echo "Usage: $0 <ngcpcfg_directory>" >&2
  exit 1
fi

# support for testsuite, assume defaults if unset
CONFIG_POOL="${CONFIG_POOL:-/etc}"
FUNCTIONS="${FUNCTIONS:-/usr/share/ngcp-ngcpcfg/functions/}"
HELPER="${HELPER:-/usr/share/ngcp-ngcpcfg/helper/}"
SKIP_NGCP_FUNCTIONS="${SKIP_NGCP_FUNCTIONS:-false}"

if "${SKIP_NGCP_FUNCTIONS}" ; then
  echo "Function 'main' is NOT loaded due to env variable SKIP_NGCP_FUNCTIONS=true"
  log_error () { echo "$@" >&2 ; }
  log_warn () { echo "$@" ; }
else
  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"
fi

# used to run a command if the file it acts on (the last parameter) exists.
maybe() {
  local command="$1"
  shift 1

  if eval [ -e "\"\$$#\"" ] ; then
    "$command" "$@"
  fi
}

target_directory="$1"
if ! [ -d "${target_directory}" ] ; then
  log_error "Directory ${target_directory} doesn't exist. Exiting."
  exit 1
fi

cd "$target_directory"

# should only be run on repositories you trust
if ! [ -e "$target_directory"/.ngcpcfg_perms ]; then
  log_warn "Permission file ${target_directory}/.ngcpcfg_perms doesn't exist."
else
  # shellcheck disable=SC1091
  . "${target_directory}"/.ngcpcfg_perms
fi

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