#!/usr/bin/env nix-shell
#! nix-shell -i bash --pure
#! nix-shell -p bash coreutils git gnused

# Replace git folders with a placeholder containing the remote and the commit

function prompt { # text
    while true; do
        read -p "$1 [yn] " yn
        case $yn in
            [Yy]* ) return 1;;
            [Nn]* ) return 0;;
            * ) echo "Please answer yes or no.";;
        esac
    done
}

if [[ "$#" == 0 || "$#" > 2 ]]
then
    echo "Usage: $0 gitfolder [-y]"
    exit 1
fi

folder="$(echo "$1" | sed 's/\/*$//')"
if [ "$2" == "-y" ]
then
    donotask=true
fi

if [ ! -d "$folder/.git" ]
then
    echo "$folder is not a git repository"
    exit 1
fi

if [ -n "$(git -C "$folder" diff)" ]
then
    echo "WARNING: There are unstaged change. Those will be discarded if you continue."
fi

echo "Be sure that every commit in the repository is backed up somewhere else, since those will be discarded."

TMPFILE=$(mktemp)

(echo "[gitplaceholder]"
echo "lastcommit=$(git log --format="%H" -n 1)"
echo
echo "[remote]"
git -C "$folder" remote -v
echo
echo "[branch]"
git -C "$folder" branch -v
echo
echo "[diff]"
git -C "$folder" diff -v) > $TMPFILE 2> /dev/null

if [ ! $donotask ]
then
    less $TMPFILE
    echo
    echo "This will be written in place of $folder."
    prompt "Do you want to continue ?"
    if [ "$?" == 0 ]
    then
        echo "Canceled"
        rm $TMPFILE
        exit 0
    fi
fi
echo "Dummying..."
rm -rf "$folder"
mv $TMPFILE $folder