from django.http import HttpResponse
from monitor import driver
from core.models import *
from hpc.models import *
from requestrouter.models import *
import xos.settings
import json
import os
import time

def HpcConfig(request):
    hpc = HpcService.objects.all()
    if (not hpc):
        return HttpResponse("# Error: no HPC service")

    hpc = hpc[0]
    try:
       slices = hpc.slices.all()
    except:
       # this field used to be improperly named, and makemigrations won't fix it
       slices = hpc.service.all()
    for slice in slices:
        if "cmi" in slice.name:
            cmiSlice = slice
        elif ("hpc" in slice.name) or ("vcoblitz" in slice.name):
            hpcSlice = slice

    if not cmiSlice:
        return HttpResponse("# Error: no CMI slice")

    if len(cmiSlice.slivers.all())==0:
        return HttpResponse("# Error: CMI slice has no slivers")

    if not hpcSlice:
        return HttpResponse("# Error: not HPC slice")

    rr = RequestRouterService.objects.all()
    if not (rr):
        return HttpResponse("# Error: no RR service")

    rr = rr[0]
    try:
       slices = rr.slices.all()
    except:
       # this field used to be improperly named, and makemigrations won't fix it
       slices = rr.service.all()
    for slice in slices:
        if "redir" in slice.name:
            redirSlice = slice
        elif "demux" in slice.name:
            demuxSlice = slice

    if not redirSlice:
        return HttpResponse("# Error: no dnsredir slice")

    if not demuxSlice:
        return HttpResponse("# Error: no dnsdemux slice")

    # for now, assuming not using NAT
    cmi_hostname = cmiSlice.slivers.all()[0].node.name

    d = {}
    d["hpc_slicename"] = hpcSlice.name
    d["redir_slicename"] = redirSlice.name
    d["demux_slicename"] = demuxSlice.name
    d["cmi_hostname"] = cmi_hostname
    d["xos_hostname"] = xos.settings.RESTAPI_HOSTNAME
    d["xos_port"] = str(xos.settings.RESTAPI_PORT)

    return HttpResponse("""# auto-generated by HpcConfig
ENABLE_PLC=False
ENABLE_PS=True
BASE_HRN="princeton"
RELEVANT_SERVICE_NAMES=['vcoblitz', 'coredirect', 'codnsdemux', "syndicate_comon_server"]
COBLITZ_SLICE_NAME=BASE_HRN+"_vcoblitz"
COBLITZ_SLICE_ID=70
COBLITZ_PS_SLICE_NAME="{hpc_slicename}"
DNSREDIR_SLICE_NAME=BASE_HRN+"_coredirect"
DNSREDIR_SLICE_ID=71
DNSREDIR_PS_SLICE_NAME="{redir_slicename}"
DNSDEMUX_SLICE_NAME=BASE_HRN+"_codnsdemux"
DNSDEMUX_SLICE_ID=69
DNSDEMUX_PS_SLICE_NAME="{demux_slicename}"
CMI_URL="http://{cmi_hostname}/"
CMI_HTTP_PORT="8004"
CMI_HTTPS_PORT="8003"
PUPPET_MASTER_HOSTNAME="{cmi_hostname}"
PUPPET_MASTER_PORT="8140"
PS_HOSTNAME="{xos_hostname}"
PS_PORT="{xos_port}"
""".format(**d))


@@ -222,16 +222,93 @@
 quest):%0A
+    hpcSlice=None%0A    cmiSlice=None%0A    redirSlice=None%0A    demuxSlice=None%0A%0A
     hpc 

fix fault if no slices attached to services