#!/usr/bin/env python
import urllib2, tarfile, re, glob, shutil

rawTar = urllib2.urlopen("ftp://heasarc.gsfc.nasa.gov/software/fitsio/c/cfitsio_latest.tar.gz")
tar = tarfile.open(fileobj=rawTar, mode="r|gz")
while True:
    info = tar.next()
    if info.name == "cfitsio/configure": break
else:
    raise RuntimeError("cfitsio/configure not found.")

configure = tar.extractfile(info)

major_version = None
minor_version = None

for line in configure:
    line = re.sub(r"#.*", "", line).strip()
    if line.startswith("CFITSIO_MAJOR="):
        major_version = line[14:]
        if minor_version is not None: break
    elif line.startswith("CFITSIO_MINOR="):
        minor_version = line[14:]
        if major_version is not None: break

if (major_version is None) or (minor_version is None):
    raise RuntimeError("Failed to get major or minor version")

minor_version = (minor_version + "000")[:3]

version = major_version + "." + minor_version

newBuildFile = "cfitsio-" + version + ".build"
buildFile, = glob.glob("cfitsio-*.build")

if buildFile != newBuildFile:
    print "mv {old} {new}".format(old=buildFile, new=newBuildFile)
    shutil.move(buildFile, newBuildFile)
