#!/usr/bin/env python
import sys
import os, errno
import subprocess


def generate_template(template_name, destination):
  template_dir = os.path.join(os.path.dirname(__file__), '..', 'snake_skin', 'templates')
  print('\tcreating ' + destination)
  template = open(template_dir + '/' + template_name).read()
  f = open('./' + library + '/' + destination, 'w')
  author = subprocess.check_output('git config user.name', shell=True).rstrip() or 'AUTHOR'
  f.write(template.format(library_name = library, author = author))
  f.close()

def shed(library):
  try:
    os.makedirs(library)
  except OSError as exc:
    if exc.errno == errno.EEXIST:
      print "directory exists, cannot create"
      exit()
    else:
      raise

  os.makedirs(library + '/' + library)
  generate_template('setup.py', 'setup.py')
  generate_template('requirements.txt', 'requirements.txt')
  generate_template('__init__.py', library + '/__init__.py')
  generate_template('README.md', 'README.md')
  generate_template('LICENSE', 'LICENSE')
  generate_template('MANIFEST.in', 'MANIFEST.in')
  generate_template('gitignore', '.gitignore')
  subprocess.call('cd ' + library + ' && git init', shell=True)

def help():
  print 'Usage: snake_skin command options'
  print 'commands: '
  print '\tshed - create new Python library skeleton'
  print '\thelp - this info'

if sys.argv[1] == 'shed':
  if len(sys.argv) > 2:
    library = sys.argv[2]
    shed(library)
  else:
    print 'Project name not specified'
else:
  help()

