#!/bin/bash

#TODO : support "like=" to copy/renaming an existing class

PACKAGE=org.artisanlogiciel.games

TOOLP="$0 $*"

ctype=class
while [[ $# > 0 ]]
do
    case $1 in
	class|interface)
	    ctype=$1
	    ;;
	package=*)
	    PACKAGE=${1/package=/}
	    ;;
	package_dir=*)
	    PACKAGE_DIR=${1/package=/}
	    PACKAGE=${PACKAGE//\//\.}
	    ;;
	*)
	    CLASS=${1}
	    ;;
    esac
    shift 1
done

if [[ -z $CLASS ]]
then
    echo "[ERROR] Missing class" >&2
    exit 1
fi

PACKAGE_DIR=${PACKAGE//\./\/}

if [[ ! -d $PACKAGE_DIR ]]
then
    echo "Missing $PACKAGE_DIR" >&2
    exit 1
fi

JAVA_FILE=$PACKAGE_DIR/$CLASS.java
if [[ -e $JAVA_FILE ]]
then
    echo "[ERROR] $JAVA_FILE already exists" >&2
    exit 1
else

    if [[ $ctype == class ]]
    then
cat <<EOF >$JAVA_FILE
package $PACKAGE;

/**
 $CLASS was autogenerated by $TOOLP
 **/
public $ctype $CLASS
{
    Object param;

    $CLASS(Object param)
    {
       this.param=param;
    }

    void method()
    {
       System.out.println("Method of $PACKAGE.$CLASS");
    }

  public static void main(String args[]) {
    if ( args.length > 1 )
    {
      $CLASS instance=new $CLASS(args[1]);
      instance.method();
    }
    else 
    {
      System.err.println("Missing argument for $CLASS");
    }
  }
}
EOF
    else
cat <<EOF >$JAVA_FILE
package $PACKAGE;

/**
 $CLASS was autogenerated by $TOOLP
 **/
public $ctype $CLASS
{
    /**
       @return X
    */
    int getX();

    /**
       @return Y
    */
    int getY();
}
EOF
    fi
fi

echo "$JAVA_FILE generated"
