#!/bin/sh

set -eu

usage() {
  echo <<EOF
Usage: $(basename "$0") [option]

Resolve local puavo api server from dns.  If the device type is bootserver,
laptop or wirelessaccesspoint, cloud fallback will be used by default,
meaning that in case dns resolve fails it will return the address of cloud
puavo-rest.

  --cloud-fallback      Fallback to cloud puavo-rest if dns lookup fails
  --no-cloud-fallback   Do not fallback to cloud puavo-rest
  --writable            Search for writable puavo-rest instance
EOF
}

opt_cloud_fallback=false
use_dns=true

puavo_hosttype=$(cat /etc/puavo/hosttype)
if [    "$puavo_hosttype" = 'bootserver' \
     -o "$puavo_hosttype" = 'laptop'     \
     -o "$puavo_hosttype" = 'wirelessaccesspoint' ]; then
  opt_cloud_fallback=true
fi

while true; do
  case "${1:-}" in
    -c|--cloud-fallback)
      opt_cloud_fallback=true
      shift
      ;;
    -n|--no-cloud-fallback)
      opt_cloud_fallback=false
      shift
      ;;
    -w|--writable)
      # at the moment only the cloud API server is writable
      opt_cloud_fallback=true
      use_dns=false
      shift
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    --)
      break
      ;;
    '')
      break
      ;;
    *)
      printf "Unknown option %s\n" "${1:-}"
      exit 1
      ;;
  esac
done

puavo_domain=$(cat /etc/puavo/domain)

lookup_puavo_apiserver() {
  if [ -n "${PUAVO_CERT_VERSION:-}" ]; then
    cert_version="$PUAVO_CERT_VERSION"
  else
    cert_version=$(puavo-conf puavo.admin.certs.versions | awk '{ print $1 }')
  fi

  host -t SRV -W 1 "_puavo-api_${cert_version}._tcp.${puavo_domain}" \
    | awk -v puavo_domain="$puavo_domain" '
        $2 == "has" && $3 == "SRV" && $4 == "record" {
          sub(/\.$/, "", $8)

          # check that $8 has puavo_domain-suffix
          i = index($8, puavo_domain)
          if (i == 0) { next }
          if ($8 == (substr($8, 0, i-1) puavo_domain)) {
            printf "https://%s:%s\n", $8, $7
            exit(0)
          }
        }'
}

if $use_dns; then
  puavo_apiserver=$(lookup_puavo_apiserver)
  if [ -n "$puavo_apiserver" ]; then
    printf "%s\n" "$puavo_apiserver"
    exit 0
  fi
fi

if $opt_cloud_fallback; then
  puavo_apiserver=$(puavo-conf puavo.www.apiserver)
  if [ -n "$puavo_apiserver" ]; then
    printf "%s\n" "$puavo_apiserver"
    exit 0
  fi
fi

echo "Failed to resolve api server" >&2
exit 1
