#!/usr/bin/env bash
printf 'hcloud %s\n' "$*" >> "$STUB_LOG"
kind=$1 verb=$2
state="$STUB_STATE/$kind"
case "$verb" in
  create)
    if [ "$kind" = server ]; then
      type=$(printf '%s\n' "$@" | grep -A1 -x -- '--type' | tail -n1)
      if [ -s "$state" ]; then echo "name is already used (uniqueness_error)" >&2; exit 1; fi
      for bad in ${STUB_UNAVAILABLE_TYPES:-}; do [ "$type" = "$bad" ] && { echo "server type unavailable" >&2; exit 1; }; done
      if [ "$type" = "${STUB_CREATE_LEAVES_SERVER:-}" ]; then echo "server-id" >> "$state"; echo "action timed out" >&2; exit 1; fi
      echo '{"server":{"id":4711}}'
    fi
    echo "${kind}-id" >> "$state" ;;
  list) cat "$state" 2>&1 | grep -v 'No such file' || true ;;
  delete) grep -vx -- "$3" "$state" > "$state.new" || true; mv "$state.new" "$state" ;;
  ip) if [ "$3" = "-6" ]; then echo "2001:db8::1"; else echo "192.0.2.10"; fi ;;
  add-rule) : ;;
  *) echo "stub hcloud: unexpected $*" >&2; exit 2 ;;
esac
