#!/bin/bash

DEST="/var/www/html/clima"
GOES="/mnt/goes/IMAGES/GOES-19/Full Disk"

mkdir -p "$DEST" "$DEST/historial_ir" "$DEST/historial_fc"

FECHA=$(date +%Y%m%d_%H%M%S)

buscar_ir() {
    find "$GOES" -type f \( \
        -name "abi_rgb_Clean_Longwave_IR_Window_Band_map.png" -o \
        -name "abi_rgb_Infrared_Longwave_Window_Band_map.png" -o \
        -name "abi_rgb_Dirty_Longwave_Window.png" -o \
        -name "*Longwave*Window*map.png" \
    \) ! -name "*Shortwave*" -printf '%T@ %p\n' 2>/dev/null \
    | sort -n | tail -1 | cut -d' ' -f2-
}

buscar_fc() {
    find "$GOES" -type f \( \
        -name "abi_rgb_ABI_False_Color_map.png" -o \
        -name "abi_rgb_ABI_False_Color.png" -o \
        -name "*False_Color*map.png" \
    \) -printf '%T@ %p\n' 2>/dev/null \
    | sort -n | tail -1 | cut -d' ' -f2-
}

buscar_wv() {
    find "$GOES" -type f \( \
        -name "abi_rgb_Upper-Level_Tropospheric_Water_Vapor_map.png" -o \
        -name "*Upper-Level_Tropospheric_Water_Vapor*map.png" \
    \) -printf '%T@ %p\n' 2>/dev/null \
    | sort -n | tail -1 | cut -d' ' -f2-
}

recortar_valdivia() {
    convert "$1" \
        -gravity South \
        -crop 700x700+0+300 \
        +repage \
        -resize 900x900 \
        "$2"
}

############################
# INFRARROJO
############################

IR=$(buscar_ir)

if [ -n "$IR" ] && [ -f "$IR" ]; then
    recortar_valdivia "$IR" "$DEST/valdivia_ir.jpg"
    cp "$DEST/valdivia_ir.jpg" "$DEST/historial_ir/ir_${FECHA}.jpg"
fi

############################
# FALSO COLOR
############################

FC=$(buscar_fc)

if [ -n "$FC" ] && [ -f "$FC" ]; then
    recortar_valdivia "$FC" "$DEST/valdivia_fc.jpg"
    cp "$DEST/valdivia_fc.jpg" "$DEST/historial_fc/fc_${FECHA}.jpg"
fi

############################
# VAPOR DE AGUA (nivel alto)
############################

WV=$(buscar_wv)

if [ -n "$WV" ] && [ -f "$WV" ]; then
    recortar_valdivia "$WV" "$DEST/valdivia_wv.jpg"
fi

############################
# BORRAR HISTORIAL ANTIGUO
############################

ls -1t "$DEST/historial_ir"/*.jpg 2>/dev/null | tail -n +49 | xargs -r rm -f
ls -1t "$DEST/historial_fc"/*.jpg 2>/dev/null | tail -n +49 | xargs -r rm -f

############################
# GENERAR LISTA DE IMAGENES
############################

(
echo "["
FIRST=1
for f in $(ls "$DEST"/historial_ir/*.jpg 2>/dev/null | sort); do
    NOMBRE=$(basename "$f")
    if [ $FIRST -eq 0 ]; then echo ","; fi
    echo -n "\"$NOMBRE\""
    FIRST=0
done
echo "]"
) > "$DEST/historial_ir/lista.json"

date '+Actualizado: %d-%m-%Y %H:%M:%S' > "$DEST/ultima_actualizacion.txt"
