#!/usr/bin/env bash

if [ "$BASIC_BASE_URL" == "" ]; then
    base_url="https://gitea.tforgione.fr/basic/"
    custom_base_url=false
else
    base_url=$BASIC_BASE_URL
    echo $base_url | grep /$ > /dev/null 2>&1
    if [ $? -ne 0 ]; then
        base_url="$base_url"/
    fi
    custom_base_url=true
fi

eprint() {
    echo -e >&2 "\x1B[1;31merror:\x1B[0m" $@
}

info() {
    echo -e "\x1B[1minfo:\x1B[0m" $@
}

info_n() {
    echo -en "\x1B[1minfo:\x1B[0m" $@
}

print-help() {
    echo -e "\033[32mbasic\033[0m"
    echo -e "Thomas Forgione <thomas@forgione.fr>"
    echo -e "A script that automatically clones templates from $base_url"
    echo -e "Use the environment variable BASIC_BASE_URL to clone templates from somewhere else."
    echo
    print-usage
}

print-usage() {
    echo -e "\033[33mUSAGE:\033[0m"
    echo -e "    \033[32mbasic init <template>\033[0m                initialize a template in the current directory"
    echo -e "    \033[32mbasic init <template> <directory>\033[0m    initialize a template in the specified directory"

}

print-usage-and-exit() {
    print-usage
    exit $1
}

git_clone() {
    GIT_TERMINAL_PROMPT=0 git ls-remote $1 > /dev/null 2>&1
    if [ $? -ne 0 ]; then
        eprint "the repository $1 does not exist or is private"
        exit 1
    fi

    if [ -d $2 ] && [ ! -z "$(ls -A $2)" ]; then
        if [ "$2" == "." ]; then
            eprint "the current directory is not empty"
            info "use \`basic init <template> <directory>\` to specify another directory"
        else
            eprint "the directory $2 exists and is not empty"
        fi
        print-usage-and-exit 2
    fi

    info_n "downloading template..."
    GIT_TERMINAL_PROMPT=0 git clone $@ > /dev/null 2>&1
    if [ $? -ne 0 ]; then
        echo >&2
        eprint "failed to download template"
        print-usage-and-exit 2
    fi
    echo " done!"
}

init() {
    template=$1

    if [ $# -gt 1 ]; then
        name=$2
    else
        name=.
    fi

    git_clone $base_url/$1 $name
    rm -rf $name/.git
}

main() {
    arg=$1
    shift

    case $arg in
        "init")
            init $@
            ;;

        "help")
            print-help
            exit
            ;;

        ?*)
            eprint "command $arg does not exist"
            print-usage-and-exit 1
            ;;

        "")
            print-help
            exit
            ;;
    esac
}

main $@