#!/bin/bash

BOLD='\e[1m'
RESET='\e[0m'

GREEN='\e[92m'
RED='\e[91m'
YELLOW='\e[93m'

echo -ne ${BOLD}
echo -e "---------------------"
echo -e "pugs plugin generator"
echo -e "---------------------"
echo -e ${RESET}

CURRENT_DIR="$(pwd -P)"
SCRIPT_DIR="$( cd -- "$(dirname "$0")" >/dev/null 2>&1 ; pwd -P )"
PUGS_DIR="$(dirname ${SCRIPT_DIR})"

if [[ "${CURRENT_DIR}" =~ "${PUGS_DIR}" ]]
then
    echo -e ${RED}"Aborting..."${RESET}
    echo -e "run this script outside of pugs sources"
    exit 1
fi

NAME_RE='^[A-Z][a-zA-Z0-9]*$'

echo "   Plugin name must fulfill the following constrains:"
echo "   - be a single word that starts by an upper case,"
echo "   - contains only letters or numbers,"
echo "   and preferably separate words with caps."
echo
echo "   ex.: MyFirstPlugin"
echo

while [[ ! "${PLUGIN_NAME}" =~ $NAME_RE ]]
do
    echo -n "Give plugin name: "
    read -r PLUGIN_NAME

    if [[ ! "${PLUGIN_NAME}" =~ $NAME_RE ]]
    then
	echo -e ${RED}"  invalid name!"${RESET}
	echo
	unset PLUGIN_NAME
    fi

done

PLUGIN_UP="${PLUGIN_NAME^^}"
PLUGIN_LOW="${PLUGIN_NAME,,}"
echo
echo -e "creating plugin ${YELLOW}${PLUGIN_NAME}${RESET} in directory ${YELLOW}${PLUGIN_LOW}${RESET}"
echo

if [[ -e ${PLUGIN_LOW} ]]
then
    echo -e ${RED}"Aborting..."${RESET}
    echo -e "directory \"${PLUGIN_LOW}\" ${YELLOW}already exists${RESET}!"
    exit 1
fi


mkdir "${PLUGIN_LOW}"
mkdir "${PLUGIN_LOW}/cmake"

cp "${PUGS_DIR}"/cmake/CheckNotInSources.cmake "${PLUGIN_LOW}"/cmake/
cp "${PUGS_DIR}"/tools/plugin-template/FindPugs.cmake "${PLUGIN_LOW}"/cmake/
cp "${PUGS_DIR}"/.gitignore "${PLUGIN_LOW}"
cp "${PUGS_DIR}"/.clang-format "${PLUGIN_LOW}"
cat "${PUGS_DIR}"/tools/plugin-template/CMakeLists.txt-template | sed s/_PLUGIN_NAME_/${PLUGIN_NAME}/g | sed s/_PLUGIN_LOW_/${PLUGIN_LOW}/g | sed s/_PLUGIN_UP_/${PLUGIN_UP}/g > "${PLUGIN_LOW}"/CMakeLists.txt
cat "${PUGS_DIR}"/tools/plugin-template/Module.hpp-template | sed s/_PLUGIN_NAME_/${PLUGIN_NAME}/g | sed s/_PLUGIN_LOW_/${PLUGIN_LOW}/g | sed s/_PLUGIN_UP_/${PLUGIN_UP}/g > "${PLUGIN_LOW}"/${PLUGIN_NAME}Module.hpp
cat "${PUGS_DIR}"/tools/plugin-template/Module.cpp-template | sed s/_PLUGIN_NAME_/${PLUGIN_NAME}/g | sed s/_PLUGIN_LOW_/${PLUGIN_LOW}/g | sed s/_PLUGIN_UP_/${PLUGIN_UP}/g > "${PLUGIN_LOW}"/${PLUGIN_NAME}Module.cpp
cat "${PUGS_DIR}"/tools/plugin-template/README.md-template | sed s/_PLUGIN_NAME_/${PLUGIN_NAME}/g | sed s/_PLUGIN_LOW_/${PLUGIN_LOW}/g | sed s/_PLUGIN_UP_/${PLUGIN_UP}/g > "${PLUGIN_LOW}"/README.md

(cd "${PLUGIN_LOW}"; git init -q)
(cd "${PLUGIN_LOW}"; git add .)
(cd "${PLUGIN_LOW}"; git commit -m "init" -q)

echo -e ${GREEN}"Creation finished successfully!"${RESET}
