#!/bin/bash -e

if ! [ "$1" ]
then
   echo "usage: $0 <version>"
   exit 1
fi

if ! [ -d ".git" ]
then
   echo "Should be run inside a git repo dir."
   exit 1
fi

make clean || exit 1

if [ "$1" != "scm" ]
then

grep -q "\"$1\"" rockspec || {
   echo
   echo "version in rockspec is incorrect. Please fix it."
   exit 1
}

grep -q "program_version = \"$1\"" src/luarocks/core/cfg.lua || {
   echo
   echo "program_version in src/luarocks/core/cfg.lua is incorrect. Please fix it."
   exit 1
}

grep -q "version: $1\\." appveyor.yml || {
   echo
   echo "version in appveyor.yml is incorrect. Please fix it."
   exit 1
}

grep -q "LUAROCKS_VER: $1" appveyor.yml || {
   echo
   echo "LUAROCKS_VER in appveyor.yml is incorrect. Please fix it."
   exit 1
}

# e.g. if $1 is "2.3.0", $program_series is "2.3"
program_series=${1%.*}

grep -q "program_series = \"$program_series\"" src/luarocks/core/cfg.lua || {
   echo
   echo "program_series in src/luarocks/core/cfg.lua is incorrect. Please fix it."
   exit 1
}

grep -q "vars.VERSION = \"$program_series\"" install.bat || {
   echo
   echo "vars.VERSION in install.bat is incorrect. Please fix it."
   exit 1
}

fi

out="luarocks-$1"
rm -rf "$out"
mkdir "$out"
rm -f "missing_ref"
git ls-files | while read i
do
   if [ -f "$i" ]
   then
      dir=`dirname $i`
      mkdir -p "$out/$dir"
      cp "$i" "$out/$dir"
      if echo "$i" | grep -v "/bin/" | grep -q "^src/"
      then
         grep -qw `basename "$i"` Makefile.setup.inc || {
            echo "Missing ref in Makefile.setup.inc: $i"
            touch "missing_ref"
            exit 1
         }
      fi
   fi
done
if [ -e "missing_ref" ]
then
   rm -f "missing_ref"
   exit 1
fi

cat Makefile.setup.inc | tr ' \\' '\n\n' | grep 'lua$' | while read i
do
   if [ ! -e src/luarocks/$i ]
   then
      echo "Ref in Makefile.setup.inc for file that no longer exists: $i"
      touch "outdated_ref"
      exit 1
   fi
done
if [ -e "outdated_ref" ]
then
   rm -f "outdated_ref"
   exit 1
fi

rm -rf "release-unix" "release-windows" "$out.tar.gz" "$out-win32.zip"

mkdir "release-unix"
cp -a "$out" "release-unix"
mkdir "release-windows"
mv "$out" "release-windows/$out-win32"

cd "release-unix/$out"
rm -rf makedist install.bat COPYING_lua COPYING_7z COPYING_win win32 lfw .travis.yml .gitignore appveyor* .appveyor
cd ..
tar czvpf ../"$out.tar.gz" "$out"
cd ..
rm -rf "release-unix"

cd "release-windows/$out-win32"
rm -rf makedist Makefile* configure lfw .travis.yml .gitignore test appveyor* .appveyor
cd ..
zip -r ../"$out-win32.zip" "$out-win32"
cd ..
rm -rf "release-windows"