#!/bin/bash

# Copyright (C) 2009-2013 Thiago Leucz Astrizi

# This file is part of Weaver Framework.

# Weaver Framework is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Weaver Framework is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Weaver Framework.  If not, see <http://www.gnu.org/licenses/>.

WEAVER=/usr/share/weaver
# If weaver isn't installed, it should work too
if ! [ -a ${WEAVER} ]; then
    WEAVER=${0:0:$((${#0}-6))}
fi

VERSION=0.2.0

# This function cleans the current directory recursively, erasing temporary
# files
function clean_directory(){
    find . -name "*\#" -exec rm -f {} \;
    find . -name "*.o" -exec rm -f {} \;
}

# This function prints a help message when the user is inside a Weaver
# Directory
function weaver_directory_help(){
    echo "       \\                You are inside a Weaver Directory."
    echo "        \\______/        The following command uses are available:"
    echo "        /\\____/\\"
    echo "       / /\\__/\\ \\       weaver"
    echo "    __/_/_/\\/\\_\\_\\___     Erases recursively temporary files."
    echo "      \\ \\ \\/\/ / /"
    echo "       \\ \\/__\\/ /       weaver NAME"
    echo "        \\/____\\/          Creates NAME.c and NAME.h, updating"
    echo "        /      \\          the Makefile and headers"
    echo "       /"
}

# This function prints a help message when the user is outside a
# Weaver Directory
function weaver_help(){
        echo "    .  .     You are outside a Weaver Directory."
        echo "   .|  |.    The following command uses are available:"
        echo "   ||  ||"
        echo "   \\\\()//  weaver"
        echo "   .={}=.      Print this message and exits."
        echo "  / /\`'\\ \\"
        echo "  \` \\  / '  weaver PROJECT_NAME"
        echo "     \`'        Creates a new Weaver Directory with a new"
	echo "                project."
}

# This function creates a new "module", new  ".c" and ".h" files in the
# src/ directory whith the name passed as argument. The Makefiles and
# header files are also updated
function create_module(){
    if [ -a src/${1}.c ]; then
	echo "You already have source files with these names."
    else
	if ! [ -a /usr/share/weaver ]; then
	    WEAVER=${WEAVER}/src/
	fi
	# Project root address
        ADDR=$(echo $(pwd) | sed s/$(head -n 1 .web).*//)$(head -n 1 .web)
	# Project name
        PROJ=$(head -n 1 .web)
	# User name
	NAME=$(grep "^$(whoami):" /etc/passwd | cut -d : -f 5 | sed s/,.*//)
	# Current year
	YEAR=$(date +%Y)
	cd $ADDR
	# Creating the files
	sed s/DUMMY/${PROJ}/ ${WEAVER}/src/game.c | sed s/Copyright.*Astrizi/Copyright" (C) "${YEAR}\ "${NAME}"/ | head -n 18 > src/${1}.c
	echo "#include \"${1}.h\"" >> src/${1}.c
	echo >> src/${1}.h
	sed s/DUMMY/${PROJ}/ ${WEAVER}/src/game.h | sed s/Copyright.*Astrizi/Copyright\ \(C\)\ ${YEAR}\ "${NAME}"/ | sed s/_GAME_H_/_$(echo ${1} | tr [:lower:] [:upper:])_H_/ > src/${1}.h
	echo "#include \"game.h\"" >> src/${1}.h
	echo "" >> src/${1}.h
	echo "#endif" >> src/${1}.h

	# Updating header files
	sed s/\#define\ _GAME_H_/\#define\ _GAME_H_"\n"\#include\ \"${1}.h\"/ src/game.h > src/game.h~
	mv src/game.h~ src/game.h

	# Updating Makefiles
	sed s/PROG_OBJ=/PROG_OBJ=${1}.o\ / Makefile | sed s:PROG_HEAD=:PROG_HEAD=src/${1}.h\ : > Makefile~
        sed s/\#GAME_END/${1}.o:" src\/"${1}".c \${PROG_HEAD}\n\t\${CC} -c src\/"${1}".c\n"\#GAME_END/ Makefile~ > Makefile
        rm Makefile~
    fi
}

# This function updates a Weaver Directory putting the newest Weaver
# files there
function update_weaver(){
    YEAR=$(grep "Copyright (C) " $1/src/game.c | sed s/^" "*// | sed s/" "+/" "/ | cut -d ' ' -f 3)
    COUNT=$(( $(echo $YEAR | grep -o "," | wc -l | sed s/\ //g) + 1 ))
    if [ $(echo $YEAR | cut -d , -f $COUNT) != $(date +%Y) ]; then
	YEAR=${YEAR}","$(date +%Y)
    fi
    NAME=$(grep "Copyright (C) " $1/src/game.c | sed s/^" "*// | sed s/" "+/" "/ | cut -d ' ' -f 4-)
    PROJ=$(basename ${1})
    # Updating Weaver API
    cp -r ${WEAVER}/src/weaver $1/src 2> /dev/null

    # Updating year and copyright holder
    for i in $(ls $1/src/*.{c,h}); do
	file=$(basename $i)
	sed s/Copyright\ \(C\)\ .*$/Copyright\ \(C\)\ ${YEAR}\ "${NAME}"/ $1/src/$file > $1/src/${file}~
	mv $1/src/$file~ $1/src/$file
    done

    # Correcting some names in some source code files
    if ! [ -a /usr/share/weaver ]; then
      # If weaver is not installed, we check for the files in weaver's source dir
      sed s/DUMMY/${PROJ}/ ${WEAVER}/src/src/weaver/sound.c > $1/src/weaver/sound.c
      sed s/DUMMY/${PROJ}/ ${WEAVER}/src/src/weaver/image.c > $1/src/weaver/image.c
      sed s/DUMMY/${PROJ}/ ${WEAVER}/src/src/weaver/font.c > $1/src/weaver/font.c
    else
      # else, we check the normal location
      sed s/DUMMY/${PROJ}/ ${WEAVER}/src/weaver/sound.c > $1/src/weaver/sound.c
      sed s/DUMMY/${PROJ}/ ${WEAVER}/src/weaver/image.c > $1/src/weaver/image.c
      sed s/DUMMY/${PROJ}/ ${WEAVER}/src/weaver/font.c > $1/src/weaver/font.c
    fi
    echo "Project updated to Weaver version ${VERSION}."
}

# This function creates a new Weaver Project, whose name is passed as
# argument
function weaver_create(){
    mkdir $1
    if [[ ${WEAVER} == "/usr/share/weaver" ]]; then
	cp -r ${WEAVER}/{fonts,images,LICENSE,Makefile,music,sound,src} $1
    else
	mkdir $1/{fonts,images,music,sound}
	cp -r ${WEAVER}/src/{LICENSE,Makefile} $1
	cp -r ${WEAVER}/src/src $1
    fi
    # Creating a new Weaver project
    rm -f $1/reserved_words
    NAME=$(grep "^$(whoami):" /etc/passwd | cut -d : -f 5 | sed s/,.*//)
    YEAR=$(date +%Y)
    PROJ_NAME=$(basename $1)
    sed s/dummy/"${PROJ_NAME}"/ ${1}/Makefile > $1/Makefile~ &&
    mv $1/Makefile{~,} &&
    sed s/DUMMY/"${PROJ_NAME}"/ ${1}/src/game.c | sed s/Copyright.*Astrizi/Copyright\ \(C\)\ ${YEAR}\ "${NAME}"/ > $1/src/game.c~ &&
    mv $1/src/game.c{~,} &&
    sed s/DUMMY/"${PROJ_NAME}"/ ${1}/src/game.h | sed s/Copyright.*Astrizi/Copyright\ \(C\)\ ${YEAR}\ "${NAME}"/ > $1/src/game.h~ &&
    mv $1/src/game.h{~,} &&
    echo "#endif" >> $1/src/game.h &&
    sed s/DUMMY/"${PROJ_NAME}"/ ${1}/src/weaver/sound.c > $1/src/weaver/sound.c~ &&
    mv $1/src/weaver/sound.c{~,} &&
    sed s/DUMMY/"${PROJ_NAME}"/ ${1}/src/weaver/image.c > $1/src/weaver/image.c~ &&
    mv $1/src/weaver/image.c{~,} &&
    sed s/DUMMY/"${PROJ_NAME}"/ ${1}/src/weaver/font.c > $1/src/weaver/font.c~ &&
    mv $1/src/weaver/font.c{~,} &&
    echo $1 > $1/.web &&
    echo $1 > $1/src/.web &&
    echo $1 > $1/src/weaver/.web &&
    echo $1 > $1/images/.web &&
    echo $1 > $1/sound/.web &&
    echo $1 > $1/fonts/.web &&
    echo $1 > $1/music/.web
}

if [ -a .web ]; then
    if [ -z $1 ]; then
	# Calling weaver without arguments in a Weaver Directory
        clean_directory
    else
        if [[ $1 == "--help" ]]; then
	    # Using weaver --help in a Weaver Directory
	    weaver_directory_help
            exit
        else
	    if [ -e  "$1"/.web ]; then
		# Updating weaver version in the current project
		# If it's not the top level directory from a project, find the
		# top level directory and then update.
		if [ -e "$1"/../.web ]; then
		    ${0} "$1"/../
		else
		    update_weaver "$1"
		fi
	    else
	        # Calling weaver with arguments in a Weaver Directory
       		create_module $1
	    fi
        fi
    fi
else
    if [[  -z $1  ||  $1 == "--help" ]]; then
	# Called without arguments or with --help
	weaver_help
    elif [[ $1 == "--version" ]]; then
	# --version invoked
        echo "WEAVER -- Version ${VERSION}"
    elif grep "^[ ]*"$1"[ ]*$" ${WEAVER}/reserved_words &> /dev/null; then
        # Trying to create a project with a reserved name
	echo $1" is a reserved name. Please, give other name for the project."
    elif [ -e "$1"/.web ]; then
	# The project exists. Update it
	if [ -e "$1"/../.web ]; then
	    ${0} "$1"/../
	else
	    if [[ ${1:$((${#1}-1))} == "/" ]]; then
		update_weaver ${1:0:$((${#1}-1))}
	    else
		update_weaver $1
	    fi
	fi
    else
	weaver_create $1
    fi
fi
