#!/bin/bash

ZIPFILE=$1
OLDVER=$2
VERSION=$3
CASE=$4

# Make sure the git repository is in good shape before messing with it.
[ -z "$(git status --porcelain)" ] || exit 127
../../../bin/setup-submodule src/ || exit 127
( cd src; git rev-parse --verify $VERSION >/dev/null 2>&1 ) && exit 126

cleanup() {
    # Run on script failure only
    if [ $? -ne 0 ]; then
        git clean -fd
        git submodule update src/
        ( cd src/; git checkout --detach )
        ( cd src/; git branch -D $VERSION )
    fi
}
[ "$CPADDON_AUTO_UPDATE" = 1 ] && trap 'cleanup' EXIT

# Use existing update scripts to setup most files.
../../../bin/update_src $ZIPFILE $OLDVER $VERSION && ../../../bin/package_src_update $OLDVER $VERSION || exit 1
./generate_mysql $ZIPFILE $VERSION || exit 2

# Create an upgrade script to automatically run Coppermine updates
# using built-in mechanisms.  But first, check to see that the
# mechanism is still likely to work.
UPDATE_FILE=src/update.php
[ -f $UPDATE_FILE ] || exit 3
grep -q "// define('SKIP_AUTHENTICATION', true);" $UPDATE_FILE || exit 4
grep -q "// If you don't remember the admin account data you're prompted for when running this file in your browser, umcomment the line above" $UPDATE_FILE || exit 5

# Actually create the script.
SCRIPT=upgrade/${OLDVER}_$VERSION/script
cat >"$SCRIPT" <<EOF
#!/usr/local/cpanel/3rdparty/bin/php
<?php
# Let the upgrader know that we are authorized
define('SKIP_AUTHENTICATION', true);

# Run the built-in Coppermine update script
include "update.php";
?>
EOF
chmod 755 "$SCRIPT"

# Update the ../Coppermine.pm file with a new version.
MODULE=../Coppermine.pm
sed -i "s/version *=> *'$OLDVER',/version => '$VERSION',/" $MODULE

# Increment the $VERSION
perl -MMath::BigFloat -pi -e 's/(?<=our \$VERSION = )([\d.]+)(?=;)/$f = Math::BigFloat->new($1); $f->badd(0.01)->precision(-2); "".$f/e' $MODULE

# Finally, tidy all of the changes to the module file.
perltidy -b $MODULE
rm -f $MODULE.bak

# Update the repository to the new version.
git rm $OLDVER.{mysql,tar.gz}
git add $VERSION.{mysql,tar.gz} keys_named_after_version/$VERSION upgrade/${OLDVER}_$VERSION/ src/ $MODULE
git commit -F - <<MSG
Updated Coppermine to v$VERSION

Case $CASE
MSG
