#!/usr/bin/env python2
import subprocess
import sys
import os
import stat
from zipfile import ZipFile, ZIP_DEFLATED

job = sys.argv[1]


def build():
    for file in os.listdir("."):
        if os.path.isdir(file) and not file.startswith("_template"):
            # generate plugin
            subprocess.call("cd %s && ./generate.py build" % file, shell=True)


def deploy():
    for file in os.listdir("."):
        if os.path.isdir(file) and not file.startswith("_template"):
            # find zipfile
            for subfile in os.listdir(os.path.join(file, "build")):
                if subfile.endswith(".zip"):
                    with ZipFile(os.path.join(file, "build", subfile), 'r') as zip:
                        if zip.testzip():
                            print("bad widget zip")
                            return
                        # extract filename from zip
                        zip.extractall(os.path.join("..", "uploads", "widgets"))


def create_plugin():

    plugin_name = input("Plugin Name: ")
    author_name = input("Author Name: ")
    author_email = input("Author Email: ")

    # copy files + replace content
    name_lower = plugin_name.lower()
    os.mkdir(name_lower)
    for root, dirs, files in os.walk('_template'):
        for file in files:
            with open(os.path.join(root, file), 'r') as f:
                content = f.read()
                content = content.replace("###NAME###", plugin_name)
                content = content.replace("###NAME_LOWER###", name_lower)
                content = content.replace("###AUTHOR###", author_name)
                content = content.replace("###EMAIL###", author_email)

                # write
                target_path = root.replace("###NAME_LOWER###", name_lower).replace("_template", name_lower)
                if not os.path.exists(target_path):
                    os.makedirs(target_path)

                with open(os.path.join(target_path, file), 'w') as wf:
                    wf.write(content)

    # make generate.py executable
    os.chmod(os.path.join(name_lower, "generate.py"), stat.S_IRWXU | stat.S_IRGRP | stat.S_IWGRP | stat.S_IROTH)
    print("%s plugin has been created." % plugin_name)


def make_plugin_bundle():
    app_name = sys.argv[2]
    path = sys.argv[3]
    archive_path = os.path.join(path, "%s.zip" % app_name)
    if os.path.exists(path):
        with ZipFile(archive_path, 'w', ZIP_DEFLATED) as archive:
            # add manifest
            archive.write(os.path.join(path, "..", "Manifest.json"), os.path.join(app_name, "Manifest.json"))

            # add scripts
            for root, dirs, files in os.walk(os.path.join(path, 'script')):
                for f in files:
                    archive.write(os.path.join(root, f), os.path.join(app_name, f))

            # add resources
            for root, dirs, files in os.walk(os.path.join(path, 'resource')):
                for f in files:
                    archive.write(os.path.join(root, f), os.path.join(root.replace(path, app_name, 1), f))

    print("%s written" % archive_path)

if job == "build":
    build()
elif job == "deploy":
    build()
    deploy()
elif job == "create-plugin":
    create_plugin()
elif job == "bundle-plugin":
    make_plugin_bundle()
else:
    print("Unknown job: %s" % job)
@@ -67,16 +67,32 @@
 rt stat%0A
+import argparse%0A
 from zip
@@ -130,27 +130,8 @@
 ED%0A%0A
-job = sys.argv%5B1%5D%0A%0A
 %0Adef
@@ -2231,23 +2231,16 @@
 dle(
-):%0A    
 app_name
  = s
@@ -2239,45 +2239,16 @@
 name
- = sys.argv%5B2%5D%0A    path = sys.argv%5B3%5D
+, path):
 %0A   
@@ -3045,97 +3045,120 @@
 h)%0A%0A
+%0A
 if 
-job == %22build
+__name__ == %22__main__
 %22:%0A
+%0A
     
-build()%0Aelif job == %22deploy%22:%0A    build()%0A    deploy()%0Aelif job ==
+commands = %7B%0A        %22build%22: build,%0A        %22deploy%22: %5Bbuild, deploy%5D,%0A       
  %22cr
@@ -3170,20 +3170,16 @@
 plugin%22:
-%0A   
  create_
@@ -3188,22 +3188,17 @@
 ugin
-()%0Aelif job ==
+,%0A       
  %22bu
@@ -3210,20 +3210,16 @@
 plugin%22:
-%0A   
  make_pl
@@ -3233,47 +3233,735 @@
 ndle
-()%0Aelse:%0A    print(%22Unknown job: %25s%22 %25 job)
+%0A    %7D%0A    parser = argparse.ArgumentParser(prog=%22make.py%22, usage=%22make.py %5Btask%5D%22,%0A                                     description=%22Plugin building helper.%22)%0A%0A    parser.add_argument('task', type=str, help='task (%25s)' %25 %22, %22.join(commands.keys()), nargs='?')%0A    options, unknown = parser.parse_known_args()%0A%0A    if options.task is None:%0A        parser.print_help()%0A%0A    elif options.task not in commands:%0A        print(%22action '%25s' is not available%22 %25 options.task)%0A        parser.print_help()%0A%0A    else:%0A        # run command%0A        if isinstance(commands%5Boptions.task%5D, list):%0A            for task in commands%5Boptions.task%5D:%0A                task(*sys.argv%5B2:%5D)%0A        else:%0A            commands%5Boptions.task%5D(*sys.argv%5B2:%5D)%0A

use argparser