#!/bin/bash

TYPE="$1"
NAME="$2"
STATE="$3"
PRIORITY="$4"

. /opt/aep/etc/provider_api

API_TOKEN="${API_TOKEN:?missing variable: \$API_TOKEN}"
API_URL="${API_URL:?missing variable: \$API_URL}"
# One or more floating IPs. `flip_ids` is a whitespace-separated list; a file
# that only has the older single `flip_id` keeps working unchanged. When both
# are set, `flip_ids` wins (it is expected to contain `flip_id` as well).
flip_ids="${flip_ids:-${flip_id:-}}"
flip_ids="${flip_ids:?missing variable: \$flip_ids or \$flip_id}"

is_json() {
  jq -re '.' <<<"${1:-}" >/dev/null 2>&1
}

case "$STATE" in
  MASTER)
    server_id="$(curl -sSL http://169.254.169.254/hetzner/v1/metadata/instance-id)"
    # One assign per floating IP, one after the other. A failure of one does
    # not stop the others: every address that can move, moves. The response
    # (or error text) of each call goes to the log with its id.
    for id in $flip_ids; do
      case "$id" in
        *[!0-9]*|'') echo "floating-ip-hetzner: skipping invalid id '${id}'"; continue ;;
      esac
      rsp="$(curl -X POST "${API_URL}/floating_ips/${id}/actions/assign" -sSL -H "Authorization: Bearer ${API_TOKEN}" -H 'Content-Type: application/json' -d '{"server":'"$server_id"'}')"
      if is_json "$rsp"; then
        echo "floating-ip-hetzner ${id}: $(echo "$rsp" | jq -c -r '.')"
      else
        echo "floating-ip-hetzner ${id}: ${rsp}"
      fi
    done
    exit 0
    ;;
  BACKUP|STOP|FAULT)
    exit 0
    ;;
  *)
    echo "Unknown state: ${STATE}"
    exit 1
    ;;
esac
