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

### Variables
DESIRED_TAG="v0.0.1"

###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 --depth 1 --branch "${DESIRED_TAG}" "https://github.com/hrubymar10/MacCompileStuff" "MacCompileStuff-${DESIRED_TAG}"
}

check_and_checkout_tag() {
  local repo_path="$1"

  cd "$repo_path" || return 1

  CURRENT_TAG=$(git describe --tags --exact-match 2>/dev/null)
  if [ "${CURRENT_TAG}" != "${DESIRED_TAG}" ]; then
    echo "==> Checking out tag ${DESIRED_TAG} ..."
    git fetch --tags
    git checkout "${DESIRED_TAG}" || return 1
  fi
}
###/Functions

SECONDS=0

MY_PATH=$(cd "$(dirname "$0")" && pwd)
if [ -z "$MY_PATH" ] ; then
  echo 'Error: Script path is for some reason not accessible' >&2
  exit 1
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

if ! [ -d "MacCompileStuff-${DESIRED_TAG}" ]; then
  get_mcs
else
  cd "MacCompileStuff-${DESIRED_TAG}"
  if ! check_and_checkout_tag .; then
    echo 'Error: Failed to checkout correct tag. Cloning again...' >&2
    cd ".." || exit
    rm -rf "MacCompileStuff-${DESIRED_TAG}"
    get_mcs
  fi
fi
cd "${MY_PATH}" || exit

rm -f "Headers"
ln -s "temp/MacCompileStuff-${DESIRED_TAG}/Headers"

rm -f "lib"
ln -s "temp/MacCompileStuff-${DESIRED_TAG}/lib"

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