import os
import re
import sys
from setuptools import setup, find_packages
from distutils.sysconfig import get_config_vars
from subprocess import check_output

def file_contents(fp):
    fd = open(fp, 'r')
    content = fd.read()
    fd.close()
    return content.strip()

_git_version_re = re.compile(r'v(\d+.\d+.\d+(rc\d+)?)(-(\d+)-g([0-9a-f]+))?$')

def get_version():
    top_srcdir = os.path.dirname(sys.argv[0]) or '.'
    if os.path.isdir(os.path.join(top_srcdir, '.git')):
        cmd = ['git', 'describe', '--tags']
        version = check_output(cmd, cwd=top_srcdir).decode('utf-8').strip()
        mo = re.match(_git_version_re, version)
        if mo:
            if mo.group(3):
                return '%s.dev%s+%s' % (mo.group(1), mo.group(4), mo.group(5))
            else:
                return mo.group(1)
    return file_contents(os.path.join(top_srcdir, 'VERSION'))

def get_nagios_plugin_dir():
    exec_prefix, libdir = get_config_vars('exec_prefix', 'LIBDIR')
#    if libdir.startswith(exec_prefix + '/'):
#        libdir = libdir[len(exec_prefix)+1:]
#    return os.path.join(libdir, 'nagios/plugins')
    if libdir.endswith('/usr/lib64'):
        return '/usr/lib64/nagios/plugins'
    else:
        return '/usr/lib/nagios/plugins'

setup(
    name = "nordugrid-arc-nagios-plugins",
    version = get_version(),
    description = 'Nagios Probes for Arc CEs',
    url = 'http://www.nordugrid.org/',
    author = 'Petter Urkedal',
    author_email = 'urkedal@nbi.dk',

    requires = ['cryptography', 'ldap'],
    packages = find_packages(),

    data_files = [
        (get_nagios_plugin_dir(), [
            'plugins/check_arcce_clean',
            'plugins/check_arcce_monitor',
            'plugins/check_arcce_submit',
            'plugins/check_arcrest_info',
            'plugins/check_arcservice',
            'plugins/check_gridstorage',
        ]),
        ('/etc/arc/nagios', ['config/20-dist.ini']),
        ('/etc/arc/nagios/20-dist.d', ['config/20-dist.d/default.xrsl.j2']),
        ('/etc/arc/nagios', ['config/60-egi.ini']),
        ('/etc/arc/nagios/60-egi.d', ['config/60-egi.d/arcce_igtf.py']),
    ],
)
