apiVersion: batch/v1beta1
kind: CronJob
metadata:
  name: dns-update
spec:
  schedule: "0 * * * *"
  successfulJobsHistoryLimit: 1
  failedJobsHistoryLimit: 3
  concurrencyPolicy: Forbid
  jobTemplate:
    spec:
      template:
        spec:
          restartPolicy: OnFailure
          imagePullSecrets: 
            - name: registry.internal.aleemhaji.com
          containers:
            - name: dns-updater
              image: registry.internal.aleemhaji.com/crons:latest
              command:
                - sh
                - -xec
                - |
                  curl "https://www.namesilo.com/api/dnsListRecords?version=1&type=xml&key=${NAMESILO_API_KEY}&domain=aleemhaji.com" | \
                    sed 's+<resource_record>+\'$'\n+g' | sed 's+</resource_record>+\'$'\n+g' | grep record_id | while read line; do
                      if echo $line | grep '<type>A</type>' > /dev/null; then
                        curl "https://www.namesilo.com/api/dnsUpdateRecord?version=1&type=xml&key=${NAMESILO_API_KEY}&domain=aleemhaji.com&rrid=$(echo $line | sed -E 's/.*<record_id>([0-9a-f]{32}).*/\1/')&rrvalue=$(curl https://icanhazip.com)&rrttl=7207"
                      elif echo $line | grep '<type>CNAME</type>' > /dev/null; then
                        if echo $line | grep '<value>aleemhaji.com</value>' > /dev/null; then
                          echo "Skipping CNAME update because it's already correctly set."
                        else
                          curl "https://www.namesilo.com/api/dnsUpdateRecord?version=1&type=xml&key=${NAMESILO_API_KEY}&domain=aleemhaji.com&rrid=$(echo $line | sed -E 's/.*<record_id>([0-9a-f]{32}).*/\1/')&rrhost=$(echo $line | sed -E 's/.*<host>([^<]*).*/\1/' | sed 's/.aleemhaji.com//')&rrvalue=aleemhaji.com&rrttl=7207"
                        fi
                      elif echo $line | grep '<type>TXT</type>' > /dev/null; then
                        echo "Skipping TXT record because there's nothing to do with it"
                      else
                        echo "Can't handle record ($line)"
                      fi
                    done
              env:
                - name: NAMESILO_API_KEY 
                  valueFrom:
                    secretKeyRef:
                      name: namesilo-api-key
                      key: value
