#!/bin/bash

set -euo pipefail
set -xuve

# Function to regrid the HILDA+ data to a specified resolution and handle metadata
regrid_hildaplus() {
  local ifile=$1
  local ofile=$2
  local tmpdir=$3
  local resolution=$4
  local year=$5
  local output_width=$6
  local output_height=$7
  local xmin=$8
  local ymin=$9
  local xmax=${10}
  local ymax=${11}
  local tmp_prefix="tmp"
  local ovar="LULC_states"
  
  echo "Starting regrid_hildaplus for year: ${year} with resolution: ${resolution}"

  # Clean up any existing temporary files
  rm -f ${tmp_prefix}?.nc

  # Calculate the correct time index
  local time_index=$((year - 1899))

  # Extract the data for the specific year
  echo "Extracting data for year ${year} (time index: ${time_index})..."
  ncks -O -d time,${time_index} ${ifile} ${tmp_prefix}1.nc

  # Perform the regridding using gdalwarp
  echo "Executing gdalwarp..."
  gdalwarp -overwrite -of netcdf -ot Byte -co FORMAT=NC4 -r mode -ts ${output_width} ${output_height} -te ${xmin} ${ymin} ${xmax} ${ymax} -multi -wo NUM_THREADS=8 NETCDF:"${tmp_prefix}1.nc":${ovar} ${tmp_prefix}3.nc

  if [ $? -ne 0 ]; then
    echo "gdalwarp failed"
    exit 1
  fi
  echo "gdalwarp completed successfully."

  # Add time dimension to the file
  echo "Adding time dimension..."
  ncecat -u time ${tmp_prefix}3.nc ${tmp_prefix}4.nc
  ncap2 -O -s "time[time]={${year}}" ${tmp_prefix}4.nc ${tmp_prefix}5.nc
  ncatted -O -a units,time,o,c,"years since ${year}-01-01" ${tmp_prefix}5.nc
  echo "Time dimension added successfully."

  # Fix metadata using ncatted
  echo "Fixing metadata..."
  ncatted -h -a history,global,d,, ${tmp_prefix}5.nc
  ncatted -h -a history,global,c,c,"`date` : regridded to ${resolution} degrees resolution using gdalwarp and fixed metadata using nco" ${tmp_prefix}5.nc
  echo "Metadata fixed successfully."

  # Rename the variable to the original name
  echo "Renaming variables..."
  ncrename -h -v Band1,${ovar} ${tmp_prefix}5.nc
  if [ $? -ne 0 ]; then
    echo "ncrename failed"
    exit 1
  fi
  echo "Variables renamed successfully."

  # Add variable-specific metadata
  echo "Adding metadata..."
  ncatted -h -a long_name,${ovar},m,c,"land use/cover category as numeric codes" ${tmp_prefix}5.nc
  ncatted -h -a standard_name,${ovar},c,c,"land_cover_lccs" ${tmp_prefix}5.nc
  ncatted -h -a units,${ovar},o,c,"numeric land use/cover codes" ${tmp_prefix}5.nc
  ncatted -h -a _FillValue,${ovar},o,c,99 ${tmp_prefix}5.nc

  # Move the final product to the output directory
  echo "Moving final product to output directory..."
  mv ${tmp_prefix}5.nc ${ofile}
  if [ $? -ne 0 ]; then
    echo "Failed to move the final product to the output directory"
    exit 1
  fi
  echo "Final product moved successfully."

  # Clean up temporary files
  echo "Cleaning up temporary files..."
  rm -f ${tmp_prefix}?.nc
  echo "Temporary files cleaned up."

  echo "Finished processing for year: ${year} with resolution: ${resolution}"
}

# Parameters
ifile=$1
ofile=$2
tmpdir=$3
resolution=$4
year=$5
output_width=$6
output_height=$7
xmin=$8
ymin=$9
xmax=${10}
ymax=${11}

mkdir -p $tmpdir
cd $tmpdir

# Process files for the given year
regrid_hildaplus ${ifile} ${ofile} ${tmpdir} ${resolution} ${year} ${output_width} ${output_height} ${xmin} ${ymin} ${xmax} ${ymax}
