#!/bin/bash

#----------------------------------------------------------
# Bash script to download horizontal slices for a specific wind direction
# ERCOFTAC KB Wiki for the AC-5/6 case
#
# File Created: April 08, 2026
# J.M. Duró (UPC), A. Miró (UPC), E. Mestres (UPC), O. Lehmkuhl (BSC), I. Rodriguez (UPC)
#-----------------------------------------------------------

# Assigning arguments to variables
ANGLE=$1
START=$2
END=$3
DH=$4
DEST=${5:-.}

# Variables
URL=https://kbwiki-data.s3-eu-west-2.amazonaws.com
CASE=AC-5/6
FOLDER=slices

# Safety check. This replaces the dot in angle with a hyphen.
ANGLE="${ANGLE//./-}"

# Create the main destination and the meshes subdirectory
sliceFolder="$DEST/city_$ANGLE"
meshFolder="$DEST/meshes"

mkdir -p "${sliceFolder}"
mkdir -p "${meshFolder}"

printf "Starting download for Angle: $ANGLE from Height $START to $END..."

for h in $(seq "$START" "$DH" "$END"); do
    echo "------------------------------------------"
    echo "Processing Height: $h"

    # 1. Download the Slice file (checking for existence in destination)
    SLICE_FILE="${FOLDER}/city_${ANGLE}/height_${h}-vtk.hdf"
    SLICE_URL="${URL}/${CASE}/${SLICE_FILE}"
    SLICE_DEST="${sliceFolder}/height_${h}-vtk.hdf"
    
    if [ ! -f "$SLICE_DEST" ]; then
        curl -L --progress-bar -o "$SLICE_DEST" "$SLICE_URL"
    else
        echo "Slice file already exists in ${sliceFolder}. Skipping download."
    fi

    # 2. Download the Mesh file (checking for existence in destination)
    MESH_FILE="${FOLDER}/meshes/height_${h}-vtk.hdf"
    MESH_URL="${URL}/${CASE}/${MESH_FILE}"
    MESH_DEST="${meshFolder}/height_${h}-vtk.hdf"

    if [ ! -f "$MESH_DEST" ]; then
        curl -L --progress-bar -o "$MESH_DEST" "$MESH_URL"
    else
        echo "Mesh file already exists in ${meshFolder}. Skipping download."
    fi
done
