#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: Elena Graverini
# @Date:   2015-12-15 11:41:23
# @Last Modified by:   Elena Graverini
# @Last Modified time: 2015-12-15 12:00:34

# This file should be run on lxplus
import os, sys
if not sys.argv:
    lastYear = 2015
else:
    lastYear = int(sys.argv[1])
years = range(2009, lastYear + 1)
location_tt = '/group/st/sw/RadiationMonitoring/LeakageCurrent/InputData/TT/Temperatures'
location_it = '/group/st/sw/RadiationMonitoring/LeakageCurrent/InputData/IT/Temperatures'
for y in years:
    os.system('scp egraveri@lbgw:%s/tt_box_temperatures_%s.txt .' % (location_tt, y))
    os.system('scp egraveri@lbgw:%s/it_box_temperatures_%s.txt .' % (location_it, y))
output_location = '/afs/cern.ch/user/e/egraveri/cmtuser/STMonitoring/STAging/data/temperature'
output_tt = output_location + '/tttemp.txt'
output_it = output_location + '/ittemp.txt'
print('Backing up old files...')
os.system('mv %s %s_BK' % (output_tt, output_tt))
os.system('mv %s %s_BK' % (output_it, output_it))


def concatenate(filelist, destination):
    with open(destination, 'w') as outfile:
        for fname in filelist:
            with open(fname, 'r') as infile:
                for line in infile:
                    outfile.write(line)

files_tt = ['tt_box_temperatures_%s.txt' % y for y in years]
files_it = ['it_box_temperatures_%s.txt' % y for y in years]
concatenate(files_tt, output_tt)
concatenate(files_it, output_it)
for f in files_tt:
    os.system('rm %s' % f)
for f in files_it:
    os.system('rm %s' % f)
