#!/bin/bash
set +e

kasm_id=$1
container_name=$2
container_ns_id=$3
notification_pipe=$4

log() {
  echo "$(date '+%Y-%m-%d %H:%M:%S') | $1 | ${kasm_id} | $2" >> /var/log/kasm-sidecar/network_sidecar.log
}

log "Starting notification bridge for container \"$container_name\""

# ensure the notification pipe exists
if [ ! -p "$notification_pipe" ]; then
  log "error" "Notification pipe not found: $notification_pipe"
  exit 1
fi

sleep 1

# ensure the container has a valid notification binary available
notification_method=""

if docker exec -i $container_name which kdialog &> /dev/null; then
  notification_method="kdialog"
elif docker exec -i $container_name which notify-send &> /dev/null; then
  notification_method="notify-send"
else
  notification_method="none"
  log "Unable to show container notifications, neither notify-send nor kdialog found in container \"$container_name\""
fi

log "Container \"$container_name\" notification method: $notification_method"

# 
while true; do
  if read notification < "$notification_pipe"; then
    if [ "$notification_method" == "none" ]; then
      continue
    fi

    icon=$(echo $notification | cut -d: -f1)
    title=$(echo $notification | cut -d: -f2 | base64 -d)
    message=$(echo $notification | cut -d: -f3 | base64 -d)
    icon_path="/usr/share/extra/icons/egress_${icon}.svg"

    if [ "$notification_method" == "notify-send" ]; then
      notification_command="notify-send -u critical -i '$icon_path' -t 0 '$title' '$message'"
    else
      notification_command="kdialog --title '$title' --passivepopup '$message' --icon '$icon_path'"
    fi

    until docker exec -i $container_name sh -c "$notification_command" &> /dev/null; do
      sleep 5
    done

    sleep 1
  fi
done