"""Quickstart command to generate a new project.

Quickstart takes the files from turbogears.quickstart and processes them to produce
a new, ready-to-run project."""

import pkg_resources
import re
import os
import stat
import optparse
import sys

beginning_letter = re.compile(r"^[^a-z]*")
valid_only = re.compile(r"[^a-z0-9_]")

class quickstart:
    "Implementation of quickstart."
    
    name = None
    package = None
    
    def __init__(self, version):
        parser = optparse.OptionParser(usage="%prog quickstart [options]",
                                       version="%prog " + version)
        parser.add_option("-n", "--name", help="project name", dest="name")
        parser.add_option("-p", "--package", help="package name for the code",
            dest="package")
        parser.add_option("--dry-run", help="dry run (don't actually do anything)",
            action="store_true", dest="dry_run")
        (options, args) = parser.parse_args()
        self.__dict__ = options.__dict__
        self.turbogearsversion = version
    
    def _process_template(self, oldfile, newfile):
        """Uses Python's built in string formatting templates to 
        produce new files."""
        if newfile.endswith(".source"):
            newfile = newfile[:-7]
        generatedFile = newfile
        if newfile.endswith(".empty"):
            generatedFile = os.path.split(newfile)[0] + "/"

        if self.dry_run:
            print("would generate %s" % generatedFile)
            return
        dirname = os.path.dirname(newfile)
        if not os.path.exists(dirname):
            print "creating directory %s" % dirname
            os.makedirs(dirname)
        if not os.path.basename(newfile) == "empty":
            print("generating %s" % generatedFile)
            template = open(oldfile).read()
            output = open(newfile, "w")
            output.write(template % self.__dict__)
            output.close()
            if newfile.endswith("-start.py"):
                oldmode = os.stat(newfile).st_mode
                os.chmod(newfile, oldmode | stat.S_IXUSR)
    
    def run(self):
        "Quickstarts the new project."
        
        while not self.name:
            self.name = raw_input("Enter project name: ")
            
        while not self.package:
            package = self.name.lower()
            package = beginning_letter.sub("", package)
            package = valid_only.sub("", package)
            self.package = raw_input("Enter package name [%s]: " % package)
            if not self.package:
                self.package = package
        
        if os.path.exists(self.package):
            print("A directory called '%s' already exists. Exiting."
                      % self.package)
            return
            
        safename = pkg_resources.safe_name(self.name)
        basefiles = pkg_resources.resource_filename("turbogears", "quickstart")
        for root, dirs, files in os.walk(basefiles):
            newpath = root[len(basefiles)-10:]
            if newpath.find(".svn") > -1:
                continue
            newpath = newpath.replace("quickstart", self.package)
            newpath = newpath.replace("projectname", self.package)
            newpath = newpath.replace("ProjectName.egg-info", 
                                    "%s.egg-info" 
                                    % safename.replace("-", "_"))
            newpath = newpath.replace("ProjectName", safename)
            for f in files:
                if (root == basefiles and f.startswith("__init__.py")) \
                   or f.endswith(".pyc") or f.endswith(".pyo"):
                    continue
                newf = f
                if f.startswith("project-start.py"):
                    newf = "%s-start.py" % (self.package)
                self._process_template(os.path.join(root, f), 
                                      os.path.join(newpath, newf))
        
        if not self.dry_run:
            os.chdir(self.package)
            sys.argv = ["setup.py", "egg_info"]
            import imp
            imp.load_module("setup", *imp.find_module("setup", ["."]))
        