#!/bin/bash
#
# Use this script to create a new plugin.
#

if [ -z "$1" ]; then
    echo "Usage: ./scripts/new_plugin plugin_name [plugin_number]"
    exit 1
fi

PLUGIN_NAME="${1%/}"
PLUGIN_NUM="$2"
SKELETON="t2PSkel"

rand_pl_num() {
    PLUGIN_NUM=$(cat /dev/urandom | tr -dc '0-9' | fold -w 3 | head -1)
}

if [ ! -d "$SKELETON" ]; then
    printf "\e[0;31mCould not find folder './%s/'\e[0m\n" "$SKELETON" >&2
    exit 1
fi

if [ -d "$PLUGIN_NAME" ] && [ "$(ls -a "$PLUGIN_NAME" | grep -v "^\.")" ]; then
    printf "\e[0;31mFolder '%s' already exists and is not empty\e[0m\n" "$PLUGIN_NAME" >&2
    exit 1
fi

if [ -z "$PLUGIN_NUM" ]; then
    rand_pl_num
    while [ "$(grep "^PLUGINORDER=$PLUGIN_NUM\ *$" */autogen.sh)" ]; do
        rand_pl_num
    done
    echo "No plugin number provided... using $PLUGIN_NUM"
else
    TMP="$(grep "^PLUGINORDER=$PLUGIN_NUM\ *$" */autogen.sh)"
    if [ "$TMP" ]; then
        printf "\e[0;31mPlugin number %s already used by '%s' plugin\e[0m\n" "$PLUGIN_NUM" "${TMP%/*}" >&2
        exit 1
    fi
fi

FILES=(
    AUTHORS
    autogen.sh
    ChangeLog
    configure.ac
    COPYING
    doc/Makefile
    doc/"$SKELETON".tex
    Makefile.am
    NEWS
    README
    src/Makefile.am
    src/"$SKELETON".h
    src/"$SKELETON".c
    t2plconf
    tests/"$SKELETON".flags
)

# Create directories and copy files
mkdir -p "$PLUGIN_NAME/"{doc,src,tests}
for i in ${FILES[@]}; do
    cp "$SKELETON/$i" "$PLUGIN_NAME/$i"
done
cd "$PLUGIN_NAME"

# Replace plugin name and order
sed -i "s/$SKELETON/$PLUGIN_NAME/g" ${FILES[@]}
sed -i "s/$SKELETON/\U$PLUGIN_NAME\E/ig" ${FILES[@]}
sed -i "s/^PLUGINORDER=999$/PLUGINORDER=${PLUGIN_NUM}/" autogen.sh

# Replace guard in header file
GUARD=$(echo "$PLUGIN_NAME" | sed 's/\([a-z0-9_]\+\)\([A-Z]\)/\1_\2/g')
SGUARD=$(echo "$SKELETON" | sed 's/\([a-z0-9_]\+\)\([A-Z]\)/\1_\2/g')
sed  -i "s/__${SGUARD}_H__/__\U$GUARD\E_H__/ig" "src/${SKELETON}.h"

# Rename files
mv "doc/${SKELETON}.tex" "doc/${PLUGIN_NAME}.tex"
mv "src/${SKELETON}.c" "src/${PLUGIN_NAME}.c"
mv "src/${SKELETON}.h" "src/${PLUGIN_NAME}.h"
mv "tests/${SKELETON}.flags" "tests/${PLUGIN_NAME}.flags"

printf "\e[0;32mPlugin '$PLUGIN_NAME' created\e[0m\n"
