#!/bin/bash
set -eou pipefail

readonly API_URL="https://api.gandi.net/v5"
readonly APIKEY=$(pass api/gandi)

function curl_plain(){ 
	exec 3>&1
	HTTP_STATUS=$(/usr/bin/curl -s -w "%{http_code}" -o >(cat >&3) -H 'Accept: text/plain' -H "Authorization: Apikey $APIKEY" "$@")
}

function curl(){ 
	exec 3>&1
	HTTP_STATUS=$(/usr/bin/curl -s -w "%{http_code}" -o >(cat >&3) -H "Authorization: Apikey $APIKEY" "$@")
}

tmpdir(){
	template="$PROGRAM.XXXXXXXXXXXXX"
	SECURE_TMPDIR="$(mktemp -d "/dev/shm/$template")"
	remove_tmpfile() {
		rm -rf "$SECURE_TMPDIR"
	}
	trap remove_tmpfile EXIT
}

show_response(){
	test -p /dev/stdin && input="$(</dev/stdin)"
	if [ "$(jq -r '.status' <<< "$input")" == "error" ]; then
		jq -r '"return: \(.status)"' <<< "$input"
		jq -r '.errors[] | "\(.line): \(.cause)"' <<< "$input"
	else
		jq -r ".message" <<< "$input"
	fi
}

PROGRAM="${0##*/}"
COMMAND="$1"

case "$COMMAND" in
	list)
		curl "$API_URL/livedns/domains" | jq -r ".[].fqdn"
		;;
	records)
		shift
		curl_plain "$API_URL/livedns/domains/$1/records"
		;;
	snapshots)
		shift
		DOMAIN="$1"
		echo "UUID					Created"
		curl "$API_URL/livedns/domains/$DOMAIN/snapshots" | jq -r '.[] | [.id, .created_at] | @tsv'
		;;
	show-snapshot)
		shift; DOMAIN="$1"
		shift; UUID="$1"
		curl "$API_URL/livedns/domains/$DOMAIN/snapshots/$UUID"
		;;
	edit)
		shift; 
		session_id=""
		while true; do
			case "$1" in
				-s|--session)      shift; session_id=$1; shift; break ;;
				*) break ;;
			esac
		done
		DOMAIN="$1"
		tmpdir
		tmp_file="$(mktemp -u "$SECURE_TMPDIR/XXXXXX")-${DOMAIN}.txt"
		if [ -z "$session_id" ]; then
			curl_plain "$API_URL/livedns/domains/$DOMAIN/records" > "$tmp_file"
		else
			# Doesn't work
			ZONE_HREF=$(curl "$API_URL/livedns/domains/$DOMAIN" | jq -r ".zone_href")
			curl "$ZONE_HREF/snapshots/$session_id" > "$tmp_file"
		fi
		$EDITOR "$tmp_file"
		curl -X PUT -H "Content-Type: text/plain" --data-binary "@$tmp_file" "$API_URL/livedns/domains/$DOMAIN/records"
		# if [ "$HTTP_STATUS" = "200" ]; then
			# if [ -z ${ZONE_HREF+x} ]; then
			# 	ZONE_HREF=$(curl "$API_URL/domains/$DOMAIN" | jq -r ".zone_href")
			# fi
			# curl -X POST "$ZONE_HREF/snapshots" | jq -r ".message"
		# fi
		;;
esac
