import requests
import boto3
import os
import json
import datetime
import configparser

script_dir = os.path.dirname(os.path.abspath(__file__))
os.chdir(script_dir)

# File to store the last known IP address
ip_file = 'last_ip'

# Include config data
config = configparser.ConfigParser()
config.read('settings.conf')
HostedZoneId = config['Settings']['HostedZoneId']
function_name = config['Settings']['function_name']
domain_list = config['Domains']['domain_list'].split(',')
ttl = config['Settings']['TTL']
ttl = int(ttl)

# Create a Lambda client
lambda_client = boto3.client('lambda')

def get_public_ip():
    """Fetch the current public IP address."""
    response = requests.get("http://checkip.amazonaws.com")
    return response.text.strip()

def read_last_ip():
    """Read the last known IP from file."""
    if os.path.exists(ip_file):
        with open(ip_file, 'r') as file:
            return file.read().strip()
    return None

def write_last_ip(ip):
    """Write the current IP to file as the last known IP."""
    with open(ip_file, 'w') as file:
        file.write(ip)

def invoke_lambda(ip_address, domain_name, HostedZoneId, ttl):
    """Invoke the Lambda function with the current IP address."""
    response = lambda_client.invoke(
        FunctionName=function_name,
        InvocationType='RequestResponse',
        Payload=json.dumps({'public_ip': ip_address, 'domain': domain_name, 'zoneId': HostedZoneId, 'ttl': ttl})  # Pass IP and domain as part of the payload
    )
    response_payload = response['Payload'].read()
    print("Lambda response:", response_payload.decode('utf-8'))

def main():
    current_ip = get_public_ip()
    last_ip = read_last_ip()

    if current_ip != last_ip:
        print("Public IP has changed. Updating DNS by invoking AWS lambda Function...")
        for domain_name in domain_list:
            current_datetime = datetime.datetime.now()
            formatted_datetime = current_datetime.strftime("%Y-%m-%d %H:%M:%S")
            print(formatted_datetime, domain_name, current_ip)
            invoke_lambda(current_ip, domain_name, HostedZoneId, ttl)
        write_last_ip(current_ip)
    else:
        current_datetime = datetime.datetime.now()
        formatted_datetime = current_datetime.strftime("%Y-%m-%d %H:%M:%S")
        print(f"{formatted_datetime}: Public IP has not changed. No update needed, Lambda Not invoked.")

if __name__ == "__main__":
    main()

