#!/bin/bash
set -e

# Dismiss a mako notification on the basis of its summary. Used by the first-run notifications to dismiss them after clicking for action.

if (($# == 0)); then
  echo "Usage: nomarchy-notification-dismiss <summary>"
  exit 1
fi

# Find the first notification whose 'summary' matches the regex in $1
output=$(makoctl list)

if [[ $output == "["* ]] || [[ $output == "{"* ]]; then
    # JSON format (mako 1.8+)
    # Structure is usually an array of notifications or a wrapper object
    notification_id=$(echo "$output" | jq -r --arg pat "$1" '
        if type == "array" then . 
        else .notifications // .data[0] // [] end
        | .[] | select((.summary // .["summary-text"] // "") | contains($pat)) | .id' | head -n1)
else
    # Human format (older mako)
    notification_id=$(echo "$output" | grep -F "$1" | head -n1 | sed -E 's/^Notification ([0-9]+):.*/\1/')
fi

if [[ "$notification_id" =~ ^[0-9]+$ ]]; then
  makoctl dismiss -n "$notification_id"
fi
