#!/usr/bin/env bash
#
# Runs one effect script with the notification in its environment.
#
#   ar-effect <type> ['<json>']
#
# json: {"effect": {"type": ..., ...options}, "notification": {...}, "rule": {"name": ...}}
#
# The script is ~/.config/attention-required/effects/<type> if you wrote one,
# otherwise effects/<type> next to this plugin. It runs with:
#   AR_APP, AR_SUMMARY, AR_BODY, AR_KEY, AR_URGENCY   the notification
#   AR_RULE                                           the rule that matched
#   AR_EFFECT                                         the effect type
#   AR_OPT_<NAME>                                     each option on the effect, upper-cased
#   AR_PAYLOAD                                        the whole json
set -uo pipefail

type=${1:-}
payload=${2:-'{}'}
[[ -n $type ]] || { echo "usage: ar-effect <type> [json]" >&2; exit 2; }
[[ $type =~ ^[A-Za-z0-9_.-]+$ ]] || { echo "attention-required: bad effect name '$type'" >&2; exit 2; }

here=$(cd "$(dirname "$(readlink -f "$0")")/.." && pwd)
config_dir=${XDG_CONFIG_HOME:-$HOME/.config}/attention-required

script=
for candidate in "$config_dir/effects/$type" "$here/effects/$type"; do
  if [[ -f $candidate && -x $candidate ]]; then
    script=$candidate
    break
  fi
done
[[ -n $script ]] || {
  echo "attention-required: no effect named '$type' (looked in $config_dir/effects and $here/effects)" >&2
  exit 1
}

command -v jq >/dev/null 2>&1 || { echo "jq is not installed" >&2; exit 1; }

# NUL-separated so a body with newlines survives the trip.
while IFS= read -r -d '' kv; do
  export "$kv"
done < <(jq -j '
  def env_key: ascii_upcase | gsub("[^A-Z0-9]"; "_");
  ((.notification // {}) | to_entries[]
    | select((.value | type) == "string" or (.value | type) == "number" or (.value | type) == "boolean")
    | "AR_\(.key | env_key)=\(.value | tostring)\u0000"),
  "AR_RULE=\(.rule.name // "")\u0000",
  "AR_EFFECT=\(.effect.type // "")\u0000",
  ((.effect // {}) | to_entries[]
    | select(.key != "type")
    | "AR_OPT_\(.key | env_key)=\(.value | if type == "string" then . else tojson end)\u0000")
' <<<"$payload" 2>/dev/null)

export AR_PAYLOAD=$payload
export AR_PLUGIN_DIR=$here
exec "$script"
