#!/bin/bash

# Copyright (c) 2018 Liam Stanley <me@liamstanley.io>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

# email of the account in mention
auth_email="your@email.com"
# key found in the cloudflare account settings menu
auth_key="<your-key>"
# zone in cloudflare -- this is usually just the base domain name
zone_name="domain.com"
# record in cloudflare to update -- can be root or subdomain
record_name="example.domain.com"
# delay in seconds to check for ip changes
delay=30

###########
IP_URL="http://ipv4.icanhazip.com"
API_URL="https://api.cloudflare.com/client/v4"
###########

function log { echo -e "[$(date '+%y/%m/%d %H:%M:%S')] >> $@"; }
function getip { curl -s "$IP_URL"; }
function waitdelay { log "sleeping for $delay seconds..."; sleep $delay; }

function api {
    METHOD=$1
    URI=$2
    shift 2
    curl -s -H "X-Auth-Email: ${auth_email}" -H "X-Auth-Key: ${auth_key}" -H "Content-Type: application/json" -X "$METHOD" "${API_URL}${URI}" $@
}

log " -   email: $auth_email"
log " -    zone: $zone_name"
log " -  record: $record_name"
log " -  ip-url: $IP_URL"
log " - api-url: $API_URL"

log "sending info requests..."
zone_id=$(api GET "/zones?name=${zone_name}" | grep -Po '(?<="id":")[^"]*' | head -1)
record_id=$(api GET "/zones/${zone_id}/dns_records?name=${record_name}" | grep -Po '(?<="id":")[^"]*')
log "info: zone[$zone_id] record[$record_id]"


oldip=""

while true;do
    log "checking if our ip has changed... (url: $IP_URL)"
    ip=$(getip)
    log "ip: $ip"

    if [ "$ip" == "$oldip" ];then
        log "no changes.. skipping"
        waitdelay
        continue
    fi

    oldip=$ip

    log "sending update request..."
    update=$(api PUT "/zones/${zone_id}/dns_records/${record_id}" --data "{\"id\":\"${zone_id}\",\"type\":\"A\",\"name\":\"${record_name}\",\"content\":\"${ip}\"}")

    if [[ $update == *"\"success\":false"* ]]; then
        log "request failed; results:\n$update"
        exit 1 
    else
        message="IP changed to: $ip"
        log "record ${record_name} changed to: $ip"
    fi

    waitdelay
done

