#!/bin/sh

# Author: Khalid Baheyeldin http://2bits.com
# Based on Artisan Numerique http://artisan.karma-lab.net/node/1240
#
# Modified 2018-Mar-26 for Drupal 6 LTS repo on Github

TMP="/tmp"

PROG=`basename $0`
if [ $# != 3 ]; then
  echo "Usage: $PROG old_version new_version drupal_directory"
  echo "Example: $PROG 7.15 7.32 /var/www"
  exit
fi

VER_OLD="$1"
VER_NEW="$2"
DRUPAL_DIR="$3"

MAJOR_OLD=`echo $VER_OLD | awk -F. '{print $1}'`
MAJOR_NEW=`echo $VER_NEW | awk -F. '{print $1}'`

if [ "$MAJOR_OLD" != "$MAJOR_NEW" ]; then
  echo "$PROG can only update minor versions"
  exit
fi

# Get the right URL for the repository, depending on version
# Drupal 6 LTS is hosted on github, D7 and D8 are on drupal.org
case "$VER_OLD" in
6.*) REPO="https://github.com/d6lts/drupal/archive"
     PREFIX=""
     ;;
*)   REPO="https://ftp.drupal.org/files/projects"
     PREFIX="drupal-"
     ;;
esac

# Convert . to a real directory, so cd works later
if [ "$DRUPAL_DIR" = '.' ]; then
  DRUPAL_DIR=`pwd`
fi

# If not a directory, then spit out an error
if [ ! -d "$DRUPAL_DIR" ]; then
  echo "Directory $DRUPAL_DIR does not exist ..."
  exit 1
fi

# Patch filename
PATCH_FILE=$TMP/patch-$VER_OLD-$VER_NEW.patch

# Change that to the directory where Drupal is installed
cd $TMP

# Cleanup the temp directory
rm -rf "drupal-*" "patch-*patch"

for VER in $VER_OLD $VER_NEW
do
  # Download the tar ball
  TAR_GZ=${PREFIX}${VER}.tar.gz

  wget -O $TAR_GZ --no-check-certificate $REPO/$TAR_GZ

  if [ ! -r $TAR_GZ ]; then
    echo "Could not download $TAR_GZ"
    exit
  fi

  # Extract it
  tar -xzf $TAR_GZ
  if [ $? != 0 ]; then
    echo "Could not extract $TAR_GZ"
    exit
  fi

done

# Now create the diff file
diff -Naur drupal-$VER_OLD drupal-$VER_NEW > $PATCH_FILE

# Now change to the directory where your Drupal installation is
cd $DRUPAL_DIR

# Check that the patch would apply without errors
patch -p1 --dry-run < $PATCH_FILE

# Assuming there are no error from the previous step, you can
echo "Please review the messages above, then answer the following question!"
# now apply the patch for real
echo "Do you want to proceed with the patch? (y/n) \c"
read ANS

case $ANS in
y) echo "Applying patch ..."
   patch -p1 -b < $PATCH_FILE
   ;;
*) echo "Patching cancelled ..."
   ;;
esac
