#!/bin/bash

set -euo pipefail

ROOT_DIR="$(git rev-parse --show-toplevel)"
LIBSIGNAL_DIR="${ROOT_DIR}/../libsignal-ios-v0.100.0-kivo"
LIBSIGNAL_REMOTE="https://github.com/sowhat1010/libsignal.git"
LIBSIGNAL_COMMIT="ed3a21d54b0caf1684eb1bf1dba62fff64c784ef"
LIBSIGNAL_TREE="7acb693463102d8ae4e9fe780493968684bd901f"

if [[ ! -d "${LIBSIGNAL_DIR}/.git" ]]; then
  git clone --no-checkout "${LIBSIGNAL_REMOTE}" "${LIBSIGNAL_DIR}"
elif [[ -n "$(git -C "${LIBSIGNAL_DIR}" status --porcelain)" ]]; then
  echo "Refusing to replace a dirty libsignal checkout: ${LIBSIGNAL_DIR}" >&2
  exit 1
fi

git -C "${LIBSIGNAL_DIR}" fetch --depth=1 "${LIBSIGNAL_REMOTE}" "${LIBSIGNAL_COMMIT}"
git -C "${LIBSIGNAL_DIR}" checkout --detach "${LIBSIGNAL_COMMIT}"

actual_tree="$(git -C "${LIBSIGNAL_DIR}" rev-parse HEAD^{tree})"
if [[ "${actual_tree}" != "${LIBSIGNAL_TREE}" ]]; then
  echo "Unexpected libsignal source tree: ${actual_tree}" >&2
  exit 1
fi

cd "${ROOT_DIR}"
if ! bundle check >/dev/null; then
  echo "Ruby dependencies are missing. Run 'bundle install' and retry." >&2
  exit 1
fi

git submodule update --init --recursive Pods SignalServiceKit/tests/MessageBackup/Signal-Message-Backup-Tests

# SignalRingRTC's podspec prepares its cached WebRTC framework during
# `pod install`, but CocoaPods decides framework search paths before that
# prepare step runs.  A fresh checkout therefore needs the pinned artifact in
# place before the first Pods project is generated; otherwise only a second
# `pod install` reproduces the frozen xcconfig files.
Pods/SignalRingRTC/bin/set-up-for-cocoapods
bundle exec pod install
cmp Podfile.lock Pods/Manifest.lock
Scripts/verify_kivo_pods_install

echo "Kivo open-source dependencies are pinned and installed."
