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

starttimestamp=$(date +%s)

###Functions
time_interval_to_string() {
  local START=$1
  local END=$2

  declare -i timestamp
  declare -i days
  declare -i hours
  declare -i minutes
  declare -i seconds
  timestamp=$END-$START

  days=$timestamp/60/60/24
  hours=$((($timestamp-($days*60*60*24))/60/60))
  minutes=$((($timestamp-($days*60*60*24)-($hours*60*60))/60))
  seconds=$((($timestamp-($days*60*60*24)-($hours*60*60)-($minutes*60))))
  if [ $days -eq 0 ]; then
    if [ $hours -eq 0 ]; then
      if [ $minutes -eq 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 "universal_libs_support" --depth 1 "https://github.com/hrubymar10/MacCompileStuff" "MacCompileStuff-universal_libs_support"
}
###/Functions

starttimestamp=`date +%s`

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}"

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 ! [ -x "$(command -v git)" ]; then
  echo 'Error: Git is not installed. Use for example Homebrew to install git. https://brew.sh/' >&2
  exit 1
fi

if ! [ -d "temp" ]; then
  mkdir "temp"
fi
cd "temp"
if [ -d "MacCompileStuff-master" ]; then
  rm -rf MacCompileStuff-master
fi

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

rm -rf "Headers"
ln -s "temp/MacCompileStuff-universal_libs_support/Headers"

rm -rf "lib"
ln -s "temp/MacCompileStuff-universal_libs_support/lib"

echo "==> DONE ..."
echo
time_interval_to_string "$starttimestamp" "$(date +%s)"
echo
