#!/usr/bin/env bash
set -euo pipefail

root=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)
config_path=

while (($#)); do
  case $1 in
    --config)
      if (($# < 2)); then
        printf 'catalog-import: --config requires a path\n' >&2
        exit 64
      fi
      config_path=$2
      shift 2
      ;;
    *)
      printf 'catalog-import: unknown argument: %s\n' "$1" >&2
      exit 64
      ;;
  esac
done

if [[ -z $config_path || ! -r $root/$config_path ]]; then
  printf 'catalog-import: configuration file %s is not readable\n' "${config_path:-<unset>}" >&2
  exit 78
fi

# The fixture configuration is shell-compatible and contains data only.
# shellcheck disable=SC1090
source "$root/$config_path"

if [[ ${PROFILE-} != production || -z ${SOURCE_FILE-} ]]; then
  printf 'catalog-import: invalid application configuration\n' >&2
  exit 78
fi
if [[ ! -r $root/$SOURCE_FILE ]]; then
  printf 'catalog-import: source file %s is not readable\n' "$SOURCE_FILE" >&2
  exit 66
fi
if [[ -z ${UNIT_OUTPUT_DIR-} || -z ${UNIT_START_NUMBER-} ]]; then
  printf 'catalog-import: supervisor runtime variables are missing\n' >&2
  exit 70
fi

header=$(sed -n '1p' "$root/$SOURCE_FILE")
if [[ $header != $'sku\tquantity' ]]; then
  printf 'catalog-import: source header is invalid\n' >&2
  exit 65
fi

record_count=$(awk 'NR > 1 { count++ } END { print count + 0 }' "$root/$SOURCE_FILE")
mkdir -p "$UNIT_OUTPUT_DIR"
{
  printf 'service=catalog-import.service\n'
  printf 'profile=%s\n' "$PROFILE"
  printf 'source=%s\n' "$SOURCE_FILE"
  printf 'records=%s\n' "$record_count"
  printf 'start=%s\n' "$UNIT_START_NUMBER"
} >"$UNIT_OUTPUT_DIR/catalog-import.receipt"
