#!/bin/bash

# Set your Supabase project URL and API key
SUPABASE_URL="https://v5.fares.cyou"
SUPABASE_API_KEY="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyAgCiAgICAicm9sZSI6ICJzZXJ2aWNlX3JvbGUiLAogICAgImlzcyI6ICJzdXBhYmFzZS1kZW1vIiwKICAgICJpYXQiOiAxNjQxNzY5MjAwLAogICAgImV4cCI6IDE3OTk1MzU2MDAKfQ.DaYlNEoUrrEn2Ig7tqibS-PHK5vgusbcbo7X36XVt4Q"
BUCKET_NAME="csv"
#FOLDER="/ftphich"

# Directory to watch
WATCHED_DIR="/app/watched"

# Files to monitor
FILES_TO_MONITOR=("ExportPGRGPNmois.zip" "secondprgtype.zip" "exportPRG.zip" "exportPGRGPN.zip" "exportlicence.txt")

# Declare an associative array to hold the last modified timestamps
declare -A last_modified

# Initialize the last modified timestamps
#"for file in "${FILES_TO_MONITOR[@]}"; do
#   last_modified["$file"]=$(stat -c %Y "$WATCHED_DIR/$file" 2>/dev/null)
#done



# Function to upload file to Supabase
upload_file() {
    local file="$1"
    local basename_file=$(basename "$file")
    
    #echo "Uploading $basename_file to Supabase storage..."

    # Use curl to upload the file
    response=$(curl --fail-with-body -X POST "${SUPABASE_URL}/upload" \
        -H "Content-Type: application/octet-stream" \
        -H "Authorization: Bearer ${SUPABASE_API_KEY}" \
        --data-binary @"$file" 2>/dev/null)

    response=$(curl -F "file=@$file;type=application/octet-stream" \
     -H "Authorization: Bearer  ${SUPABASE_API_KEY}" \
     -X POST "${SUPABASE_URL}/upload" 2>/dev/null)

    if [ $? -eq 0 ]; then
        echo "File uploaded successfully: $response"
        # Check if the upload was successful
        if echo "$response" | grep -q '"Key":';  then
        #echo "$response"
            echo "$(date '+%d%b%y %H:%M:%S') +++ Successfully uploaded $basename_file."
        else
            echo "$(date '+%d%b%y %H:%M:%S') --- Failed to upload $basename_file. Response: $response"
        fi

    else 
        echo "$(date '+%d%b%y %H:%M:%S') --- Failed to upload file. Response: $response"
    fi

}

# Polling loop
while true; do
    for file in "${FILES_TO_MONITOR[@]}"; do
        full_path="$WATCHED_DIR/$file"
        # Get the current modified timestamp
        current_modified=$(stat -c %Y "$full_path" 2>/dev/null)
        #echo "file $file timestamp $current_modified"
        # Check if the file has been modified
        if [[ "$current_modified" != "${last_modified[$file]}" ]]; then
            formatted_lastdate=$(date -d @"${last_modified[$file]}" '+%d%b%y %H%M')
            formatted_curdate=$(date -d @"$current_modified" '+%d%b%y %H%M')
            echo "=================================================== $file"
            echo "$(date '+%d%b%y %H:%M:%S') ... file has been modified. last: $formatted_lastdate >>> current: $formatted_curdate"
            upload_file "$full_path"
            # Update the last modified timestamp
            last_modified["$file"]=$current_modified
        fi
    done
    # Sleep for a specified interval (e.g., 5 seconds)
    sleep 5
done


