#!/usr/bin/env python

"""
fetch and rename files uploaded from the Danish telescope at La Silla,
left using rsync at uploadPath
"""


import fnmatch
import os
import re
import shutil
import sys

from gavo import api
from gavo import utils


def makeFilterId(hdr):
# Would be nice, but the headers are broken and only fixed later.  So, no
# filters in file names.
	hdr["FILTER_A"].verify("silentfix")
	fa, fb = hdr["FILTER_A"], hdr["FILTER_B"]
	f1, f2 = int(fa), int(fb)
	return {
		3: 'V',
		4: 'R',
		5: 'I',}[f1+f2]


def getNameFromFits(fName, objectMap):
	hdr = utils.readPrimaryHeaderQuick(open(fName))
	objectName = objectMap.resolve(hdr["OBJECT"])
	newName = "%s_%sT%s.fits"%(objectName,
		re.sub("[-:.]", "", hdr["DATE-OBS"].split("T")[0]),
		hdr["TM_START"]).replace(" ", "_")
	return newName


def getNameMap(uploadPath, objectMap):
	"""returns a list of (sourceName, targetName) pairs for the .fits files
	found in targetPath.
	"""
	map = []
	for root, dirs, files in os.walk(uploadPath):
		for fName in files:
			if fnmatch.fnmatch(fName, "R.*.fits"):
				fName = os.path.join(root, fName)
				map.append((fName, getNameFromFits(fName, objectMap)))
	return map


def copyMissing(nameMap, targetDir):
	for src, dest in nameMap:
		dest = os.path.join(targetDir, dest)
		if os.path.exists(dest):
			continue
		shutil.copyfile(src, dest)


def parseCommandLine():
	if len(sys.argv)==1:
		return "/home/silla/upload"
	elif len(sys.argv)==2 and not sys.argv[1].startswith("-"):
		return sys.argv[1]
	else:
		sys.exit("Usage %s [<src dir>] -- Import FITSes from danish tel."%
			sys.argv[0])


def main():
	uploadPath = parseCommandLine()
	api.setDBProfile("admin")
	rd = api.getRD("danish/red")
	objectMap = utils.NameMap(os.path.join(rd.resdir, "res/objectmap.txt"))
	nameMap = getNameMap(uploadPath, objectMap)
	targetDir = os.path.join(rd.resdir, "data")
	copyMissing(nameMap, targetDir)


if __name__=="__main__":
	main()
