03_ad/ad-dynamic-dns-inject.sh
#!/usr/bin/env bash

### BEGIN SCRIPT HEADER
SCRIPT_PATH=$(readlink -f "${BASH_SOURCE[0]}")
SCRIPT_NAME=$(basename "${SCRIPT_PATH}")
DIR_SCRIPT=$(dirname "${SCRIPT_PATH}")
DIR_ROOT=$(dirname $DIR_SCRIPT)
HELPER="${DIR_ROOT}/01_pwnbox/tools-helper.sh"
source "$HELPER" || exit
### END SCRIPT HEADER

### BEGIN COMMON
function print_usage_and_exit {
    print_info "Usage: ${SCRIPT_NAME} <add|del> fqdn [ip]"
    exit
}

check_argc $# 2 || print_usage_and_exit
### END COMMON

function record_add {
    if [ $# -eq 2 ]
    then
        ns=$(get_dns_servers || return)
        arg_server=$(echo "${ns}" | head -n1)
        arg_fqdn=$1
        arg_ip=$2
        res=$(echo -e "server ${arg_server}\nupdate add ${arg_fqdn} 86400 A ${arg_ip}\nsend\nquit\n" | nsupdate 2>&1)
        if [ $? -eq 0 ]
        then
            print_success "Added record '${arg_fqdn} -> ${arg_ip}' on DNS server ${arg_server}"
        else
            print_error "Failed to add record: '${res}'"
        fi
    else
        print_error "Invalid number of arguments"
        print_usage
    fi
}

function record_del {
    if [ $# -eq 1 ]
    then
        ns=$(get_dns_servers || return)
        arg_server=$(echo "${ns}" | head -n1)
        arg_fqdn=$1
        res=$(echo -e "server ${arg_server}\nupdate delete ${arg_fqdn} A\nsend\nquit\n" | nsupdate 2>&1)
        if [ $? -eq 0 ]
        then
            print_success "Deleted record '${arg_fqdn}' on DNS server ${arg_server}"
        else
            print_error "Failed to delete record: '${res}'"
        fi
    else
        print_error "Invalid number of arguments"
        print_usage
    fi
}

case $1 in
    "add")
        record_add ${@:2}
        ;;
    "del")
        record_del ${@:2}
        ;;
    *)
        print_error "Unknown command: ${1}"
        ;;
esac