echo $0
cd "$(dirname "$0")"
echo $(date)


. ./config.cfg  ##include configuration file

mkdir -p $web_path ##create folder if not exists

### $1 = Producto
### $2 = Canal Goes
### $3 = DATASET del netcdf
### $4 = nombre de la imagen final
### bash /cloudclusters/projects/goes_gdal/goes_netcdf.sh ABI-L2-CMIPF 02 CMI goes16_02

$python_path goes_down.py $1 $2

##ver netcdf "NUEVO"
cmp -s down/ultimo_$1_$2.nc down/ultimo_$1_$2_old.nc
resultado=$?
echo "Resultado $resultado"
if test $resultado -eq 0
    then
        echo " The NTCDF files match....exit"
        exit
else
        echo "The NETCDF file is different"
        cp down/ultimo_$1_$2.nc down/ultimo_$1_$2_old.nc
fi

rm $1_$2_$3*.tif

if [ $2 = "02" ] || [ $2 = "01" ] ; then
    echo "-scale grayscale"
    $gdal_path/gdal_translate -scale NETCDF:down/ultimo_$1_$2.nc:$3 $1_$2_$3.tif
##fi
##if [ $2 = "13" ]; then
else
    echo "-------------------unscale--------------"
    echo "COMANDO: $gdal_path/gdal_translate -unscale NETCDF:$(dirname "$0")/down/ultimo_$1_$2.nc:$3 $1_$2_$3.tif"
    $gdal_path/gdal_translate -unscale NETCDF:$(dirname "$0")/down/ultimo_$1_$2.nc:$3 $1_$2_$3.tif
fi

$gdal_path/gdalwarp -t_srs EPSG:4326 $1_$2_$3.tif $1_$2_$3_4326.tif -overwrite
$gdal_path/gdal_translate -projwin -120 35 -50 0 $1_$2_$3_4326.tif $1_$2_$3_4326_crop.tif

$gdal_path/gdalwarp -t_srs EPSG:3857 -r cubicspline $1_$2_$3_4326_crop.tif $1_$2_$3_3857.tif -overwrite

if [ $2 = "02" ] || [ $2 = "01" ]; then
    $gdal_path/gdal_translate -ot Byte $1_$2_$3_3857.tif $web_path/$4.jpg
    /usr/bin/convert -quality 75% -scale 75% -brightness-contrast 5x10 -transparent black -fuzz 25% $web_path/$4.jpg $web_path/$4.gif
    ## muy grande /usr/bin/convert -quality 75% -scale 50% -brightness-contrast 10x10 -transparent black -fuzz 20% $web_path/$4.jpg $web_path/$4.png
    echo "Generado: $web_path/$4.jpg y gif"
    imgtype="gif"
##fi
##if [ $2 = "13" ]; then
else
   if [ $2 = "RR" ]; then

    ## fix valores a 0
   ## no fun $gdal_path/gdal_calc.py -A $1_$2_$3_4326_crop.tif --outfile=$1_$2_$3_4326_cropfix.tif --calc="A*1"  --type=UInt16 --NoDataValue=0 --overwrite
   ## no fun  cp $1_$2_$3_4326_cropfix.tif $1_$2_$3_4326_crop.tif
    ## fin fix valores raros a 0

    $gdal_path/gdalwarp $1_$2_$3_3857.tif -r cubicspline -tr 1500 1500 $1_$2_$3_3857r.tif -overwrite
    $gdal_path/gdaldem color-relief $1_$2_$3_3857r.tif -nearest_color_entry ./colors$2$3.txt $web_path/$4.png -alpha
    else 
    $gdal_path/gdaldem color-relief $1_$2_$3_3857.tif -nearest_color_entry ./colors$2$3.txt $web_path/$4.png -alpha
    fi
    /usr/bin/convert -scale 70% $web_path/$4.png $web_path/$4.png
    imgtype="png"
fi

## guardar el geotiff en web
cp $1_$2_$3_4326_crop.tif $web_path/$4.tif

cmp -s $web_path/$4.$imgtype $web_path/$4_1.$imgtype
resultado=$?
echo "Resultado $resultado"
if test $resultado -eq 0
    then
        echo " The files match"
else
        echo "The  new file is different"
