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

import json
import os
import re
import sys
import stat


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

    manifest = ""

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

    if(manifest == ""):
        os.popen("rm -rf ./" + name)
    else:
        file = open(os.path.join(conf, manifest), "rb")
        fileJson = json.load(file)

        dirs = []

        prefix = ""

        if(type == "bizframe"):
            prefix = "./" + name + "/"
        elif(type == "subsystem"):
            prefix =  "./"

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

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

        for x in dirs:
            if(type == "bizframe" and x != "" or type == "subsystem" and x != name):
                if(os.path.exists(prefix + x)):
                    try:
                        os.removedirs(prefix + x)
                    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)
