#!/usr/bin/env python

# $Id$

import sys
if not hasattr(sys, 'version_info') or sys.version_info < (2, 4):
    raise SystemExit, 'Muttils requires Python 2.4 or later'

from distutils.core import setup
import os.path, subprocess, time


# simplified hg versioning

def runhg(cmd):
    out, err = subprocess.Popen(['hg'] + cmd,
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE).communicate()
    err = [e for e in err.splitlines()
           if not e.startswith('Not trusting file') \
              and not e.startswith('warning: Not importing')]
    if err:
        return ''
    return out

version = ''

if os.path.isdir('.hg'):
    v = runhg(['id', '-i', '-t'])
    v = v.split()
    while len(v) > 1 and v[-1][0].isalpha():
        v.pop()
    if len(v) > 1: # tag found
        version = v[-1]
        if v[0].endswith('+'):
            version += '+'
    elif len(v) == 1:
        cmd = ['parents', '--template', '{latesttag}+{latesttagdistance}-']
        version = runhg(cmd) + v[0]
    if version.endswith('+'):
        version += time.strftime('%Y%m%d')
elif os.path.isfile('.hg_archival.txt'):
    kw = dict([[t.strip() for t in l.split(':', 1)]
               for l in open('.hg_archival.txt')])
    if 'tag' in kw:
        version =  kw['tag']
    elif 'latesttag' in kw:
        version = '%(latesttag)s+%(latesttagdistance)s-%(node).12s' % kw
    else:
        version = kw.get('node', '')[:12]

if version:
    fp = open('muttils/__version__.py', 'w')
    fp.write('# this file is autogenerated by setup.py\n')
    fp.write('version = "%s"\n' % version)
    fp.close()

try:
    from muttils import __version__
    version = __version__.version
except ImportError:
    version = 'unknown'

setup(name='muttils',
      version=version,
      description='Python utilities for console mail clients (eg. mutt)',
      author='Christian Ebert',
      author_email='blacktrash@gmx.net',
      url='http://www.blacktrash.org/hg/muttils/',
      packages=['muttils'],
      package_data={'muttils': ['effective_tld_names.dat']},
      scripts=['sigpager', 'urlbatcher', 'urlpager',
               'pybrowser', 'wrap', 'viewhtmlmsg'])
