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

import json
import os
import re
import sys
import stat


def clear(name, deploy_type):
    conf = os.path.join(os.path.abspath(os.path.dirname(sys.argv[0])), "conf")
    manifest = ""

    if os.path.exists(conf):
        for file in os.listdir(conf):
            if re.match(r'manifest\.[0-9]+\.json', file):
                manifest = file
                break

    if not manifest:
        os.system("rm -rf ./" + name)
    else:
        with open(os.path.join(conf, manifest), "rb") as f:
            fileJson = json.load(f)

        dirs = []
        prefix = "./" + name + "/" if deploy_type == "bizframe" else "./"

        for x in fileJson:
            if fileJson[x]["dir"] not in dirs:
                dirs.append(fileJson[x]["dir"])

            file_path = prefix + fileJson[x]["path"]
            if os.path.exists(file_path):
                os.remove(file_path)

        for x in dirs:
            should_remove = (deploy_type == "bizframe" and x != "") or (deploy_type == "subsystem" and x != name)
            if should_remove:
                dir_path = prefix + x
                if os.path.exists(dir_path):
                    try:
                        os.removedirs(dir_path)
                    except OSError:
                        pass

RD, WD, XD = 4, 2, 1
BNS = [RD, WD, XD]
MDS = [
    [stat.S_IRUSR, stat.S_IRGRP, stat.S_IROTH],
    [stat.S_IWUSR, stat.S_IWGRP, stat.S_IWOTH],
    [stat.S_IXUSR, stat.S_IXGRP, stat.S_IXOTH]
]

def chmod(path, mode):
    if isinstance(mode, int):
        mode = str(mode)
    if not re.match("^[0-7]{1,3}$", mode):
        raise Exception("mode does not conform to ^[0-7]{1,3}$ pattern")
    mode = "{0:0>3}".format(mode)
    mode_num = 0
    for midx, m in enumerate(mode):
        for bnidx, bn in enumerate(BNS):
            if (int(m) & bn) > 0:
                mode_num += MDS[bnidx][midx]
    os.chmod(path, mode_num)
