#!/bin/sh
set -eu

repository="$1"
branch="$2"
snapshot_prefix="$3"
repo_path="$4"

private_key="${UNIDESK_CONTROLLER_GITHUB_SSH_PRIVATE_KEY}"
proxy_host="${UNIDESK_CONTROLLER_GITHUB_PROXY_HOST}"
proxy_port="${UNIDESK_CONTROLLER_GITHUB_PROXY_PORT}"

mkdir -p "$(dirname "${repo_path}")" /root/.ssh
cp "${private_key}" /root/.ssh/id_rsa
chmod 0400 /root/.ssh/id_rsa
touch /root/.ssh/known_hosts

test -n "${proxy_host}"
test -n "${proxy_port}"
export GIT_SSH=/etc/unidesk-cicd-branch-follower/git-ssh-proxy.sh
unset GIT_SSH_COMMAND

remote="ssh://git@ssh.github.com:443/${repository}.git"
if [ -d "${repo_path}/objects" ] && [ -f "${repo_path}/HEAD" ]; then
  git --git-dir="${repo_path}" remote set-url origin "${remote}" || git --git-dir="${repo_path}" remote add origin "${remote}"
else
  rm -rf "${repo_path}"
  git init --bare "${repo_path}" >/dev/null
  git --git-dir="${repo_path}" remote add origin "${remote}"
fi

git --git-dir="${repo_path}" config uploadpack.allowReachableSHA1InWant true
git --git-dir="${repo_path}" config uploadpack.allowAnySHA1InWant true
timeout 30 git --git-dir="${repo_path}" fetch --quiet --prune origin "+refs/heads/${branch}:refs/mirror-stage/heads/${branch}"
source_sha=$(git --git-dir="${repo_path}" rev-parse --verify "refs/mirror-stage/heads/${branch}^{commit}")
git --git-dir="${repo_path}" update-ref "refs/heads/${branch}" "${source_sha}"
if [ -n "${snapshot_prefix}" ]; then
  git --git-dir="${repo_path}" update-ref "${snapshot_prefix%/}/${source_sha}" "${source_sha}"
fi
git --git-dir="${repo_path}" update-server-info

printf '{"event":"unidesk-cicd-git-mirror-sync","repository":"%s","branch":"%s","commit":"%s","sourceAuthority":"k8s-git-mirror-cache"}\n' "${repository}" "${branch}" "${source_sha}"