#fi
 	#	cp $web_path/$2_8.png $web_path/$2_9.png
 	#	cp $web_path/$2_7.png $web_path/$2_8.png
 	#	cp $web_path/$2_6.png $web_path/$2_7.png
 	#	cp $web_path/$4_5.$imgtype $web_path/$4_6.$imgtype
 		cp $web_path/$4_4.$imgtype $web_path/$4_5.$imgtype
 		cp $web_path/$4_3.$imgtype $web_path/$4_4.$imgtype
 		cp $web_path/$4_2.$imgtype $web_path/$4_3.$imgtype
 		cp $web_path/$4_1.$imgtype $web_path/$4_2.$imgtype
 		cp $web_path/$4.$imgtype $web_path/$4_1.$imgtype

        ## TIFF
        cp $web_path/$4_4.tif $web_path/$4_5.tif
 		cp $web_path/$4_3.tif $web_path/$4_4.tif
 		cp $web_path/$4_2.tif $web_path/$4_3.tif
 		cp $web_path/$4_1.tif $web_path/$4_2.tif
 		cp $web_path/$4.tif $web_path/$4_1.tif


         ##crear gif //ver esto por el png https://stackoverflow.com/questions/14676119/imagemagick-and-transparent-background-for-animated-gif
        echo "Crear GIF -> $(date)"
        /usr/bin/convert -delay 50 -loop 0 -alpha set -dispose previous `ls -vr $web_path/$4*.$imgtype` $web_path/a_$4new.gif
        echo "GIF  creado -> $(date)"
        ##optimize
        echo "mogrify optimizar -> $(date)"
        /usr/bin/mogrify -layers 'optimize' -fuzz 10% $web_path/a_$4new.gif
        echo "optimizado -> $(date)"
        cp $web_path/a_$4new.gif $web_path/a_$4.gif


 fi

## para hacer sandwich
## composite -dissolve 30 /cloudclusters/default_site/data/goes/goes16_13_5.png /cloudclusters/default_site/data/goes/goes16_02_5.gif -alpha Set -resize 1662x888 -gravity center /cloudclusters/default_site/data/test/test_sw.png

### ################# compuesto visible +  rayos ############################3
if [ $2 = "01" ] ; then
    echo "Haciendo el composite"
    composite $web_path/rayos.png $web_path/goes16_01.gif -alpha set -resize 3562x1904 -gravity center $web_path/goes16_visglm.gif
    cp $web_path/goes16_visglm_4.gif $web_path/goes16_visglm_5.gif
    cp $web_path/goes16_visglm_3.gif $web_path/goes16_visglm_4.gif
    cp $web_path/goes16_visglm_2.gif $web_path/goes16_visglm_3.gif
    cp $web_path/goes16_visglm_1.gif $web_path/goes16_visglm_2.gif
    cp $web_path/goes16_visglm.gif   $web_path/goes16_visglm_1.gif

##crear gif //ver esto por el png https://stackoverflow.com/questions/14676119/imagemagick-and-transparent-background-for-animated-gif
    echo "El gif del composite con prueba"
    /usr/bin/convert -delay 50 -loop 0 -alpha set -dispose previous `ls -vr $web_path/goes16_visglm*.gif` $web_path/a_goes16_visglm.gif
  
fi

############################ rayos y tiempo severo enfriamiento #############################
if [ $2 = "13" ] ; then
echo "Generado heatmap de rayos"
rm down/OR_GLM* ##borrando los anteriores
$gdal_path/python goes_glm.py $web_path 600 ##eran 900 por 15m ahora 600
$gdal_path/gdal_rasterize -burn 1.0 -tr 0.05 0.05 -a_nodata 0.0 -ot Byte -of GTiff -add $web_path/rayos.geojson $web_path/rayos.tif
$gdal_path/gdal_translate -projwin -120 35 -50 0 $web_path/rayos.tif $web_path/rayos_crop.tif
$gdal_path/gdalwarp -t_srs EPSG:3857 $web_path/rayos_crop.tif rayos_3857.tif -overwrite
## 220817 no resample $gdal_path/gdalwarp -r cubicspline -tr 1000 1000 rayos_3857.tif rayos_3857r.tif -overwrite
## $gdal_path/gdalwarp -t_srs EPSG:3857 $web_path/rayos_crop.tif rayos_3857.tif -overwrite
$gdal_path/gdaldem color-relief rayos_3857.tif ./colorsGLM.txt -nearest_color_entry $web_path/rayos.png -alpha

cp $web_path/rayos_4.png $web_path/rayos_5.png
cp $web_path/rayos_3.png $web_path/rayos_4.png
cp $web_path/rayos_2.png $web_path/rayos_3.png
cp $web_path/rayos_1.png $web_path/rayos_2.png
cp $web_path/rayos.png $web_path/rayos_1.png
##crear gif //ver esto por el png https://stackoverflow.com/questions/14676119/imagemagick-and-transparent-background-for-animated-gif
echo "Crear GIF rayos -> $(date)"
/usr/bin/convert -delay 50 -loop 0 -alpha set -dispose previous `ls -vr $web_path/rayos*.png` $web_path/a_rayos_new.gif
echo "GIF rayos creado -> $(date)"
cp $web_path/a_rayos_new.gif $web_path/a_rayos.gif
##optimize
#/usr/bin/mogrify -layers 'optimize' -fuzz 10% $web_path/a_$4.gif
############## fin rayos

