File: //bigscoots/cpanel/ptr.sh
#!/bin/bash
# Function to output JSON formatted results
output() {
echo "{\"errors\": [], \"messages\": [\"$1\"], \"success\": $2, \"result\": {}}" | jq
}
# Input Validation
if [[ -z $1 || -z $2 ]]; then
output "Usage: $0 <RIP> <RHOSTNAME>" "false"
exit 1
fi
RIP=$1
RHOSTNAME=$2
# Parse IP into reverse DNS format
RLO=$(echo "${RIP}" | awk -F. '{print $4}')
PTRABBR=$(echo "${RIP}" | awk -F. '{print $3"." $2"."$1}')
PTRZONE=$(echo "${PTRABBR}".in-addr.arpa)
# --- STEP 1: REMOVE EXISTING RECORDS ---
# We loop to ensure multiple records for the same IP are cleared
while :; do
# Use jq to find the 'Line' number for the specific record name
# Note: WHM API requires the trailing dot in the name field for matches
DNSLINE=$(whmapi1 dumpzone domain="${PTRZONE}" --output=json | \
jq -r ".data.zone[0].record[] | select(.name == \"${RLO}.${PTRZONE}.\") | .Line // empty" | head -1)
# If no Line number is found, there are no more records to delete
if [[ -z "$DNSLINE" ]]; then
break
fi
output "Attempting removal from zone=${PTRZONE} on line=${DNSLINE} for ${RIP}" "true"
if ! whmapi1 removezonerecord zone="${PTRZONE}" line="${DNSLINE}" > /dev/null 2>&1; then
output "FAILED: Could not remove line=${DNSLINE} from zone=${PTRZONE}" "false"
# Exit loop on failure to prevent an infinite loop
break
else
output "SUCCESS: Removed line=${DNSLINE} from zone=${PTRZONE}" "true"
fi
done
# --- STEP 2: ADD NEW RECORD ---
# Verify if the record still exists (it shouldn't) before adding the new one
CHECK_EXISTS=$(whmapi1 dumpzone domain="${PTRZONE}" --output=json | \
jq -r ".data.zone[0].record[] | select(.name == \"${RLO}.${PTRZONE}.\") | .name // empty")
if [[ -z "$CHECK_EXISTS" ]]; then
output "Adding PTR record to zone=${PTRZONE} for ${RIP} -> ${RHOSTNAME}" "true"
if ! whmapi1 addzonerecord zone="${PTRZONE}" name="${RLO}" ptrdname="${RHOSTNAME}" type=PTR > /dev/null 2>&1; then
output "FAILED: Adding to zone=${PTRZONE} for ${RIP} : ${RHOSTNAME}" "false"
else
output "SUCCESS: Added PTR record for ${RIP} : ${RHOSTNAME}" "true"
fi
else
output "SKIPPED: A record for ${RLO}.${PTRZONE} still exists. Check zone manually." "false"
fi