#!/bin/ksh -x

export LANG=en_US.UTF-8

#dataf=$1
#datai=`date -d "${dataf} 00:00 -1 day ago" +"%Y%m%d"`

datai=2024010100
dataf=2024123123

datai=2024010100
dataf=2025010100
dataf=2024010123

tmp=/share/ioper/tempo/MERGE/GOES/OBS/ANA/TMP/${datai}_${dataf}
scr=/share/ioper/tempo/MERGE/GOES/OBS
out=/share/ioper/tempo/MERGE/GOES/OBS/ANA/${dataf:0:6}

rm -f $tmp/ANA_*.txt

arquivo="$scr/lista_final.txt"

MAX_TIME="00:01:00" # Tempo máximo permitido (HH:MM:SS)

while read -r IDs LON LAT ALT; do
  for pid in $(ps -aux | grep "/usr/bin/wget --timeout=30 --continue --tries=5 --limit-rate=500k --wait=2 --random-wait -O "|grep -v color  | awk '{if ($3 == "0.0") print $2}'); do
    etime=$(ps -p "$pid" -o etime= | tr -d ' ')
    if [[ "$etime" > "$MAX_TIME" ]]; then
        echo "Processo travado! PID: $pid | Tempo de execucao: $etime"
        echo "Matando o  processo PID: $pid"
        kill -9 "$pid"
    else
        echo "Processo PID: $pid inativo, mas dentro do limite de tempo ($etime)."
    fi
  done
  $scr/busca_ANA.ksh $datai $dataf $IDs $LON $LAT $tmp  & 

  while [ $(ps -auxwww |grep https://telemetriaws1.ana.gov.br  |wc -l) -ge 5 ] ; do 
    sleep 5
  done 
done < "$arquivo"

sleep 5
cd  $tmp 
cat ANA*.txt > OBS_${datai}_${dataf}.txt
$scr/processa_ANA_horario.ksh $datai ${dataf}
rm -Rf $tmp 


