#!/bin/sh

set -e

die () {
    echo >&2 "error: " "$@"
    exit 1
}

# Verify that we're in a normal git checkout.
if ! [ -d ".git" ]; then
    if [ -f ".git" ]; then
        die "already a worktree checkout"
    fi
    die "no '.git' directory found"
fi

# Move `.git` to be a bare repository.
readonly bare_repo="$PWD/ci-orig.git"
if [ -e "$bare_repo" ]; then
    die "the target bare repository already exists"
fi
mv -v ".git" "$bare_repo"
git -C "$bare_repo" config --bool core.bare true

# Make a worktree.
readonly worktree_dir="$bare_repo/worktrees/gitlab-ci"
mkdir -p "$worktree_dir"

# Populate the worktree metadata.
echo "$PWD/.git" > "$worktree_dir/gitdir"
echo "../.." > "$worktree_dir/commondir"
# Perform a "checkout" of the repository.
cp "$bare_repo/HEAD" "$worktree_dir"
cp "$bare_repo/index" "$worktree_dir"
# Link to the worktree.
echo "gitdir: $worktree_dir" > .git

echo "linked as a worktree from $worktree_dir"
