#!/usr/bin/python
# coding=UTF-8
"""
packaging script for the freewat project

USAGE
    package.py [-h, -i, -u]

OPTIONS
    -h, --help
        print this help

    -i, --install
        install the package in the .qgis2 directory

    -u, --uninstall
        uninstall (remove) the package from .qgis2 directory
"""

import os
import zipfile
import re
import getopt
import sys
import shutil
from subprocess import Popen, PIPE

assert __name__ == "__main__"

# @todo make that work on windows
qgis_plugin_dir = os.path.join(os.environ["HOME"], ".qgis2", "python", "plugins")

try:
    optlist, args = getopt.getopt(sys.argv[1:],
            "hiu",
            ["help", "install", "uninstall"])
except Exception as e:
    sys.stderr.write(str(e)+"\n")
    exit(1)

optlist = dict(optlist)

if "-h" in optlist or "--help" in optlist:
    help(sys.modules[__name__])
    exit(0)

currendir = os.path.abspath(os.path.dirname(__file__))
out = os.path.join(currendir,"freewat.zip")

os.chdir("..")
with zipfile.ZipFile(out, 'w') as package:
    #@todo deal with top-level directory that are not freewat
    for root, dirs, files in os.walk("freewat"):
        for file_ in files:
            if not re.match(r".*\.(pyc|zip)", file_):
                package.write(os.path.join(root, file_))

target_dir = os.path.join(qgis_plugin_dir, "freewat")

if "-u" in optlist or "--uninstall" in optlist:
    if os.path.isdir(target_dir):
        shutil.rmtree(target_dir)

if "-i" in optlist or "--install" in optlist:
    if os.path.isdir(target_dir):
        print "removing ", target_dir
        shutil.rmtree(target_dir)
    
    
    with zipfile.ZipFile(out, "r") as z:
        z.extractall(qgis_plugin_dir)
    
    #out, err = Popen(["unzip",out, "-d", qgis_plugin_dir], stdout=PIPE, stdin=PIPE, stderr=PIPE).communicate()
    # if err:
        # sys.stderr.write(err)
        # exit(1)
  
