#!/bin/bash

function do_header
{
    if [ -e "$header_path" ]; then
        read -p "'$header_path' already exists. Overwrite? (yes/no) ";

        if [ x$REPLY != xyes ]; then
            return 0;
        fi
    fi

    # --- QnD: Header File ---
    echo "#ifndef $header_guard" > $header_path;
    echo "    #define $header_guard" >> $header_path;
    echo >> $header_path;

    if [ x$namespace != x ]; then
        indent="    ";
        echo "namespace $namespace" >> $header_path;
        echo "{" >> $header_path;
    fi

    echo "${indent}class $name" >> $header_path;
    echo "${indent}{" >> $header_path;
    echo "${indent}public:" >> $header_path;
    echo "${indent}    ${name}(void);" >> $header_path;
    echo "${indent}    virtual ~${name}(void);" >> $header_path;
    echo "${indent}};" >> $header_path;

    if [ x$namespace != x ]; then
        echo "}" >> $header_path;
    fi

    echo >> $header_path;
    echo "#endif //${header_guard}" >> $header_path;
    echo >> $header_path;
}

function do_source
{
    if [ -e "$source_path" ]; then
        read -p "'$source_path' already exists. Overwrite? (yes/no) ";

        if [ x$REPLY != xyes ]; then
            return 0;
        fi
    fi

    # QnD --- Source File ---
    echo "#include <${nsdir}${header_file}>" > $source_path;
    echo >> $source_path;

    if [ x$namespace != x ]; then
        indent="    ";
        echo "namespace $namespace" >> $source_path;
        echo "{" >> $source_path;
    fi

    echo "${indent}${name}::${name}(void)" >> $source_path;
    echo "${indent}{" >> $source_path;
    echo "${indent}    // TODO" >> $source_path;
    echo "${indent}}" >> $source_path;
    echo >> $source_path;
    echo "${indent}${name}::~${name}(void)" >> $source_path;
    echo "${indent}{" >> $source_path;
    echo "${indent}    // TODO" >> $source_path;
    echo "${indent}}" >> $source_path;

    if [ x$namespace != x ]; then
        echo "}" >> $source_path;
    fi

    echo >> $source_path;
}

if [ x$1 = x ]; then
    echo "Usage: $0 NAME [NAMESPACE]";
    echo;
    echo "Where NAME is the name of the file/class and NAMESPACE is the namespace.";

    exit -1;
fi

name="`echo "$1" | sed -r 's/\s+//g'`";
namespace="`echo "$2" | sed -r 's/\s+//g'`";

if [ x$namespace = x ]; then
    header_guard="`echo "$name" | tr [:lower:] [:upper:]`_HPP";
else
    header_guard="`echo "\`echo "${namespace}" | sed -r 's/::/_/g'\`_${name}" | tr [:lower:] [:upper:]`_HPP";
fi

header_file="${name}.hpp";

if [ -d include ]; then
    incdir=include/;
fi

if [ x$namespace != x ]; then
    nsdir="`echo "$namespace" | sed -r 's/::/\//g'`/";
    mkdir -p "${incdir}${nsdir}";
fi

header_path="${incdir}${nsdir}${header_file}";

do_header;

source_file="${name}.cpp";

if [ -d src ]; then
    srcdir=src/;
fi

if [ x$namespace != x ]; then
    mkdir -p "${srcdir}${nsdir}";
fi

source_path="${srcdir}${nsdir}${source_file}";

do_source;

