#!/usr/bin/env python
import sys

from vappio.webservice import cluster

# Ensure we are dealing with kv pairs
if sys.stdin.readline().strip() != 'kv':
    raise Exception('Header needs to be kv')

# Write our header out
sys.stdout.write('kv\n')

kv = {'cluster.CLUSTER_NAME': None,
      'pipeline.EXEC_WANT_INSTANCES': None
      }

for line in sys.stdin:
    sys.stdout.write(line)
    k, v = line.strip().split('=', 1)
    if k in kv:
        kv[k] = v

if [v for v in kv.values() if not v]:
    raise Exception('Not all expected values present in config')

cl = cluster.listClusters('localhost', {'cluster_name': kv['cluster.CLUSTER_NAME']})[0]

wantInstances = int(kv['pipeline.EXEC_WANT_INSTANCES'])

diffInstances = wantInstances - len([i for i in cl['exec_nodes'] if i['state'] != 'terminated'])

if diffInstances > 0:
    taskName = cluster.addInstances('localhost', kv['cluster.CLUSTER_NAME'], diffInstances, 0)
    sys.stdout.write('pipeline.ADD_INSTANCES_TASKNAME=%s\n' % taskName)

    