##diferencia tiempo severo
$gdal_path/gdal_calc.py -A $web_path/$4_1.tif -B $web_path/$4_2.tif --calc="1*((A<223)*(A-B)<-40)*(A-B)" --outfile $web_path/$4dif.tif --overwrite
$gdal_path/gdal_calc.py -A $web_path/$4_1.tif -B $web_path/$4_2.tif --calc="(A-B)" --outfile $web_path/$4diffull.tif --overwrite

##alertas 230529 se cambio de 0.20 a 0.10 rayos.tif
cd ../alerts_raster
/bin/bash r_alertas.sh $goes_url/rayos.tif rayos GT 50 0.10 15 35000
/bin/bash r_alertas.sh $goes_url/$4dif.tif $4dif LT -85 0.10 15 35000

##envio de alertas
cd "$(dirname "$0")" ##regresar al path 
/bin/bash loop_alerts.sh rayos
/bin/bash loop_alerts.sh goes16_13dif
fi

##22.10.04 alertas de lluvia 1 y generacion de geotiff
if [ $2 = "RR" ]; then
    echo "Calculo de lluvia horaria para alertar -> $(date)"
    ### calculo de lluvia horaria para alertar 231009 se cambio a /1 para que sea un promedio entre el inicio y final de la medición alerta en 80mm 80% del maxico 83.3mmm
    ### vamos a cambiar a lo que dice el docto$gdal_path/gdal_calc.py -A $web_path/$4_1.tif -B $web_path/$4_2.tif -C $web_path/$4_3.tif -D $web_path/$4_4.tif -E $web_path/$4_5.tif --calc="((A/6)+(B/6)+(C/6)+(D/6)+(E/6))/1" --outfile $web_path/$4_1h.tif --overwrite
    ## solo los últimos 4 ~ 15 minutos
    $gdal_path/gdal_calc.py -A $web_path/$4_1.tif -B $web_path/$4_2.tif -C $web_path/$4_3.tif -D $web_path/$4_4.tif --calc="((A*15/60/2)+(B*15/60/2)+(C*15/60/2)+(D*15/60/2))/1" --outfile $web_path/$4_1h.tif --overwrite
    
    ##230614 para usar RR como datos de lluvia reciente desde QPE
    $gdal_path/gdalwarp $web_path/$4_1h.tif -t_srs EPSG:3857 -r cubicspline -tr 1500 1500 $4_1h_3857r.tif -overwrite
    $gdal_path/gdaldem color-relief $4_1h_3857r.tif -nearest_color_entry ./colorsRR.txt $web_path/goes16_accRR_1h.png -alpha
    

    ##envio de alertas
    cd ../alerts_raster
    /bin/bash r_alertas.sh $goes_url/$4_1h.tif pcpn_1h GT 45 0.10 15 30000
    cd "$(dirname "$0")" ##regresar al path 
    /bin/bash loop_alerts.sh pcpn_1h
fi
echo $(date)

##23.06.05 calculo overshooting tops al final cuando ya se generaron
if [ $2 = "14" ]; then
    echo "Calcular overshooting tops -> $(date)"
    ### calculo de lluvia horaria para alertar

    # Get the time coverage end values from the TIFF files
    time_coverage_end_14=$($gdal_path/gdalinfo $web_path/goes16_14.tif | grep -i NC_GLOBAL#time_coverage_end=)
    time_coverage_end_13=$($gdal_path/gdalinfo $web_path/goes16_13.tif | grep -i NC_GLOBAL#time_coverage_end=)

    # Extract the timestamps from the time coverage end values
    timestamp_14=$(echo $time_coverage_end_14 | cut -d'=' -f2)
    timestamp_13=$(echo $time_coverage_end_13 | cut -d'=' -f2)

    # Convert the timestamps to Unix timestamps
    unix_timestamp_14=$(date -d "$timestamp_14" +%s)
    unix_timestamp_13=$(date -d "$timestamp_13" +%s)

    # Calculate the time difference in seconds (absolute value)
    time_difference=$((unix_timestamp_14 - unix_timestamp_13))
    time_difference=${time_difference#-}   ###valor absoluto

    # Check if the time difference is less than 2 minutes (120 seconds)
    if ((time_difference < 120)); then
        echo "The timestamps are less than 2 minutes apart. 14: $timestamp_14 13: $timestamp_13"
        $gdal_path/gdal_calc.py -A $web_path/goes16_14.tif -B $web_path/goes16_13.tif --calc="(A<221)*(A-B)" --outfile $web_path/$4_ost.tif --overwrite
    fi
    
    
fi
echo $(date)

