#!/usr/bin/python
# Copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0

# Google's Python Class
# http://code.google.com/edu/languages/google-python-class/

import sys
import re
import os
import shutil
import commands

import logging, pprint


logging.basicConfig(
    # filename=LOG_PATH,
    level=logging.DEBUG,
    format='[%(asctime)s] %(levelname)s [%(module)s-%(funcName)s()::%(lineno)d] %(message)s',
    datefmt='%d/%b/%Y %H:%M:%S' )
log = logging.getLogger(__name__)
log.info( 'log configured' )


"""Copy Special exercise
"""

# +++your code here+++
# Write functions and modify main() to call them

# LAB(begin solution)
def get_special_paths(dirname):
  """Given a dirname, returns a list of all its special files."""
  log.debug( 'dirname, ```%s```' % dirname )
  result = []
  paths = os.listdir(dirname)  # list of paths in that dir
  log.debug( 'paths, ```%s```' % paths )
  for fname in paths:
    log.debug( 'fname, ```%s```' % fname )
    match = re.search(r'__(\w+)__', fname)
    log.debug( 'match, `%s`' % pprint.pformat(dir(match)) )
    if match:
      log.debug( 'match.span(), `%s`' % repr(match.span()) )
      log.debug( 'match.group(), ```%s```' % match.group() )
      result.append(os.path.abspath(os.path.join(dirname, fname)))
  log.debug( 'result, ```%s```' % result )
  return result


def copy_to(paths, to_dir):
  """Copy all of the given files to the given dir, creating it if necessary."""
  if not os.path.exists(to_dir):
    os.mkdir(to_dir)  # arguably throw an exception instead
  for path in paths:
    fname = os.path.basename(path)
    shutil.copy(path, os.path.join(to_dir, fname))
    # could error out if already exists os.path.exists():


def zip_to(paths, zipfile):
  """Zip up all of the given files into a new zip file with the given name."""
  cmd = 'zip -j ' + zipfile + ' ' + ' '.join(paths)
  print "Command I'm going to do:" + cmd
  (status, output) = commands.getstatusoutput(cmd)
  log.debug( 'status, `%s`; output, ```%s```' % (status, output) )
  # If command had a problem (status is non-zero),
  # print its output to stderr and exit.
  if status:
    sys.stderr.write(output)
    sys.exit(1)

# LAB(end solution)


def main():
  # This basic command line argument parsing code is provided.
  # Add code to call your functions below.

  # Make a list of command line arguments, omitting the [0] element
  # which is the script itself.

  args = sys.argv[1:]
  log.debug( 'args, ```%s```' % args )
  if not args:
    print "usage: [--todir dir][--tozip zipfile] dir [dir ...]";
    sys.exit(1)

  # todir and tozip are either set from command line
  # or left as the empty string.
  # The args array is left just containing the dirs.
  todir = ''
  if args[0] == '--todir':
    todir = args[1]
    del args[0:2]
  log.debug( 'todir, ```%s```' % todir )

  tozip = ''
  if args[0] == '--tozip':
    tozip = args[1]
    del args[0:2]
  log.debug( 'tozip, ```%s```' % tozip )

  if len(args) == 0:
    print "error: must specify one or more dirs"
    sys.exit(1)

  # +++your code here+++
  # Call your functions
  # LAB(begin solution)

  # Gather all the special files
  paths = []
  for dirname in args:
    log.debug( 'dirname entry, ```%s```' % dirname )
    paths.extend(get_special_paths(dirname))
  log.debug( 'paths, ```%s```' % paths )

  if todir:
    copy_to(paths, todir)
  elif tozip:
    zip_to(paths, tozip)
  else:
    print '\n'.join(paths)
  # LAB(end solution)

if __name__ == "__main__":
  main()
