#!/usr/bin/env python3
import os, sys, argparse

default_shebang = {
    'py': '/usr/bin/env python',
    'sh': '/bin/bash',
    }

def main():

  # Configure the command-line argument parser and handle arguments
  parser = argparse.ArgumentParser(
      description='Create a new empty file (setting mode + shebang)'
      )
  parser.add_argument('-x', '--executable', action='store_true',
      help='Set executable permissions on new file'
      )
  parser.add_argument('-s', '--shebang', action='store_true',
      help='Include default shebang (if available).'
      )
  parser.add_argument('-d', '--create-dirs', action='store_true',
      help='Create parent directories if required'
      )
  parser.add_argument('-t', '--template', action='store_true',
      help='Insert default template from ~/.config/touch.py/template.EXT'
      )
  parser.add_argument('NewFilename', action='store',
      help='Filename of new file to create')
  args = parser.parse_args()

  # Create the file as requested
  extension = os.path.splitext(args.NewFilename)[1].lstrip('.')
  if args.create_dirs:
    createParentDirectories(args.NewFilename)
  touch(args.NewFilename)
  if args.shebang:
    if extension in default_shebang:
      with open(args.NewFilename, 'a') as newFile:
        newFile.write('#!' + default_shebang[extension] + '\n')
  if args.template:
    template_path = os.path.expanduser('~/.config/touch.py/template.%s' % extension)
    if os.path.exists(template_path):
      with open(template_path) as temp:
        with open(args.NewFilename, 'a') as newFile:
          newFile.write(temp.read())
  if args.executable:
    st = os.stat(args.NewFilename)
    os.chmod(args.NewFilename, st.st_mode | 0o111)

def touch(path):
  with open(path, 'a'):
    os.utime(path, None)

def createParentDirectories(path):
  basedir = os.path.dirname(path)
  if len(basedir) > 0:
    if not os.path.exists(basedir):
      os.makedirs(basedir)

if __name__ == '__main__':
  sys.exit(main())
