#! /usr/bin/python
import os
import sys
import commands
import shutil
import datetime
from optparse import OptionParser

# Get time and date
now = datetime.datetime.now()

# Get and seperate options from arguments
parser = OptionParser()
parser.add_option("-d", "--dir", dest="dirname", help="associated backup directory", metavar="FOLDER")
(options, args) = parser.parse_args()

# If not supplied get default from environment, or just store locally
if type(options.dirname)!=type('str'):
  options.dirname=os.environ.get("BACKUPDIR")
  if options.dirname=='None': dirname='./'

print 'Associated backup folder: ' + options.dirname
# Do the copying (including associated files)
# Its a bit dense down here, this is perhaps not the cleanest way
# But its quite stable and has a lot of error checks
for arg in args:
  # State copy commands to retrieve header-files from backup folder
  try:
    if os.path.exists(os.path.join(options.dirname,arg)):
      commands.getoutput('cp -f ' + os.path.join(options.dirname,arg) + ' .')
      print 'Retrieved file: ' + arg
      f=open(arg, 'a')
      f.write('sdrFromBackup: '+now.strftime("%Y-%m-%d %H:%M"+'\n\n'))
      f.close()
    else:
      print 'Not retrieved file: ' + infile

    try:
      hfffile=str(commands.getoutput('Get <' + arg + ' hff parform=n')).rstrip().lstrip()
      if os.path.exists(hfffile):
        commands.getoutput('cp -f ' + hfffile + ' .')
        f=open(os.path.basename(hfffile), 'a')
        f.write('sdrFromBackup: '+now.strftime("%Y-%m-%d %H:%M"+'\n\n'))
        f.close()
        print 'Retrieved file: ' + hfffile
      else:
        print 'Not retrieved file: ' + hfffile
    except:
      print 'No associated headerfile for: '+arg

  except Exception, err:
    print 'Not retrieved file: ' + arg
    print err


