#!/usr/bin/env bash

set -euo pipefail

TARGET_DIR="${CI_TARGET_DIR:-/workspace/repo}"
REF_NAME="${CI_REF_NAME:-}"
INPUT_BRANCH="${CI_INPUT_BRANCH:-}"
DEFAULT_BRANCH="${CI_DEFAULT_BRANCH:-main}"
REPOSITORY="${CI_REPOSITORY:?CI_REPOSITORY is required}"
TOKEN="${CI_TOKEN:-}"
FETCH_DEPTH="${CI_FETCH_DEPTH:-1}"

if [ -n "$REF_NAME" ]; then
  SELECTED_REF="$REF_NAME"
elif [ -n "$INPUT_BRANCH" ]; then
  SELECTED_REF="$INPUT_BRANCH"
else
  SELECTED_REF="$DEFAULT_BRANCH"
fi

PARENT_DIR="$(dirname "$TARGET_DIR")"
mkdir -p "$PARENT_DIR"
rm -rf "$TARGET_DIR"

CLONE_URL="https://git.michaelschiemer.de/${REPOSITORY}.git"

if [ -n "$TOKEN" ]; then
  AUTH_URL="https://${TOKEN}@git.michaelschiemer.de/${REPOSITORY}.git"
  git clone --depth "$FETCH_DEPTH" --branch "$SELECTED_REF" "$AUTH_URL" "$TARGET_DIR"
else
  if ! git clone --depth "$FETCH_DEPTH" --branch "$SELECTED_REF" "$CLONE_URL" "$TARGET_DIR"; then
    git clone --depth "$FETCH_DEPTH" "$CLONE_URL" "$TARGET_DIR"
    (
      cd "$TARGET_DIR"
      git checkout "$SELECTED_REF" || true
    )
  fi
fi

cd "$TARGET_DIR"
echo "Checked out $SELECTED_REF into $TARGET_DIR"
