#!/bin/ksh -x
export LANG=en_US.UTF-8

datai=$1
dataf=$2

DIR=/share/ioper/tempo/MERGE/GOES/OBS/ANA/TMP/${datai}_${dataf}

cd $DIR

ARQUIVO="OBS_${datai}_${dataf}.txt"  # Substitua pelo seu arquivo
DIR_SAIDA="/share/ioper/tempo/MERGE/GOES/OBS/ANA/${datai:0:4}"
mkdir -p "$DIR_SAIDA"

# Lista todos os arquivos possíveis e remove antes de processar
awk '
{
    split($4, dt, "_")
    data = dt[1]
    time = dt[2]
    ano = substr(data, 1, 4)
    mes = substr(data, 6, 2)
    dia = substr(data, 9, 2)
    hora = substr(time, 1, 2)
    minuto = substr(time, 4, 2)

    if (minuto >= 15) {
        hora = sprintf("%02d", (hora + 1) % 24)
        if (hora == "00") {
            timestamp = mktime(ano " " mes " " dia " 00 00 00")
            timestamp += 86400
            data = strftime("%Y-%m-%d", timestamp)
            ano = substr(data, 1, 4)
            mes = substr(data, 6, 2)
            dia = substr(data, 9, 2)
        }
    }

    chave = ano mes dia hora
    if (!(chave in seen)) {
        seen[chave] = 1
        print "'"$DIR_SAIDA"'/PREC_ANA_" chave ".txt"
    }
}' "$ARQUIVO" | sort -u | while read arq; do
    rm -f "$arq"
done

# Agora processa e gera os arquivos
awk '
{
    id = $1
    lon = $2
    lat = $3
    split($4, dt, "_")
    data = dt[1]
    time = dt[2]

    ano = substr(data, 1, 4)
    mes = substr(data, 6, 2)
    dia = substr(data, 9, 2)
    hora = substr(time, 1, 2)
    minuto = substr(time, 4, 2)

    if (minuto >= 15) {
        hora = sprintf("%02d", (hora + 1) % 24)
        if (hora == "00") {
            timestamp = mktime(ano " " mes " " dia " 00 00 00")
            timestamp += 86400
            data = strftime("%Y-%m-%d", timestamp)
            ano = substr(data, 1, 4)
            mes = substr(data, 6, 2)
            dia = substr(data, 9, 2)
        }
    }

    chave = id "_"ano mes dia hora
    acumulado[chave] += $5
    info[chave] = id " ANA " lon " " lat
}
END {
    for (k in acumulado) {
        split(k, partes, "_")
        id = partes[1]
        stamp = partes[2]
        arq = sprintf("%s/PREC_ANA_%s.txt", "'"$DIR_SAIDA"'", stamp)
        print info[k] " " acumulado[k] >> arq
    }
}
' "$ARQUIVO"

exit



















data=$1

datai=$(date -d "${data:0:8} ${data:8:2} -24 hour" +"%Y%m%d")
dataf=$data

datai2=$data
dataf2=$(date -d "${data:0:8} ${data:8:2} +24 hour" +"%Y%m%d")

tmp=/scripts/ioper/Modelos/Download/scripts/OBS/ANA/TMP/${datai}_${dataf}
tmp2=/scripts/ioper/Modelos/Download/scripts/OBS/ANA/TMP/${datai2}_${dataf2}
scr=/scripts/ioper/Modelos/Download/scripts/OBS/ANA
out=/lustre_xc50/ioper/data/external/OBS_NEW/HOURLY/${dataf:0:6}/${dataf:6:2}

cat $tmp/OBS_${datai}_${dataf}.txt  $tmp2/OBS_${datai2}_${dataf2}.txt |sort -u > $tmp/OBS_TMP_$data.txt

di=$(date -d "${dataf:0:8} 00 -4 hour" +"%Y%m%d%H")
df=$(echo $(cat $tmp/OBS_${datai}_${dataf}.txt |awk {'print $4}' |sort -u |tac |head -1)| sed 's/[-_:]//g' | cut -c1-10)

while [ "$di" -le "$df" ]; do
    ddi=$di
    ddf=$(date -d "${di:0:8} ${di:8:2} +1 hour" +"%Y%m%d%H")
    dd_GMT=$(date -d "${ddf:0:8} ${ddf:8:2} +3 hour" +"%Y%m%d%H")
    echo $dd_GMT
    rm -f $out/PREC_ANA_${dd_GMT}.txt
    for id in $(cat $tmp/OBS_${datai}_${dataf}.txt |awk '{print $1}' |sort -u ) ; do
       if [ $(grep $id $tmp/OBS_TMP_$data.txt | awk -v start="${ddi:0:4}-${ddi:4:2}-${ddi:6:2}_${ddi:8:2}:01:00" -v end="${ddf:0:4}-${ddf:4:2}-${ddf:6:2}_${ddf:8:2}:00:00" '$4 >= start && $4 <= end   {print $1"  "$2"  "$3"  "$4"  "$5}' |wc -l) -gt 0 ] ; then
          grep $id $tmp/OBS_${datai}_${dataf}.txt | awk -v start="${ddi:0:4}-${ddi:4:2}-${ddi:6:2}_${ddi:8:2}:01:00" -v end="${ddf:0:4}-${ddf:4:2}-${ddf:6:2}_${ddf:8:2}:00:00" '$4 >= start && $4 <= end {sum += $5} END {if (sum <= 100) printf "%s  ANA  %s  %s  %.2f\n", $1, $2, $3, sum}' >> $out/PREC_ANA_${dd_GMT}.txt
       fi
    done
    di=$(date -d "${di:0:8} ${di:8:2} +1 hour" +"%Y%m%d%H")
done

exit
rm -f $tmp/OBS_TMP_$data.txt

hora_atual=$(date +%H)
if [ "$hora_atual" -lt 4 ]; then
  /scripts/ioper/Modelos/Download/scripts/OBS/ANA/refaz_21_22_23.ksh $datai
fi



