#!/usr/bin/python3

import os
import re
import subprocess
import sys


version = None

var = 'DEB_VERSION_UPSTREAM'

if var in os.environ:
    version = os.environ[var]
else:
    changelog_file = os.path.join(
        os.path.dirname(__file__),
        'changelog',
    )

    cmd = [
        'dpkg-parsechangelog',
        '-S', 'Version',
        '-l', changelog_file,
    ]

    p = subprocess.Popen(
        cmd,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
    )

    (stdout, stderr) = p.communicate()

    if p.returncode != 0:
        print("Error: Command failed: %s (%s)" % (
            " ".join(cmd),
            p.returncode
        ))
        if stdout:
            print(stdout.decode())
        if stderr:
            print(stderr.decode())
        sys.exit(p.returncode)

    version = stdout.decode()

    # Strip package revision
    version = re.sub(
        r'-[^-]*$',
        '',
        version,
    )

    # Strip epoch
    version = re.sub(
        r'^[0-9]*:',
        '',
        version,
    )

# Strip repacksuffix
version = re.sub(
    r'\+.*$',
    '',
    version,
)

# Strip pre-release identifier
version = re.sub(
    r'~',
    '',
    version,
)

version_file = os.path.join(
    os.path.dirname(
        os.path.dirname(__file__),
    ),
    'lib',
    'cartopy',
    '_version.py',
)

with open(version_file, 'w') as f:
    f.write("# Generated by %s/%s\n" % (
        os.path.basename(
            os.path.dirname(__file__),
        ),
        os.path.basename(__file__)
    ))
    f.write("version = '%s'\n" % version)
