#!/bin/bash
# After find_bad_files_in_pack we have a list for each simulation with 
# files unexpected in pack. Now for all these files we will find in 
# which pack we stored them
# 
# output = List_BadFile_$LOGIN.txt
# syntax ::  pack name -->  file name. 
#

LISTE_LOGIN=$SCRATCHDIR/pack_ipsl_logs/liste_login_debug.txt 

IGCM_TMP=$SCRATCHDIR/TMP_PACK
mkdir -p ${IGCM_TMP}
rm -rf ${IGCM_TMP}/*

cd ${IGCM_TMP}
for LOGIN in `awk  '{print $0}' ${LISTE_LOGIN}` ; do 
#LOGIN=p86caub
    ls -l $SCRATCHDIR/SAVE_PACK/$LOGIN > ${IGCM_TMP}/${$}.liste1.txt
    

    listSimu=`awk '{print $9}'  ${IGCM_TMP}/${$}.liste1.txt`
    echo "${listSimu}" >> ${IGCM_TMP}/${$}.liste.simu.txt
    grep -v liste_simul ${IGCM_TMP}/${$}.liste.simu.txt > ${IGCM_TMP}/${$}.liste.simu.txt.tmp
    mv ${IGCM_TMP}/${$}.liste.simu.txt.tmp ${IGCM_TMP}/${$}.liste.simu.txt
    sed -i -e "s/.info_bug_pack_output.txt//g"  ${IGCM_TMP}/${$}.liste.simu.txt


    for SIMU in `awk '{print $0}' ${IGCM_TMP}/${$}.liste.simu.txt` ; do 
	echo $SIMU
	cp $SCRATCHDIR/SAVE_PACK/$LOGIN/${SIMU}.info_bug_pack_output.txt ${IGCM_TMP}/${$}.liste.tmp
	sed -i -e "s%.*${LOGIN}%%g"  ${IGCM_TMP}/${$}.liste.tmp
	sed -i -e "s%/${SIMU}/.*$%%g"  ${IGCM_TMP}/${$}.liste.tmp

	little_path=`awk '{if (NR==1) print $0}' ${IGCM_TMP}/${$}.liste.tmp `
	# on recupere le repertoire output_tar et output_ncrcat de cette simu
	tar xf $SCRATCHDIR/pack_ipsl_logs/${LOGIN}.ipsl_logs.tgz ${LOGIN}/IGCM_DEM${little_path}/${SIMU}/output_ncrcat
	tar xf $SCRATCHDIR/pack_ipsl_logs/${LOGIN}.ipsl_logs.tgz ${LOGIN}/IGCM_DEM${little_path}/${SIMU}/output_tar


	
	for file in `awk '{print $2}'  $SCRATCHDIR/SAVE_PACK/$LOGIN/${SIMU}.info_bug_pack_output.txt`; do
	    BadFile=`grep  $file $LOGIN/IGCM_DEM${little_path}/${SIMU}/output_ncrcat/*list`
	    if [[ $BadFile != "" ]]; then 
		echo  "(.nc)" ${BadFile} >> $SCRATCHDIR/SAVE_PACK/$LOGIN/List_BadFile_$LOGIN.txt
	    fi
	    BadFile=`grep  $file $LOGIN/IGCM_DEM${little_path}/${SIMU}/output_tar/*list`
	    if [[ $BadFile != "" ]]; then 
		echo "(.tar)"  ${BadFile} >> $SCRATCHDIR/SAVE_PACK/$LOGIN/List_BadFile_$LOGIN.txt
	    fi
	done
	
    done
    sed -i -e "s%IGCM_DEM%dmf_import%g"  $SCRATCHDIR/SAVE_PACK/$LOGIN/List_BadFile_$LOGIN.txt
    sed -i -e '/(.tar)/ s%.list%.tar%g' $SCRATCHDIR/SAVE_PACK/$LOGIN/List_BadFile_$LOGIN.txt
    sed -i -e '/(.nc)/ s%.list%%g' $SCRATCHDIR/SAVE_PACK/$LOGIN/List_BadFile_$LOGIN.txt
    sed -i -e "s% $LOGIN%/ccc/store/cont003/dsm/$LOGIN%g"  $SCRATCHDIR/SAVE_PACK/$LOGIN/List_BadFile_$LOGIN.txt
    sed -i -e "s%output_ncrcat/%*/Output/*/%g"  $SCRATCHDIR/SAVE_PACK/$LOGIN/List_BadFile_$LOGIN.txt
    sed -i -e "s%output_tar/%*/Output/*/%g"  $SCRATCHDIR/SAVE_PACK/$LOGIN/List_BadFile_$LOGIN.txt
    sed -i -e "s%:% --> %g"  $SCRATCHDIR/SAVE_PACK/$LOGIN/List_BadFile_$LOGIN.txt
    sed -i -e "s%(.tar)%%g" $SCRATCHDIR/SAVE_PACK/$LOGIN/List_BadFile_$LOGIN.txt
    sed -i -e "s%(.nc)%%g" $SCRATCHDIR/SAVE_PACK/$LOGIN/List_BadFile_$LOGIN.txt


done