#!/usr/bin/env bash
# git "shared" but disconnected clone, useful for local throwaway repositories.
# Author: Noah Friedman <friedman@splode.com>
# Created: 2019-08-18
# Public domain

# $Id: git-sclone,v 1.1 2019/08/21 19:44:37 friedman Exp $

# Commentary:

# Removes upstream information to avoid accidental contamination of
# original while still making history available.

# Code:

# Removes last element from ARRAYNAME.  Optional arg N removes last N.
apop() { eval "$1=(\"\${$1[@]:0:\${#$1[@]}-${2-1}}\")"; }

main()
{
    arg=( "$@" )
    dstdir=${arg[-1]}
    apop arg

    if [[ -d $dstdir ]]; then
        srcdir=$dstdir
        dstdir=${srcdir##*/}
        dstdir=${dstdir%.git}
    else
        srcdir=${arg[-1]}
        apop arg
    fi

    emptydir=${XDG_RUNTIME_DIR-${TMPDIR-/tmp}}/empty.$$
    trap 'rmdir "$emptydir"' 0 1 2 3 15
    (umask 077; mkdir -p "$emptydir")

    ${GITPROG-git} clone --shared --template "$emptydir" "${arg[@]}" -- "$srcdir" "$dstdir"
    ${GITPROG-git} -C "$dstdir" branch   --unset-upstream
    ${GITPROG-git} -C "$dstdir" config   --remove-section remote.origin
    ${GITPROG-git} -C "$dstdir" restore-commit-mtime
}

main "$@"

# eof
