#!/bin/sh

# Configurations
CF_API_EMAIL="your_cloudflare_email"
CF_API_KEY="your_cloudflare_api_key"
DOMAIN="your_domain_name"
RECORD_NAME="your_record_name" # e.g., "www" for www.example.com
IP_FILE="/root/$RECORD_NAME.$DOMAIN.txt"
CF_API="https://api.cloudflare.com/client/v4"
# Get the current IP address
CURRENT_IP=$(curl -s ip.plus/myip)
# Check if IP has changed
if [ -f "$IP_FILE" ]; then
    OLD_IP=$(cat "$IP_FILE")
else
    OLD_IP=""
fi

if [ "$CURRENT_IP" = "$OLD_IP" ]; then
    echo "No changes in IP address. No update needed."
    exit 0
fi
# Get Zone ID
ZONE_ID=$(curl -s -X GET "$CF_API/zones?name=$DOMAIN" \
     -H "X-Auth-Email: $CF_API_EMAIL" \
     -H "X-Auth-Key: $CF_API_KEY" \
     -H "Content-Type: application/json" | grep -o '"id":"[^"]*' | head -1 | cut -d'"' -f4)
if [ -z "$ZONE_ID" ]; then
    echo "Error: Could not retrieve Zone ID."
    exit 1
fi
# Get Record ID
RECORD_ID=$(curl -s -X GET "$CF_API/zones/$ZONE_ID/dns_records?type=A&name=$RECORD_NAME.$DOMAIN" \
     -H "X-Auth-Email: $CF_API_EMAIL" \
     -H "X-Auth-Key: $CF_API_KEY" \
     -H "Content-Type: application/json" | grep -o '"id":"[^"]*' | head -1 | cut -d'"' -f4)
if [ -z "$RECORD_ID" ]; then
    echo "No DNS record found. Creating a new one."
    CREATE_RESPONSE=$(curl -s -X POST "$CF_API/zones/$ZONE_ID/dns_records" \
        -H "X-Auth-Email: $CF_API_EMAIL" \
        -H "X-Auth-Key: $CF_API_KEY" \
        -H "Content-Type: application/json" \
        --data "{\"type\":\"A\",\"name\":\"$RECORD_NAME.$DOMAIN\",\"content\":\"$CURRENT_IP\",\"ttl\":120,\"proxied\":false}")
    if echo "$CREATE_RESPONSE" | grep -q '"success":true'; then
        echo "DNS record created successfully."
        echo "$CURRENT_IP" > "$IP_FILE"
    else
        echo "Error: Failed to create DNS record."
        echo "Response: $CREATE_RESPONSE"
        exit 1
    fi
else
    echo "Updating existing DNS record."
    UPDATE_RESPONSE=$(curl -s -X PUT "$CF_API/zones/$ZONE_ID/dns_records/$RECORD_ID" \
        -H "X-Auth-Email: $CF_API_EMAIL" \
        -H "X-Auth-Key: $CF_API_KEY" \
        -H "Content-Type: application/json" \
        --data "{\"type\":\"A\",\"name\":\"$RECORD_NAME.$DOMAIN\",\"content\":\"$CURRENT_IP\",\"ttl\":120,\"proxied\":false}")
    if echo "$UPDATE_RESPONSE" | grep -q '"success":true'; then
        echo "DNS record updated successfully."
        echo "$CURRENT_IP" > "$IP_FILE"
    else
        echo "Error: Failed to update DNS record."
        echo "Response: $UPDATE_RESPONSE"
        exit 1
    fi
fi