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


. ./config.cfg  ##include configuration file

set -x
# Set your bucket name and directory to store downloaded images
gcbucket_folder="${gcbucket_folder}/ts/"
local_dir="${web_path}/animation/geocolor/"

echo "gcbucker_folder -> $gcbucket_folder"

# # Create the local directory if it doesn't exist
# mkdir -p "${local_dir}"

# # Download the latest 10 files with prefix "geojson_" sorted by reverse creation time
# gsutil -m cp "${gcbucket_folder}/geocolor_*.jpg"  \
#   "${local_dir}" \
#   -r -n 10 \
#   -Filter "creationTime() > TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 90 MINUTE)"

# # Create the GIF animation using ImageMagick (assuming the download was successful)
# if [ $? -eq 0 ]; then
#   convert -delay 10 -loop 0 "${local_dir}"/*.png geocolor.gif
# fi



# #!/bin/bash

# Define variables
BUCKET_PATH=$gcbucket_folder
LOCAL_PATH=$local_dir

TIME_THRESHOLD=$((90 * 60))  # 90 minutes in seconds

# Create the local path if it doesn't exist
mkdir -p $LOCAL_PATH

# Get the current time in seconds since epoch
CURRENT_TIME=$(date +%s)

# List files with timestamps, filter and copy them
gsutil ls -l ${BUCKET_PATH}geocolor*.jpg | while read -r line; do
    # Extract the timestamp and file path
    TIMESTAMP=$(echo $line | awk '{print $2}')
    FILE_PATH=$(echo $line | awk '{print $3}')
    
    # Convert timestamp to seconds since epoch
    FILE_TIME=$(date -d "$TIMESTAMP" +%s)
    
    # Calculate the age of the file in seconds
    FILE_AGE=$((CURRENT_TIME - FILE_TIME))
    
    # Check if the file is not older than 90 minutes
    if [ $FILE_AGE -le $TIME_THRESHOLD ]; then
        # Copy the file
        gsutil cp $FILE_PATH $LOCAL_PATH
    fi
done

# Create an animation using ImageMagick
cd $LOCAL_PATH
convert -delay 20 -loop 0 $LOCAL_PATH/geocolor*.jpg $LOCAL_PATH/animation.gif

# Optional: Clean up old jpg files to save space
#rm geocolor*.jpg
set +x