#!/usr/bin/bash

# Copyright 2022 Grillo del Mal
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

set -e 

APP_NAME=$0
VERSION="0.1.1"

function usageDialog() {
    echo "Usage: $APP_NAME [OPTION]... TAG"
}

function helpDialog() {
    echo "Creates a repository in the current folder, creates an empty commit"
    echo "and sets the described tag for it."
    echo "The purpose of this is to have a method to set what the"
    echo "'git describe' command shows without needing to import a project's"
    echo "git history."
    echo ""
    echo "Arguments"
    echo "      --rm                    Removes the repository in the current"
    echo "                              folder, prompts before removal."
    echo "  -f, --force                 Never prompt, stomp on everything"
    echo "                              (use with caution!)."
    echo "  -m, --minimal               Skip using propper git commands and"
    echo "                              write empty hash-objects."
    echo "  -h, --help                  Display this help and exit."
    echo "      --version               Output version information and exit."
}

# Parse arguments

while [ True ]
do
    if [ "$1" = "--help" -o "$1" = "--h" ]; then
        usageDialog
        helpDialog
        exit 0
    elif [ "$1" = "--version" ]; then
        echo "$0 version $VERSION"
        exit 0
    elif [ "$1" = "--rm" ]; then
        REMOVE=1
        shift 1
    elif [ "$1" = "--force" -o "$1" = "-f" ]; then
        FORCE=1
        shift 1
    elif [ "$1" = "--minimal" -o "$1" = "-m" ]; then
        MINIMAL=1
        shift 1
    else
        break
    fi
done

# Verify if this command can run

if [ $# = 0 ]; then
    echo "Error: You need to set a tag."
    usageDialog
    exit 1
fi

if [ $# -gt 1 ]; then
    echo "Error: too many arguments ($#)."
    usageDialog
    exit 1
fi

if ! command -v git &> /dev/null; then
    echo "Error: git command could not be found."
    exit 1
fi

if ! git check-ref-format tags/$1; then
    echo "Error: \"$1\" is an invalid tag."
    usageDialog
    exit 1
fi

if [ -e ".git" -a ! "$REMOVE" = "1" ] ; then 
    echo "Error: A git repository already exists in this folder."
    exit 1 
fi

# Erase if configured to do so

if [ -e ".git" -a "$REMOVE" = "1" ] ; then
    if [ "$FORCE" = "1" ]; then
        rm -rf ./.git
    else
        rm -rI ./.git
    fi

    if [ -e ".git" ]; then
        exit 1
    fi
fi

if [ $MINIMAL ] ; then

# Declare auxiliary functions

function buildTree() {
echo | cat | git hash-object -t tree -w --stdin <<EOF
EOF
}

function buildCommit() {
echo | cat | git hash-object -t commit -w --stdin <<EOF
tree $1

EOF
}

function buildTag() {
echo | cat | git hash-object -t tag -w --stdin <<EOF
object $1
type commit
tag $2

EOF
}

    # git init

    mkdir -p .git/objects
    mkdir -p .git/refs/tags
    echo "ref: refs/heads/main" > .git/HEAD

    # git commit

    TREE=$(buildTree)
    COMMIT=$(buildCommit ${TREE})

    # git tag

    TAG=$(buildTag ${COMMIT} $1)
    echo "${TAG}" > .git/refs/tags/$1

    # git checkout

    echo "${COMMIT}" > .git/HEAD
else
    git init &> /dev/null
    git config user.email "a@a.a"
    git config user.name "a"
    git \
        commit \
            --allow-empty \
            -m 'a' &> /dev/null
    git tag -a $1 -m 'a'
fi

# --- done ---
git describe
