#!/usr/bin/python
# -*- coding:Utf-8 -*- 

import sys
import traceback
import pickle
import io
import yaml

def coloring(message, ok=False):
    color = '\033[91m'
    if ok:
        color = '\033[92m'
    print(
        color
        + message
        + '\033[0m'
    )

def convert_config(in_path, out_path):
    try:
        with open(in_path, 'rb') as pkl:
            try:
                config = pickle.load(pkl)
            except:
                try:
                    config = pickle.load(pkl, encoding="utf-8")
                except:
                    coloring(
                        "Impossible de décoder le fichier %s" % in_path
                    )
                    traceback.print_exc()
                    exit(0)
    except:
        coloring(
            "Impossible d'ouvrir fichier %s" % in_path
        )
        traceback.print_exc()
        exit(0)
    try:
        with io.open(out_path, 'w', encoding='utf8') as outfile:
            try:
                yaml.safe_dump(
                    config,
                    outfile,
                    default_flow_style=False,
                    allow_unicode=True
                )
            except:
                coloring(
                    "Impossible d'encoder le fichier %s" % out_path
                )
                traceback.print_exc()
                exit(0)
    except:
        coloring(
            "Impossible d'enregistrer le fichier %s" % out_path
        )
        if verbose:
            traceback.print_exc()
if __name__ == "__main__":
    if len(sys.argv) < 2:
        coloring("Il vous manque un fichier d'entrée")
        exit(0)
    if len(sys.argv) < 3:
        coloring("Il vous manque un fichier de sortie")
        exit(0)
    convert_config(sys.argv[1], sys.argv[2])
    coloring(
        "Votre fichier de configuration a bien été converti !",
        True
    )