#!/bin/sh

# Redirect stdout and stderr to a log file
exec > >(tee -a /dns/logs.txt) 2>&1

ACTION=$1
DOMAIN=$2
VALUE=$3


# Insert or remove DNS record based on the action
if [ "$ACTION" = "present" ]; then
    echo "Inserting DNS record for $DOMAIN with value $VALUE"
    url="$ENDPOINT/create_dns_record"
    data="{ \"record\": \"$DOMAIN\", \"value\": \"$VALUE\", \"number\" : \"$CUSTOMER_NUMBER\", \"apikey\" : \"$APIKEY\" }"
    http_status_code=$(wget --server-response --header="Content-Type: application/json" --post-data="$data" "$url" -O /dev/null 2>&1 | grep "HTTP/" | awk '{print $2}')
    echo "[$http_status_code]"
    if [ "$http_status_code" = "200" ]; then
        echo "HTTP Status Code is 200. Exiting with status code 0."
        sleep 5
	exit 0
    else
        echo "HTTP Status Code is not 200. Exiting with status code 1."
        exit 1
    fi
elif [ "$ACTION" = "cleanup" ]; then
    echo "Removing DNS record for $DOMAIN"
    url="$ENDPOINT/delete_dns_record"
    data="{ \"record\": \"$DOMAIN\", \"number\" : \"$CUSTOMER_NUMBER\", \"apikey\" : \"$APIKEY\" }"
    http_status_code=$(wget --server-response --header="Content-Type: application/json" --post-data="$data" "$url" -O /dev/null 2>&1 | grep "HTTP/" | awk '{print $2}')
    echo "[$http_status_code]"
    if [ "$http_status_code" = "200" ]; then
        echo "HTTP Status Code is 200. Exiting with status code 0."
        sleep 5
	exit 0
    else
        echo "HTTP Status Code is not 200. Exiting with status code 1."
        exit 1
    fi
fi