#!/usr/bin/env bash
#
# Fix_Xcode_Dependencies
# Martin Hrubý (hrubymar10), 2016 - 2020, 2022-2024
# Victor Sergienko (singalen), 2018
#

###Functions
time_interval_to_string() {
  local duration=$(($2 - $1)) days hours minutes seconds

  days=$((duration/60/60/24))
  hours=$((duration%(60*60*24)/60/60))
  minutes=$((duration%(60*60)/60))
  seconds=$((duration%60))
  if ((days == 0)); then
    if ((hours == 0)); then
      if ((minutes == 0)); then
        echo "==> Operation took $seconds seconds ..."
      else
        echo "==> Operation took $minutes minutes and $seconds seconds ..."
      fi
    else
      echo "==> Operation took $hours hours $minutes minutes and $seconds seconds ..."
    fi
  else
    echo "==> Operation took $days days $hours hours $minutes minutes and $seconds seconds ..."
  fi
}

get_mcs() {
  git clone -b "1.18" --depth 1 "https://github.com/hrubymar10/MacCompileStuff" "MacCompileStuff-1.18"
}
###/Functions

SECONDS=0

MY_PATH=$(cd "$(dirname "$0")" && pwd)
if [ -z "$MY_PATH" ] ; then
  # error; for some reason, the path is not accessible
  # to the script (e.g. permissions re-evaled after suid)
  echo 'Error: Script path is for some reason not accessible' >&2
  exit 1  # fail
fi
cd "${MY_PATH}" || exit

if ! [ -d "The Battle for Wesnoth.xcodeproj" ]; then
  echo 'Error: I am in bad directory! I must be in wesnoth/projectfiles/Xcode !' >&2
  exit 1
fi

if ! command -v git >/dev/null; then
  echo 'Error: Git is not installed. Use for example Homebrew to install git. https://brew.sh/' >&2
  exit 1
fi

mkdir -p "temp" || exit
cd "temp" || exit
rm -rf MacCompileStuff-master

if ! [ -d "MacCompileStuff-1.18" ]; then
  get_mcs
else
  cd "MacCompileStuff-1.18"
  git pull --depth 5
  if ! [ $? -eq 0 ]; then
    echo 'Error: MacCompileStuff is too far from the local commit. Clonning again...' >&2
    cd ".." || exit
    rm -rf "MacCompileStuff-1.18"
    get_mcs
  fi
fi
cd "${MY_PATH}" || exit

rm -f "Headers"
ln -s "temp/MacCompileStuff-1.18/Headers"

rm -f "lib"
ln -s "temp/MacCompileStuff-1.18/lib"

echo "==> DONE ..."
echo
time_interval_to_string 0 "$SECONDS"
echo
