#!/usr/bin/python3
import json
import subprocess
from jdsu.mts.ScpiAccess import ScpiAccess, EsrError
import time
import logging
import os

########################################
# Check key(s) in a dictionary
def checkKey(dict, key):
    if key in dict.keys():
        return dict[key] 
    else:
        return None 
def checkKeys(dict, liste):
    subdict=dict
    for n in range(0, len(liste)):
        if not subdict:
            return None
        elem = checkKey(subdict,liste[n])
        if elem == None:
            return None
        subdict=subdict[liste[n]]
    return elem

########################################
def do_credentials():
   ret=0
   password = checkKeys(params, ['credentials', 'cli', 'password' ])
   if password != None:
      cmd="echo root:%s | chpasswd"%password
      ret = subprocess.call(cmd, shell=True)
   return ret 
   
########################################
def do_snmp():
   ret=0
   snmp_value = checkKeys(params, ['snmp_polling_agent','active' ])
   if snmp_value != None:
      if snmp_value == True:
         otu.SendCommand("OTU:API:CONF:SNMP:AGENT TRUE")
      else:
         otu.SendCommand("OTU:API:CONF:SNMP:AGENT FALSE")
   snmp_value = checkKeys(params, ['snmp_polling_agent','community' ])
   if snmp_value != None:
      cmd = "sed -i -r 's/^com2sec readwrite default.*/com2sec readwrite default     %s/' /etc/snmp/snmpd.conf"%snmp_value
      ret += subprocess.call(cmd, shell=True)
   snmp_value = checkKeys(params, ['snmp_polling_agent','port' ])
   if snmp_value != None:
      cmd = "sed -i -r 's/^agentAddress .*/agentAddress udp:%s,tcp:%s,udp6:%s,tcp6:%s/' /etc/snmp/snmpd.conf"\
              %(snmp_value,snmp_value,snmp_value,snmp_value)      
      ret += subprocess.call(cmd, shell=True)
   return ret

########################################
def do_ipv4():
   ip_value = checkKeys(params, ['ipv4_management','dhcp' ])
   if ip_value == True: 
      otu.SendCommand("OTU:SYST:COM:MODE DHCP")
   if ip_value == False:
      otu.SendCommand("OTU:SYST:COM:MODE FIX")
      ip_value = checkKeys(params, ['ipv4_management','ip' ])
      if ip_value != None:
         ip_value=ip_value.replace('.',',')
         otu.SendCommand("OTU:SYST:COM:IP ETH0,%s"%ip_value)
      ip_value = checkKeys(params, ['ipv4_management','subnet_mask' ])
      if ip_value != None:
         ip_value=ip_value.replace('.',',')
         otu.SendCommand("OTU:SYST:COM:SUBNET ETH0,%s"%ip_value)
      ip_value = checkKeys(params, ['ipv4_management','gateway' ])
      if ip_value != None:
         ip_value=ip_value.replace('.',',')
         otu.SendCommand("OTU:SYST:COM:GATE %s"%ip_value)
      ip_value = checkKeys(params, ['ipv4_management','dns' ])
      if ip_value != None:
         ip_value=ip_value.replace('.',',')
         otu.SendCommand("OTU:SYST:COM:DNS %s"%ip_value)
      ip_value = checkKeys(params, ['ipv4_management','domain' ])
      if ip_value != None:
         otu.SendCommand("OTU:SYST:COM:DOMAIN \"%s\""%ip_value)

########################################
def do_ipv6():
   ip_value = checkKeys(params, ['ipv6_management','dhcp' ])
   if ip_value == True:
      otu.SendCommand("OTU:SYST:COM:IPV6:MODE DHCP")
   if ip_value == False:
      otu.SendCommand("OTU:SYST:COM:IPV6:MODE FIX")
      ip_value = checkKeys(params, ['ipv6_management','ip' ])
      if ip_value != None:
         otu.SendCommand("OTU:SYST:COM:IPV6:IP ETH0,\"%s\""%ip_value)
      ip_value = checkKeys(params, ['ipv6_management','gateway' ])
      if ip_value != None:
         otu.SendCommand("OTU:SYST:COM:IPV6:GATE \"%s\""%ip_value)
      ip_value = checkKeys(params, ['ipv6_management','dns' ])
      if ip_value != None:
         otu.SendCommand("OTU:SYST:COM:IPV6:DNS \"%s\""%ip_value)
      ip_value = checkKeys(params, ['ipv6_management','site' ])
      if ip_value != None:
          otu.SendCommand("OTU:SYST:COM:IPV6:SITE \"%s\""%ip_value)

if __name__ == "__main__":
    start_time = time.time()
    details=""
    status="Success"
    ztp_file='/tmp/ztp.conf'
    result_code=0
    try:
        logging.basicConfig(filename='/var/log/user.log',level=logging.DEBUG,\
                            format='%(asctime)s ztp: %(message)s',datefmt='%b %d %H:%M:%S')
        with open( ztp_file, 'r') as fic:
           data = fic.read()
        otu=ScpiAccess("localhost", 1400, 60, "*PASS \"RTU\"\"PASSWORD\"\n")
        params = json.loads(data)
        if( do_credentials() != 0 ):
            details+="echec on credentials, "
            status="Failure"
            result_code=1
        if ( do_snmp() != 0 ):
            details+="failure during snmp setting, "
            status="Failure"
            result_code=1
        do_ipv4()
        do_ipv6()
    except Exception as err:
        status="Failure"
        result_code=1
        details=err
    finally:
        #if os.path.exists(ztp_file):
        #   os.remove(ztp_file)
        print("status       : %s"%status)
        print("result_code  : %d"%result_code)
        print("duration     : %.1f second(s)"%(time.time()-start_time))
        print("details      : %s"%details)
        logging.info("status       : %s"%status)
        logging.info("result_code  : %d"%result_code)
        logging.info("duration     : %.1f second(s)"%(time.time()-start_time))
        logging.info("details      : %s"%details)
        if result_code == 0:
           otu.SendCommand("OTU:SYST:REB")
        exit(result_code)
