#!/bin/bash

set -e

# running:
# bash ./scripts/flags/fetch_flags.sh

# source: https://github.com/hampusborgos/country-flags/tree/main

cur_dir="$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"

declare -A codes=(
    [eu]="eu"
    [fr]="fr"
    [gb]="en" # we alias uk flag for en locale
    [de]="de"
    [pt]="pt"
    [it]="it"
    [es]="es"
    [nl]="nl"
)

output_dir="src/Resources/public/back/images/locale"
output_dir_bis="assets/front/images/locale"
echo "Will start downloading flags into: $output_dir"
echo "and: $output_dir"

for code in "${!codes[@]}"; do
    output_path="$cur_dir/../../$output_dir/${codes[$code]}.png"
    # todo: check if secondary path is used by admin/projects
    output_path_bis="$cur_dir/../../$output_dir_bis/${codes[$code]}.png"
    #url="https://raw.githubusercontent.com/hampusborgos/country-flags/refs/heads/main/png100px/${code}.png"
    # png versions were deleted (https://github.com/hampusborgos/country-flags/commit/815b3352e743d19beb1fb7fd5845faadb9f8e5e6)
    #url="https://github.com/hampusborgos/country-flags/blob/ba2cf4101bf029d2ada26da2f95121de74581a4d/png100px/${code}.png"
    url="https://raw.githubusercontent.com/hampusborgos/country-flags/ba2cf4101bf029d2ada26da2f95121de74581a4d/png100px/${code}.png"

    echo "Downloading ${code} 📥"

    # Fetch file and check HTTP status
    http_status=$(curl -s -o "$output_path" -w "%{http_code}" "$url")

    if [[ "$http_status" == "404" ]]; then
        echo "❌ Error: ${url} returned 404 Not Found."
        rm -f "$output_path" # Remove the incomplete file
        exit 1
    elif [[ "$http_status" != "200" ]]; then
        echo "❌ Error: Failed to download ${url}. HTTP status code: $http_status"
        rm -f "$output_path" # Remove the incomplete file
        exit 1
    fi

    http_status_bis=$(curl -s -o "$output_path_bis" -w "%{http_code}" "$url")

    cp "$output_path" "$output_path_bis"

    echo "    ✅\ Success"
done
