#!/usr/bin/env python3
# -*- coding: utf-8 -*-

#########################################################################
# pyeole.service - manage EOLE services
# Copyright © 2014 Pôle de Compétence EOLE <eole@ac-dijon.fr>
#
# License CeCILL:
#  * in french: http://www.cecill.info/licences/Licence_CeCILL_V2-fr.html
#  * in english http://www.cecill.info/licences/Licence_CeCILL_V2-en.html
#########################################################################

import os
import sys

from creole.client import CreoleClient

from os.path import isfile
from subprocess import getstatusoutput


STATUS_FILE = '/usr/share/eole/hapy-deploy/.hapy-deploy.status'

if __name__ == "__main__":
    client = CreoleClient()

    if not os.path.exists(STATUS_FILE):
        sys.exit(0)

    cmd = [". /usr/lib/eole/diagnose.sh"]
    cmd.append('EchoGras "*** Déploiement automatique des machines virtuelles"')

    file = open(STATUS_FILE, 'r')
    lines = file.readlines()
    file.close()

    a={}
    for line in lines:
        if line.startswith("DEPLOY-START"):
            a={}
        else:
            if line.startswith("DEPLOY-END"):
                continue
            else:
                arrLine = line.strip().split(':')
                if not arrLine[0] in a.keys():
                    a[arrLine[0]]=[]
                a[arrLine[0]].append(arrLine[1:])

    for key,value in a.items():
        cmd.append(f'echo "   {key}:"')
        for elm in value:
            cmd.append(f'printf ".    %${{len_pf}}s => " "{elm[0]}"')
            if elm[1] == "OK":
                cmd.append(f'EchoVert "{elm[1]}"')
            elif elm[1] == "KO":
                cmd.append(f'EchoRouge "{elm[1]}"')
            else:
                cmd.append(f'EchoOrange "{elm[1]}"')

    cmd_string = "\n".join(cmd)
    err, ret = getstatusoutput(cmd_string)
    print(ret)
