#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
CLI tool: clean pert belly hack project folder
"""
import os
import shutil
import glob

from pert_belly_hack.defaults import OUTPUT_PATH
from pert_belly_hack.defaults import PACKAGE_OUTPUT_PATH

if __name__ == '__main__':
    VICTIMS = set(
        [
            os.path.abspath(OUTPUT_PATH),
            os.path.abspath(PACKAGE_OUTPUT_PATH),
            os.path.abspath('./Packages.stamps')
        ]
    )

    GLOBLINS = [
        "./*.egg-info/",
        "./doc/build/"
        "./dist/",
        ".sass-cache/",
        "*.opk"
    ]

    EXTENSIONS = [
        '.pyo',
        '.pyc'
    ]

    for root, _, files in os.walk('.'):
        for filename in files:
            abs_path = os.path.join(root, filename)
            (trunk, ext) = os.path.splitext(abs_path)
            if ext not in EXTENSIONS:
                continue
            VICTIMS.add(abs_path)

    for globme in GLOBLINS:
        for item in glob.iglob(globme):
            VICTIMS.add(item)

    for victim in reversed(sorted(list(VICTIMS))):
        if os.path.exists(victim):
            try:
                if os.path.isfile(victim):
                    print("- rm {!s}".format(victim))
                    os.unlink(victim)
                elif os.path.isdir(victim):
                    print("- rmtree {!s}".format(victim))
                    shutil.rmtree(victim)
            except Exception as exc:
                print "Could not remove {!r}: {!s}".format(victim, exc)
