#!/usr/bin/env python3
#-*- encoding: utf-8 -*-

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import requests
import json
import re
import socket

# Config
domain="soutade.fr"
API_KEY = "YOUR-KEY"
livedns_api = "https://dns.api.gandi.net/api/v5/"
dyndns_url = 'http://checkip.dyndns.com/'
headers = {
    'X-Api-Key': API_KEY,
}
A_RECORD_NAME="@" # Record of A type

def get_ipv6():
    s = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
    s.connect(('2001:4860:4860::8888', 1))
    return s.getsockname()[0]

def get_ipv4():
    response = requests.get(dyndns_url)
    if response.ok:
        pattern = re.compile('[^:]*(\d+\.\d+\.\d+\.\d+)')
        result = pattern.search(response.text, 0)
        if result == None:
            print("No IP found")
            exit(1) 
        else:
            return result.group(0).strip()
    # Bad gateway
    elif response.status_code in (502,504):
        exit(0)
    else:
        print("Connexion error")
        response.raise_for_status()
        exit(1)
    
def update_gandi_record(domain_records_href, record, current_ip):
    # Get recorded IP
    response = requests.get(f'{domain_records_href}/{A_RECORD_NAME}/{record}', headers=headers)

    if (response.ok):
        record = response.json()
    else:
        print("Failed to look for recorded IP")
        if response.status_code != 502: # Bad gateway
            response.raise_for_status()
        exit(1)
     
    print('Old IP : %s' % (record['rrset_values'][0]))

    if current_ip != record['rrset_values'][0]:
        record['rrset_values'][0] = current_ip

        # PUT new IP
        response = requests.put(f'{domain_records_href}/{A_RECORD_NAME}/{record}',
                                headers=headers, json=record)

        if (response.ok):
            print("IP updated")
        else:
            print("something went wrong")
            if response.status_code != 502: # Bad gateway
                response.raise_for_status()
            exit(1)
        
        exit(34) # IP updated return !!

# Get current IP
current_ip = get_ipv4()
print(f'Your Current IP is {current_ip}')

# Retrieve domains address
response = requests.get(livedns_api + "domains", headers=headers)
if (response.ok):
    domains = response.json()
else:
    if response.status_code != 502: # Bad gateway
        response.raise_for_status()
    exit(1)

domain_index = next((index for (index, d) in enumerate(domains) if d["fqdn"] == domain), None)

if domain_index == None:
    # domain not found
    print("The requested domain {domain} was not found in this gandi account")
    exit(1)

domain_records_href = domains[domain_index]["domain_records_href"]
update_gandi_record(domain_records_href, 'A', current_ip)

current_ip = get_ipv6()
print(f'Your Current IP is {current_ip}')

domain_records_href = domains[domain_index]["domain_records_href"]
update_gandi_record(domain_records_href, 'AAAA', current_ip)
    
exit(0)
