#!/bin/sh
#
# Copyright (C) 1999-2020 The ViewCVS Group. All Rights Reserved.
#
# By using this file, you agree to the terms and conditions set forth in
# the LICENSE.html file which can be found at the top level of the ViewVC
# distribution or at http://viewvc.org/license-1.html.
#
# For more information, visit http://viewvc.org/
#
# -----------------------------------------------------------------------
#
# make-release: internal tool for creating ViewVC releases
#
# -----------------------------------------------------------------------
#

### Validate input
if test $# != 2 && test $# != 1; then
  echo "Usage: $0 TARGET-DIRECTORY [VERSION]"
  echo ""
  echo "If VERSION (i.e. \"1.1.0\" or \"1.0.x\") is not provided,"
  echo "the release will be rolled from \"master\"."
  exit 1
fi

TARGET=${1}
if test $# = 1; then
  BRANCH=master
else
  BRANCH=${2}
fi

if test -e ${TARGET}; then
  echo "ERROR: must remove ${TARGET} first."
  exit 1
fi

### Grab an export from the GitHub repository.
TARBALL_URL="https://github.com/viewvc/viewvc/tarball/${BRANCH}"
for PLATFORM in unix windows; do
  echo "Beginning build for ${PLATFORM}:"

  echo "   Creating target directory..."
  mkdir ${TARGET}

  echo "   Exporting '${TARBALL_URL}' into '${TARGET}'..."
  (cd ${TARGET}; wget -q -O - "${TARBALL_URL}" | tar xz --strip-components=1)

  ### Various shifting, cleanup.  

  # Remove some not useful stuff.  We'll first try to read a
  # 'tools/release-ignores' file from the exported data for the list
  # of what to ignore.  Failing that, we'll use a hard-coded
  # historical list.
  JUNK_FILES=".gitignore notes tests tools misc elemx tparse"
  if [ -f "${TARBALL}/tools/release-ignores" ]; then
      echo "   Found release-specific ignorables file."
      JUNK_FILES=`cat "${TARBALL}/tools/release-ignores"`
  fi
  for JUNK in ${JUNK_FILES}; do
    if [ -d ${TARGET}/${JUNK} ]; then
      echo "   Removing directory ${TARGET}/${JUNK}..."
      rm -r ${TARGET}/${JUNK}
    elif [ -f ${TARGET}/${JUNK} ]; then
      echo "   Removing file ${TARGET}/${JUNK}..."
      rm ${TARGET}/${JUNK}
    else
      echo "   Skipping missing ${TARGET}/${JUNK}..."
    fi
  done

  # Make sure permissions are reasonable:
  echo "   Normalizing permissions..."
  find ${TARGET} -print | xargs chmod uoa+r
  find ${TARGET} -type d -print | xargs chmod uoa+x

  if test ${PLATFORM} = windows; then
    # Create also a ZIP file for those poor souls :-) still using Windows: 
    echo "   Creating ZIP archive..."
    zip -qor9 ${TARGET}.zip ${TARGET}
  else
    # Cut the tarball:
    echo "   Creating tarball archive..."
    tar cf - ${TARGET} | gzip -9 > ${TARGET}.tar.gz
  fi

  # Remove target directory
  echo "   Removing target directory..."
  rm -r ${TARGET}
done
echo "Done."
