#!/bin/bash
#
# pdns-tools
# https://git.stack-source.com/msb/pdns-tools
# Copyright (c) 2023 Matthew Saunders Brown <matthewsaundersbrown@gmail.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)

# load include file
source $(dirname $0)/pdns.sh

help()
{
  thisfilename=$(basename -- "$0")
  echo "$thisfilename"
  echo "Set/update PTR Record."
  echo ""
  echo "usage: $thisfilename -i <ip> [-r <record>] [-l <ttl>] [-s <status>] [-c <comment>] [-a <account>] [-h]"
  echo ""
  echo "  -h            Print this help."
  echo "  -i <ip>       IP address to set PTR record for."
  echo "  -r <record>   Data/value (hostname) of PTR record, optional."
  echo "  -l <ttl>      TTL, optional, defaults to $zone_defaults_ttl."
  echo "  -s <0|1>      Status, optional. O (default) for active or 1 for disabled."
  echo "  -c <comment>  An optional comment/note about the record."
  echo "  -a <account>  The account that the comment gets attributed too."
  echo "                Only used if comment is set. Optional, defaults to hostname of server running this script."
  echo
  echo "                This script sets or updates the PTR record of a given IP."
  echo "                The <record> should be a FQDN (Fully Qualified Domain Name) or left blank."
  echo "                If the <record> is blank then a default value will be set, effectively re-setting the PTR record to it's default."
}

pdns:getoptions "$@"

# check for IP
if [[ -z $ip ]]; then
  echo "IP is required"
  exit
fi

# set zone & name
OIFS=$IFS
IFS='.'
ip_parts=($ip)
IFS=$OIFS
zone=${ip_parts[2]}.${ip_parts[1]}.${ip_parts[0]}.in-addr.arpa.
name=${ip_parts[3]}.$zone

# check that zone exists
if pdns-zone-ext.sh -z $zone >> /dev/null; then

  # zone exists, build & execute command
  cmd="pdns-rr-rep.sh -z $zone -n $name -t PTR"

  # check for record data, create default if unset
  if [[ -z $record ]]; then
    record=${ip_parts[0]}-${ip_parts[1]}-${ip_parts[2]}-${ip_parts[3]}.in-addr.arpa.`dig +short $zone soa|cut -d ' ' -f 2|cut -d "." -f 2-`
  fi
  cmd="$cmd -r $record"

  if [[ -n $ttl ]]; then
    cmd="$cmd -l $ttl"
  fi

  if [[ -n $status ]]; then
    cmd="$cmd -s $status"
  fi

  if [[ -n $comment ]]; then
    cmd="$cmd -c $comment"
  fi

  if [[ -n $account ]]; then
    cmd="$cmd -a $account"
  fi

  echo $cmd

else
  echo "Zone for $zone does not exist, can't set PTR."
fi