#!/bin/bash
# check the command line
if [ $# -lt 2 ] ; then
  echo "Missing release options and release message";
  echo "Usage: $(basename $0) [-Mmp] \"release message\""
  exit 1
fi

# change working directory
pushd ~/github.com/eyereasoner/eye > /dev/null

# the following is adapted from https://gist.github.com/codezninja/c227d9c65b09d2be2d99abbfcfa8774a
while getopts "Mmp" Option
do
  case $Option in
    M ) major=true;;
    m ) minor=true;;
    p ) patch=true;;
    * ) exit 1;;
  esac
done

# if a flag is missing, show usage message
if [ $OPTIND -eq 1 ]; then
  echo "No release options were passed: -M for major, -m for minor and -p for patch";
  echo "Usage: $(basename $0) [-Mmp] \"release message\""
  exit 1
fi

shift $(($OPTIND - 1))

version=$(cat VERSION)

# build array from version string
a=( ${version//./ } )

# increment version numbers as requested
if [ ! -z $major ]; then
  ((a[0]++))
  a[1]=0
  a[2]=0
fi

if [ ! -z $minor ]; then
  ((a[1]++))
  a[2]=0
fi

if [ ! -z $patch ]; then
  ((a[2]++))
fi

echo "${a[0]}.${a[1]}.${a[2]}" > VERSION

export RELEASE="v$(cat VERSION)"
export DATE="$(date -Idate)"

# update version in eye.pl and add release line in RELEASE
cat eye.pl | sed -e "s/'EYE.*'/'EYE $RELEASE \($DATE\)'/" > eye.pl.tmp
mv eye.pl.tmp eye.pl
sed -i '3 i\'"$RELEASE"' '\("$DATE"\)' '"$1"'' RELEASE

# install eye, run the tests and do git diff
sudo ./install.sh
./test
git diff

# create the distribution zip for https://sourceforge.net/projects/eulersharp/files/eulersharp/
mkdir -p /tmp/eye
cp -a eye.pl eye.sh eye.sh.in eye.cmd install.sh install.cmd INSTALL LICENSE RELEASE README.md VERSION /tmp/eye
pushd /tmp
zip -9ur eye.zip eye
popd
cp -a /tmp/eye.zip .

# git commands
git commit -a -m "$1"
git push
git tag -a -m "$1" $RELEASE
git push origin $RELEASE

# cleanup temporary files
rm /tmp/eye.zip
rm -fr /tmp/eye

popd > /dev/null
