#!/usr/bin/env bash

# Creates a new bare clone of a repository with the bare files within a `.bare`
# directory. It also sets the origin URL so push and pull work as expected.

if [[ "$1" == "" ]]; then
  echo "Usage: ${0##*/} <repository> [<directory>]"
  exit 2
fi

set -euo pipefail

repository_url="${1}"
directory="${2:-}"
location=".bare"

# If no destination directory is specified, get it from the repository URL - the same as "git clone".
if [ -z "${directory}" ]; then
  directory="$(basename -s .git "${repository_url}")"
fi

# Create the parent directory if needed.
mkdir -pv "${directory}"
cd "${directory}"

git clone --bare "${repository_url}" "${location}"

# Adjust origin fetch locations.
cd "${location}"
git config remote.origin.fetch "+refs/heads/*:refs/remotes/origin/*"

# Set .git file contents.
cd ..
echo "gitdir: ./${location}" > .git