#!/bin/bash

network_plugin=$(sudo docker plugin ls --format '{{.Name}}' | grep '^kasmweb/sidecar:' | tail -n 1)

if [ -z "$network_plugin" ]; then
  echo "No kasmweb/sidecar plugin found"
  exit 1
fi

is_enabled=$(sudo docker plugin inspect --format '{{.Enabled}}' "$network_plugin")
if [ "$is_enabled" = "true" ]; then
  echo "Plugin already enabled: $network_plugin"
  exit 0
fi

# Unfortunately, it seems the plugin sometimes doesn't create the unix socket on time and
# docker does not take unix socket creation into account when specyfing timeouts.
echo "Enabling plugin: $network_plugin"
max_attempts=30
attempt=1

while [ $attempt -le $max_attempts ]; do
  if sudo docker plugin enable "$network_plugin"; then
    echo "Successfully enabled plugin: $network_plugin"
    exit 0
  fi
  
  echo "Attempt $attempt failed. Retrying in 1 second..."
  sleep 1
  attempt=$((attempt + 1))
done

echo "Failed to enable plugin after $max_attempts attempts"
exit 1