#!/usr/bin/python3
# @author alban
# @since 2019-08-26
# @license GPLv3

""" This check returns the list of containers in proxmox6 with each
  * id               Ex: 101
  * name             Ex: Proxy
  * running status   Ex: stopped
  * onboot status    Ex: True
  Json output        Ex: {Proxy:{name:Proxy, running:stopped, onboot:True}, ...}
"""

import subprocess
import json

# Read from `pct list` the containers list
ret = subprocess.run( ['sudo','pct','list'], stdout=subprocess.PIPE, timeout=10)
rawList = ret.stdout.split(b"\n")
pctList = {}

# Iterate through returned raw lines
for line in rawList :

  # Transform the raw line into a list
  info = line.split()
  if (len(info) == 0): continue # Skips empty lines

  # Read variables
  id = info[0].decode()
  running = info[1].decode()
  name = info[ len(info) -1 ].decode()
  if (id=="VMID"): continue # Skips the header line

  # Get the container's onboot status from its config file
  ret = subprocess.run( ['grep','^onboot','/etc/pve/lxc/{}.conf'.format(id)], timeout=5, stdout = subprocess.PIPE)
  onboot = True if (ret.returncode == 0 ) else False
  pctList[id] = {"name":name, "running":running, "onboot":onboot}

# Return the list
print( json.dumps(pctList) )
