#!/usr/bin/env python
import os
import subprocess
import glob

# load configuration
from sadcat.config import download as download_config

def bunzip2_all(mask, odir):
    '''Untar all downloaded tar files'''
    print 'bunzip: %s*%s' % (odir, mask)
    bz2Files = glob.glob('%s/*%s' % (odir, mask))
    for bz2File in bz2Files:
        bz2FileSize = os.path.getsize(bz2File)
        l2File, bz2Ext = os.path.splitext(bz2File)
        if bz2FileSize > 0 and bz2Ext == '.bz2':
            cmd = 'bunzip2 %s -cd > %s' % (str(bz2File), str(l2File))
            print 'BUNZIP: %s' % str(cmd)
            os.system(cmd)
            print 'EMPTY: %s' % str(bz2File)
            file(str(bz2File), 'wb').close()


# check if modis.py is already running
ps = subprocess.Popen(['ps', '-ef'], stdout=subprocess.PIPE).communicate()[0]
processes = ps.split('\n')
selfProcNumber = 0
for proc in processes:
    if 'modis.py' in proc:
        print proc
        selfProcNumber += 1 
        
print 'Already running processes: ', selfProcNumber

zoneNames = ['MODIS_NorthSea', 'MODIS_Barents']

if selfProcNumber <= 2:
    for zoneName in zoneNames:
        zone = download_config[zoneName]
        odir = str(zone['download'])
        mask = str(zone['mask'])
        downloadCmd = str(zone['wget']) % (mask, odir)
        print 'Download: %s ' % downloadCmd
        os.system(downloadCmd)

        bunzip2_all(mask, odir)
 
# download of non extracted
#wget --post-data="subID=1461&addurl=1&results_as_file=1" -q -O - http://oceandata.sci.gsfc.nasa.gov/search/file_search.cgi | grep A2013350.*L2_LAC_SST.bz2 | wget -nc -nd -r --retr-symlinks -w 3 --connect-timeout=60 -P /files/  -i -
#wget --post-data="subID=1461&addurl=1&results_as_file=1&sdate=2013-11-01" -q -O - http://oceandata.sci.gsfc.nasa.gov/search/file_search.cgi | grep L2_LAC_SST.bz2 | wget -nc -nd -r --retr-symlinks -w 3 --connect-timeout=60 -P /Data/sat/downloads/MODIS/Barents/  -i -

