#!/bin/sh
set -eu
TOKEN_FILE="${MERCHANT_TOKEN_FILE:-/run/secrets/merchant-access-token}"
SECRET_FILE="${PAIVANA_SECRET_FILE:-/run/secrets/paivana-secret}"
TEMPLATE="${PAIVANA_CONF_TEMPLATE:-/etc/paivana/paivana.conf.template}"
OUT="${PAIVANA_CONF:-/tmp/paivana.conf}"

if [ ! -r "$TOKEN_FILE" ]; then
  echo "missing merchant token: $TOKEN_FILE" >&2
  exit 1
fi
if [ ! -r "$SECRET_FILE" ]; then
  echo "missing paivana secret: $SECRET_FILE" >&2
  exit 1
fi

TOKEN=$(tr -d '\n\r' < "$TOKEN_FILE")
SECRET=$(tr -d '\n\r' < "$SECRET_FILE")

awk -v t="$TOKEN" -v s="$SECRET" '
{
  gsub(/@MERCHANT_ACCESS_TOKEN@/, t)
  gsub(/@PAIVANA_SECRET@/, s)
  print
}
' "$TEMPLATE" > "$OUT"
chmod 600 "$OUT"

exec paivana-httpd -c "$OUT" -g -f -L INFO
