#!/bin/bash

# Script to update GoDaddy DNS records for DevOps dashboard

# Load GoDaddy credentials from environment variables
# These should be set in .zshrc:
# export GODADDY_API_KEY="your_key"
# export GODADDY_API_SECRET="your_secret"

if [ -z "$GODADDY_API_KEY" ] || [ -z "$GODADDY_API_SECRET" ]; then
  echo "Error: GODADDY_API_KEY and GODADDY_API_SECRET environment variables must be set"
  echo "Set them in your .zshrc file"
  exit 1
fi

DOMAIN="bytelyst.com"
SERVER_IP="187.124.159.82"

# Function to add or update A record
update_dns_record() {
  local subdomain=$1
  local record_name="${subdomain}.${DOMAIN}"

  echo "Updating DNS record for ${record_name} -> ${SERVER_IP}"

  # Check if record exists
  response=$(curl -s -X GET "https://api.godaddy.com/v1/domains/${DOMAIN}/records/A/${subdomain}" \
    -H "Authorization: sso-key ${GODADDY_API_KEY}:${GODADDY_API_SECRET}" \
    -H "Content-Type: application/json")

  if [ -n "$response" ] && [ "$response" != "[]" ]; then
    # Update existing record
    echo "Record exists, updating..."
    curl -s -X PUT "https://api.godaddy.com/v1/domains/${DOMAIN}/records/A/${subdomain}" \
      -H "Authorization: sso-key ${GODADDY_API_KEY}:${GODADDY_API_SECRET}" \
      -H "Content-Type: application/json" \
      -d "[{\"data\": \"${SERVER_IP}\", \"ttl\": 600}]"
  else
    # Create new record
    echo "Record does not exist, creating..."
    curl -s -X PATCH "https://api.godaddy.com/v1/domains/${DOMAIN}/records" \
      -H "Authorization: sso-key ${GODADDY_API_KEY}:${GODADDY_API_SECRET}" \
      -H "Content-Type: application/json" \
      -d "[{\"data\": \"${SERVER_IP}\", \"name\": \"${subdomain}\", \"ttl\": 600, \"type\": \"A\"}]"
  fi

  echo "✓ Updated ${record_name}"
}

# Update DNS records
update_dns_record "devops"
update_dns_record "admin"

echo ""
echo "DNS records updated successfully!"
echo "Please allow a few minutes for DNS propagation."
