#!/usr/bin/env python3
# Print out custom template UUIDs in CLI comma-separated minimal format
# (c) Anil Madhavapeddy, Citrix Systems Inc, 2008

import atexit
import contextlib
import sys

import XenAPI


def logout(session):
    with contextlib.suppress(Exception):
        session.xenapi.session.logout()

def main(argv):
    try:
        session = XenAPI.xapi_local()
        session.xenapi.login_with_password("", "", "1.0", "xen-api-scripts-custom-template")
        atexit.register(logout, session)

        templates = session.xenapi.VM.get_all_records_where('field "is_a_template" = "true" and field "is_a_snapshot" = "false"' )
    except Exception as e:
        print(type(e).__name__, "retrieving template list:", e, file=sys.stderr)
        sys.exit(1)

    output=[]
    for tmplref in templates:
        tmplrec = templates[tmplref]
        try:
            if "default_template" not in tmplrec["other_config"] or tmplrec["other_config"]["default_template"] != 'true':
                output.append(tmplrec["uuid"])
        except KeyError:
            pass

    print(str.join(",", output))
    session.xenapi.logout()

if __name__ == "__main__":
    main(sys.argv[1:])
