#!/usr/bin/env bash
set -u

warn() {
  printf 'Notification warning: %s\n' "$*" >&2
}

branch_name="${BRANCH_NAME:-${GITHUB_REF_NAME:-}}"
if [ -z "$branch_name" ] && [ -n "${GITHUB_REF:-}" ]; then
  branch_name="${GITHUB_REF#refs/heads/}"
fi
if [ -z "$branch_name" ]; then
  branch_name="unknown"
fi

short_sha="${SHORT_SHA:-}"
if [ -z "$short_sha" ] && command -v git >/dev/null 2>&1; then
  short_sha="$(git rev-parse --short HEAD 2>/dev/null || true)"
fi
if [ -z "$short_sha" ]; then
  short_sha="unknown"
fi

notify_url="${ACTION_NOTIFY_WEBHOOK_URL:-}"
if [ -z "$notify_url" ]; then
  warn "ACTION_NOTIFY_WEBHOOK_URL is not configured, skip notification."
  exit 0
fi

deploy_env="${DEPLOY_ENV:-unknown}"
job_status="${ACTION_JOB_STATUS:-unknown}"

run_url=""
if [ -n "${GITHUB_SERVER_URL:-}" ] && [ -n "${GITHUB_REPOSITORY:-}" ] && [ -n "${GITHUB_RUN_ID:-}" ]; then
  run_url="${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}"
fi
if [ -z "$run_url" ]; then
  run_url="${GITHUB_SERVER_URL:-unknown}"
fi

export ACTION_NOTIFY_MESSAGE="$(cat <<EOF
$job_status $deploy_env/$branch_name $short_sha
$run_url
EOF
)"

payload="$(node <<'NODE'
const payload = {
  message: process.env.ACTION_NOTIFY_MESSAGE,
};

process.stdout.write(JSON.stringify(payload));
NODE
)"

if [ "${FLOW_NOTIFY_DRY_RUN:-}" = "1" ]; then
  printf 'Action notification dry run URL: %s\n' "$notify_url"
  printf 'Action notification dry run payload: %s\n' "$payload"
  exit 0
fi

if ! curl -fsS \
  -X POST "$notify_url" \
  -H "Content-Type: application/json" \
  -d "$payload" >/dev/null; then
  warn "failed to send action notification."
  exit 0
fi

echo "Sent action notification."
