#!/usr/bin/env python
import ConfigParser
import optparse
import os
import sys
import urlparse
try:
  from zope.pagetemplate.pagetemplatefile import PageTemplateFile
except:
  print """Unable to import PageTemplateFile.  This probably means
that you need to add ~zope/lib/python to your python path.
Try 'export PYTHONPATH=$PYTHONPATH:/path/to/Zope/lib/python'
where the Zope in question is version 2.8+ (you can use CacheFu
for Zope 2.7 also, but you need Zope 2.8 to run makeconfig.py)"""
  sys.exit(1)

class PT(PageTemplateFile):
  def pt_getContext(self, args, kwargs):
    rval = PageTemplateFile.pt_getContext(self, args=args)
    kwargs.update(rval)
    return kwargs

def unique_values(values):
    d = {}
    for v in values:
        d[v] = 1
    return d.keys()
    
def getContext(config_file):
  c = ConfigParser.ConfigParser()
  c.read(config_file)
  values = {
    'unique_values': unique_values, # helper function
    'varnish_binary': c.get('varnish', 'binary'),
    'varnish_config_dir': c.get('varnish', 'config_dir'),
    'varnish_cache_dir': c.get('varnish', 'cache_dir'),
    'varnish_user': None,
    'varnish_group': None,
    'varnish_address': '127.0.0.1',
    'varnish_port': 8000,
    'varnish_cachesize': None,
    }
  if c.has_option('varnish', 'user'):
    values['varnish_user'] = c.get('varnish', 'user')
  if c.has_option('varnish', 'group'):
    values['varnish_group'] = c.get('varnish', 'group')
  if c.has_option('varnish', 'address'):
    values['varnish_address'] = c.get('varnish', 'address')
  if c.has_option('varnish', 'port'):
    values['varnish_port'] = c.getint('varnish', 'port')
  if c.has_option('varnish', 'cache_size'):
    values['varnish_cachesize'] = c.getint('varnish', 'cache_size')

  count = 1
  vh_map = {}
  section = 'virtualhosts'
  for o in c.options(section):
    backend_id = 'backend_%s' % count
    (zope_host, zope_port) = c.get(section, o).split(':', 1)
    (zope_port, zope_path) = zope_port.split('/', 1)
    vh_map[backend_id] = {'host': o, 'zope_host': zope_host, 'zope_port': zope_port, 'zope_path': zope_path}
    count = count + 1 
  values['vh_map'] = vh_map
  # {backend_id: [host, zope_host, zope_port, zope_path]}
  
  return values

def generate(context, target_dir=None, source_dir=None):
  for fn in os.listdir(source_dir):
    # skip directories (e.g. .svn)
    if not os.path.isfile(os.path.join(source_dir, fn)):
      continue
    # skip emacs tmp files
    if fn.endswith('~') or fn.endswith('#'):
      continue
    filename = os.path.join(source_dir, fn)
    
    pt = PT(os.path.join(source_dir, filename))
    outfile = os.path.join(target_dir, fn)
    print 'Generating %s' % outfile
    f = open(outfile, 'w+')
    f.write(pt(**context))
    f.close()
  os.chmod(os.path.join(target_dir, 'deploy'), 0700)
  os.chmod(os.path.join(target_dir, 'varnish-start'), 0700)
  os.chmod(os.path.join(target_dir, 'varnish-stop'), 0700)


if __name__ == '__main__':
  p = optparse.OptionParser()
  p.add_option('-c', '--config', action='store', dest='config_file')
  p.add_option('-t', '--templates', action='store', dest='template_dir')
  p.add_option('-o', '--output', action='store', dest='output_dir')
  opt, args = p.parse_args()

  config_file = opt.config_file
  if not config_file:
    config_file = raw_input('Configuration file [makeconfig.cfg]: ')
    if not config_file:
      config_file = 'makeconfig.cfg'
  if not os.path.exists(config_file):
    p.error('Unable to read configuration file %s' % config_file)

  template_dir = opt.template_dir
  if not template_dir:
    template_dir = raw_input('Template directory [templates]: ')
    if not template_dir:
      template_dir = 'templates'
  if not template_dir.startswith('/'):
    template_dir = os.path.join(os.getcwd(),template_dir)
  template_dir = os.path.normpath(template_dir)
  if not os.path.exists(template_dir):
    p.error('Unable to find template directory %s' % template_dir)
  if not os.path.isdir(template_dir):
    p.error('%s is not a directory' % template_dir)

  output_dir = opt.output_dir
  if not output_dir:
    output_dir = raw_input('Output directory [output]: ')
    if not output_dir:
      output_dir = 'output'
  if not output_dir.startswith('/'):
    output_dir = os.path.join(os.getcwd(), output_dir)
  output_dir = os.path.normpath(output_dir)
  if not os.path.exists(output_dir):
    d = os.path.dirname(output_dir)
    if not os.path.exists(output_dir):
      if not os.path.exists(d):
        p.error('Unable to open parent directory for output files %s' % d)
      os.mkdir(output_dir)

  context = getContext(config_file)
  print 'Generating files for varnish behind apache'
  generate(context, output_dir, template_dir)

