#!/usr/bin/env bash 
set -x
export LANG=en_US.UTF-8
export LC_ALL=en_US.UTF-8

datai=2022120100
dataf=2023030100

SRC="/share/ioper/tempo/MERGE/GOES/OBS"

# Obter token e lista de tipos de dados
token=$(python "$SRC/ecf_token-cemaden.py")
data_type_lst=$(python "$SRC/ecf_token-cemaden.py" "$token") || data_type_lst=""


while [ -n "$datai" ] && [ "$datai" -le "$dataf" ]; do 
    echo "$datai"
    data="$datai"
    inicio=$(date -d "${data:0:8} ${data:8:10}:00 1 hours ago" +"%Y%m%d%H")01
    fim=${data}00

    DOUT="/share/ioper/tempo/MERGE/GOES/OBS/${fim}"
    SHARE="/share/ioper/tempo/MERGE/GOES/OBS/CEMADEN/${data:0:6}"

    mkdir -p "$SHARE"
    mkdir -p "$DOUT" || { echo "Failed to create directory $DOUT"; exit 1; }

    uf_list="AC AL AP AM BA CE DF ES GO MA MT MS MG PA PB PR PE PI RJ RN RS RO RR SC SP SE TO"

    retry_download() {
         url="$1"
         token="$2"
         output_file="$3"
         max_attempts=${max_attempts:-5}  # Garante que max_attempts tenha um valor
         attempt=1
         success=0
         user=rozante
        while [ "$attempt" -le "$max_attempts" ]; do
           token=$(python "$SRC/ecf_token-cemaden.py_$user")
           curl -X "GET" "$url" -H "accept: text/csv" -H "token: $token" --max-time 30 -o "$output_file"
           echo curl -X "GET" "$url" -H "accept: text/csv" -H "token: $token" --max-time 30 -o "$output_file"
            if [ "$?" -eq 0 ] && [ -s "$output_file" ] && grep -q "chuva" "$output_file"; then
                success=1
                break
            fi
	    if [ $(grep  "Nenhum resultado foi encontrado para" $output_file |wc -l) -eq 1 ] ; then
	      break
	    fi
	    if [ $(grep  "Este token excedeu o" $output_file |wc -l) -eq 1 ] ; then
	      echo "     "
	      echo "ESPERANDO 5 SEGUNDO PARA LIBERAR O TOKEN"
	      echo "     "
          if [ $user == rozante ] ; then
            user=banco
          else
            user=rozante
          fi	      
#	      sleep 5
#          token=$(python "$SRC/ecf_token-cemaden.py_$user")
	    fi
            attempt=$((attempt + 1))
        done

        if [ "${success:-0}" -eq 0 ]; then
            echo "Failed to download: $url" >> "$DOUT/failed_downloads.log"
            rm -f "$output_file"
        fi
    }

    cd "$SRC"

    for uf in $uf_list; do
        for data_type in $data_type_lst; do
            [ -z "$data_type" ] && continue  # Pula caso data_type seja vazio
             output_file="${DOUT}/${uf}_${data_type}_${fim}.dat"
            url="http://sws.cemaden.gov.br/PED/rest/pcds/dados_rede?fim=${fim}&inicio=${inicio}&tipo_pcd=${data_type}&uf=${uf}"
            retry_download "$url" "$token" "$output_file" &
            if (( $(jobs | wc -l) >= 1 )); then
                wait -n
            fi
        done
    done

    wait

    cd "$DOUT"
    cat *"${fim}.dat" | grep -E -v "OBS\.|cod\.estacao|requisi|Info" | grep "chuva" | awk -F';' '{print $1, $6, $5, $9}' | awk '
    {
        soma[$1] += $4
        if (!($1 in long_lat)) {
            long_lat[$1] = "CEMADEN "$2 " "$3
        }
    }
    END {
        for (id in soma) {
            print id, long_lat[id], soma[id]
        }
    }' > "$SHARE/PREC_CEMADEN_${data}.txt"

    rm -f *"${fim}"*.dat
    rm -rf "$DOUT"
    echo ""  
    echo "DADOS DO CEMADEN ${data} BAIXADOS COM SUCESSO"
    echo ""   
    datai=$(date -d "${datai:0:8} ${datai:8:10}:00 1 hours" +"%Y%m%d%H")
done

exit
