#!/usr/bin/python3

import xml.etree.ElementTree as ET
import sys

if len(sys.argv) != 3:
    print("Usage: " + sys.argv[0] + " in_file out_file")
    sys.exit(1)

ifile = sys.argv[1]
ofile = sys.argv[2]

itree = ET.parse(ifile)
iroot = itree.getroot()

if iroot.tag != 'AddressBook':
    print('Invalid input xml format')
    sys.exit(2)

oroot = ET.Element('YealinkIPPhoneBook')

otitle = ET.SubElement(oroot, 'Title')
otitle.text = 'Yealink'

ogroups = {}
for igroup in iroot.findall('pbgroup'):
    ogroup = ET.SubElement(oroot, 'Menu')
    iname = igroup.find('name').text or ''
    iid = igroup.find('id').text
    ogroup.set('Name', iname)
    ogroups[iid] = ogroup

for icontact in iroot.findall('Contact'):
    ifirstname = icontact.find('FirstName').text or ''
    ilastname = icontact.find('LastName').text or ''
    igroup = icontact.find('Group').text

    ocontact = ET.SubElement(ogroups[igroup], 'Unit')

    oname = (ilastname + ' ' + ifirstname).strip()
    ocontact.set('Name', oname)

    ocontact.set('Phone1', '')
    ocontact.set('Phone2', '')
    ocontact.set('Phone3', '')
    ocontact.set('default_photo', 'Resource:')

    for iphone in icontact.findall('Phone'):
        if iphone.attrib['type'] == 'Work':
            inumber = iphone.find('phonenumber').text or ''
            ocontact.set('Phone1', inumber)

for ogroup in ogroups.values():
    if not len(ogroup):
        oroot.remove(ogroup)

otree = ET.ElementTree(oroot)
otree.write(ofile, encoding='unicode', xml_declaration=True)
