#! /opt/oci/bin/python

import logging
import subprocess
import sys

import citc_oci
import oci


def handle_exception(exc_type, exc_value, exc_traceback):
    if issubclass(exc_type, KeyboardInterrupt):
        sys.__excepthook__(exc_type, exc_value, exc_traceback)
        return

    log.critical("Uncaught exception", exc_info=(exc_type, exc_value, exc_traceback))


sys.excepthook = handle_exception

log = logging.getLogger("stopnode")
log.setLevel(logging.INFO)
handler = logging.FileHandler('/var/log/slurm/elastic.log')
formatter = logging.Formatter('%(asctime)s %(name)-10s %(levelname)-8s %(message)s')
handler.setFormatter(formatter)
log.addHandler(handler)

config = oci.config.from_file()

nodespace = citc_oci.get_nodespace()

hosts = subprocess.run(["scontrol", "show", "hostnames", sys.argv[1]], stdout=subprocess.PIPE).stdout.decode().split()

for host in hosts:
    log.info(f"Stopping {host}")

    try:
        matching_nodes = oci.core.ComputeClient(config).list_instances(nodespace["compartment_id"], display_name=host).data
        node_id = [n.id for n in matching_nodes if n.lifecycle_state not in {"TERMINATED", "TERMINATING"}][0]

        oci.core.ComputeClient(config).terminate_instance(node_id)
    except Exception as e:
        log.error(f" problem while stopping: {e}")
        continue

    log.info(f" Stopped {host}")
