version=$1

DIRNAME=`dirname "$0"`
if [ "$DIRNAME" = "." ]; then
  DIRNAME="$PWD"
fi

rm -rf "$DIRNAME/target"

mkdir -p "$DIRNAME/target/tomee/"

pushd "$DIRNAME" > /dev/null

for d in *; do
  bn=$(basename $d)
  if [ "$bn" = "catalina" ]; then
    bn="tomee-catalina"
  fi
  if [ -d "$d/src/main/config/patch" ]; then
    curl https://repo1.maven.org/maven2/org/apache/tomee/$bn/$version/$bn-$version-sources.jar > $DIRNAME/target/tomee/$bn-$version-sources.jar
    pushd "$d/src/main/config/patch" > /dev/null
    for f in *; do
      bn2=$(basename $f)
      fn=$(echo $bn2 | sed 's|\.|/|g').java
      pushd "../../java" > /dev/null
      if [ "$2" != "" ]; then
        cp $fn $fn.new
        jar xf $DIRNAME/target/tomee/$bn-$version-sources.jar $fn
        dos2unix $fn
        diff -u $fn $fn.new > ../config/patch/$f
        sed -i~ 's/^\(+++\|---\)\(.*\)\t[0-9]\+-[0-9]\+-[0-9]\+ [0-9]\+:[0-9]\+:[0-9]\+\.[0-9]\+ .[0-9]\+/\1\2\t2021-01-01 00:00:00.000000000 +0000/g' ../config/patch/$f
        rm ../config/patch/$f~
        rm $fn.new     
        git checkout HEAD -- $fn
      else
        cp $fn $fn.back
        jar xf $DIRNAME/target/tomee/$bn-$version-sources.jar $fn
        dos2unix $fn
        patch $fn ../config/patch/$f
        rm $fn.back
      fi
      popd > /dev/null
    done
    popd > /dev/null
  fi
done

popd > /dev/null

MAIN_VERSION=$(echo $version | cut -d. -f1)


curl https://archive.apache.org/dist/tomcat/tomcat-$MAIN_VERSION/v$version/bin/apache-tomcat-$version.zip > "$DIRNAME/target/tomcat/apache-tomcat-$version.zip"
mkdir -p "$DIRNAME/target/tomcat/apache-tomcat-$version"
pushd "$DIRNAME/target/tomcat" > /dev/null
unzip apache-tomcat-$version.zip
pushd apache-tomcat-$version > /dev/null


rm -rf bin lib logs temp
popd > /dev/null
popd > /dev/null

rm -rf "$DIRNAME/installer/src/main/resources/org/apache/tomcat/vestige/installer/conf"
mv "$DIRNAME/target/tomcat/apache-tomcat-$version/conf" "$DIRNAME/installer/src/main/resources/org/apache/tomcat/vestige/installer"
rm -rf "$DIRNAME/full_installer/src/main/resources/org/apache/tomcat/vestige/full_installer/webapps"
mv "$DIRNAME/target/tomcat/apache-tomcat-$version/webapps" "$DIRNAME/full_installer/src/main/resources/org/apache/tomcat/vestige/full_installer/"


find conf -type f > files.txt
popd

pushd "$DIRNAME/full_installer/src/main/resources/org/apache/tomcat/vestige/full_installer"
find webapps -type f > files.txt
popd

mvn versions:set -DnewVersion=$version.1-SNAPSHOT -DgenerateBackupPoms=false

sed -i~ 's/<tomee.version>.*<\/tomee.version>/<tomee.version>'${version}'<\/tomee.version>/' pom.xml
rm pom.xml~

sed -i~ 's/version: .*/version: '${version}'/' README.md
rm README.md~

