#!/usr/bin/env python
import os
import tarfile
import shutil
from ftplib import FTP

# globals
md5suff = '.md5sum'
name = 'asap_data.tar.bz2'
dataurl  = "ftp.atnf.csiro.au"
tmpdata = '/tmp/asap_data.tar.bz2'
datadir = 'pub/software/asap/data'
tmpmd5 = tmpdata+md5suff

ftp = FTP(dataurl)   # connect to host, default port
ftp.login()               # user anonymous, passwd anonymous@
ftp.cwd(datadir)
print "Checking if an update is required."
ftp.retrbinary('RETR %s' % name+md5suff, open(tmpmd5, 'wb').write)
md5file = file(tmpmd5)
md5new = md5file.readlines()[0].split()[0]

# use ASAPDATA if set - allows non-root update
if os.environ.has_key("ASAPDATA"):
    asapbase = os.environ["ASAPDATA"]
else:
    import asap
    # get asap module path
    asapbase = asap.__path__[0]
try:
    fl = os.path.join(asapbase, name+md5suff)
    data_md5 = file(fl)
    ls = data_md5.readlines()[0]
    data_md5.close()
    md5old = ls.split()[0]
except IOError:
    md5old =''

if md5new != md5old:
    print "Update required. Downloading asap data archive...."
    ftp.retrbinary('RETR %s' % name, open(tmpdata, 'wb').write)
    os.chdir(asapbase)
    tf = tarfile.TarFile.bz2open(tmpdata)
    print "Extracting data archive in %s.." % asapbase
    for member in tf.getmembers():
        tf.extract(member)
    shutil.copy(tmpmd5, asapbase)
    os.remove(tmpdata)
    os.remove(tmpmd5)
else:
    print """Data already at latest available version.
If you still get errors running asap, please report this."""
ftp.quit()
