#!/usr/bin/python3

import json
import ovh
import sys
import argparse
import os
import re

file_name =  os.path.basename(sys.argv[0])
conf_file = "/usr/local/etc/"+file_name+".rc"


def config_read():
    with open(conf_file) as file:
        data = json.load(file)
        api_endpoint = (data.get("endpoint"))
        api_apKey = (data.get("application_key"))
        api_secret = (data.get("application_secret"))
        api_cKey = (data.get("consumer_key"))
        return api_endpoint,api_apKey,api_secret,api_cKey


def client_connect():
    client = ovh.Client(
        endpoint=api_endpoint,
        application_key=api_apKey,
        application_secret=api_secret,
        consumer_key=api_cKey,
    )
    return client


def argparse_readwrite():
    parser = argparse.ArgumentParser(prog=file_name, description='Read or alter dns objects via OVH api')
    subparsers = parser.add_subparsers(help='mode', dest='mode')

    # Read options
    parser_read = subparsers.add_parser("read", 
                                          help="Get object properties")

    parser_read.add_argument("-z", 
                                "--zone", 
                                required=True, 
                                help="zoneName, e.g. domain.com")

    parser_read.add_argument("-f",
                                "--fieldtype",
                                help="fieldType, e.g. TLSA")
    
    parser_read.add_argument("-i",
                                "--recordid",
                                help="recordid")
    
    parser_read.add_argument("-p",
                                "--prop",
                                help="Property, e.g. target, fieldType, id, zone, ttl, subDomain")
    
    parser_read.add_argument("-v",
                                "--verbose",
                                action="store_true",
                                help="Verbose mode")

    
    # Write options
    parser_write = subparsers.add_parser("write", 
                                help="Alter object properties")

    parser_write.add_argument("-z", 
                                "--zone", 
                                required=True,
                                help="zoneName, e.g. domain.com")

    parser_write.add_argument("-i", 
                                "--recordid",
                                required=True,
                                help="recordid of record")

    parser_write.add_argument("-t", 
                                "--target",
                                required=True,
                                help="target of record")
                                

    args = parser.parse_args()
  


    if args.mode == 'write': 
        printwrite(args.zone, args.recordid, args.target)
        writedata(args.zone, args.recordid, args.target)
    elif args.mode == 'read':
        if args.fieldtype:
            if args.verbose:
                printread(args.zone, args.fieldtype)
            print(json.dumps(read_all_data(args.zone, args.fieldtype, args.verbose, args.prop), indent=4))
        elif args.recordid:
            print(read_data(args.zone, args.recordid, args.prop))


def printwrite(zone, recordid, target): 
        print("Write criteria:\n")
        print("ZoneName: "+zone+"")
        print("Id: "+recordid+"")
        print("Target: "+target+"")


def printread(zone, fieldtype):
        print("Search criteria:\n")
        print("ZoneName: "+zone+"")
        print("FieldType: "+fieldtype+"\n")


def read_all_data(zone, fieldtype, verbose, prop):
    content = []
    client = client_connect()

    try:
        result = client.get('/domain/zone/'+zone+'/record', fieldType=fieldtype)
        if prop:
            prop = prop
        else:
            prop = "subDomain"
        if verbose:
            for record in result:
                content.append(client.get('/domain/zone/'+zone+'/record/{}'.format(record)))
            return content
        elif prop:
            return dict( { "data": [ dict({"{#RECORDID}":str(record), "{#PROPERTY}":read_data(zone, record, prop)}) for record in result ] } )
    except ovh.exceptions.ResourceNotFoundError:
        print("Something went wrong...!\nPlease check zoneName and/or FieldType")
    except ovh.exceptions.BadParametersError:
        print("FieldType not found...!")


def read_data(zone, recordid, prop):
    client = client_connect()

    try:
        content = client.get('/domain/zone/'+zone+'/record/{}'.format(recordid))
        if prop:
            try:        
                data = json.loads(json.dumps(content))
                return data[prop]
            except KeyError:
                print("Property not found...! Try: target, fieldType, id, zone, ttl, subDomain")
        else:
            return json.dumps(content, indent=4)
    except ovh.exceptions.ResourceNotFoundError:
        print("Something went wrong...!\nPlease check zoneName and/or FieldType")
    except ovh.exceptions.BadParametersError:
        print("FieldType not found...!")


def writedata(zone, recordid, target):
    client = client_connect()
    result = client.put('/domain/zone/'+zone+'/record/{}'.format(recordid),target=target)
    client.post('/domain/zone/'+zone+'/refresh')


if __name__ == "__main__":
    try:
        api_endpoint,api_apKey,api_secret,api_cKey = config_read()
        argparse_readwrite()
        
    except IOError:
        print("Config file "+conf_file+" not found...!")
    except TypeError:
        print("Config file "+conf_file+" not found...!")
