#!/bin/bash

# Download additional components
#
# Usage:
#   repack.sh --upstream-version <ver>
#
# For example:
#   debian/repack.sh --upstream-version '3.1.13+dsfg.1'
#

set -e

if [ -z "$1" ] || [ -z "$2" ] ; then
    >&2 echo
    >&2 echo "Usage:"
    >&2 echo "  repack.sh --upstream-version <ver>"
    >&2 echo
    >&2 echo "For example:"
    >&2 echo "  debian/repack.sh --upstream-version '3.1.13+dsfg.1'"
    >&2 echo
    exit 1
fi

YELLOW='\033[0;33m'
RESET='\033[0m'

VER="$2"
SCRIPT_PATH=$(readlink -f "$0")
SCRIPT_DIR=$(dirname "$SCRIPT_PATH")
PACKAGE_DIR="$PWD"

PKG=$(dpkg-parsechangelog --show-field Source)

case "$VER" in
  3.1.13\+?*)
    UPSTEAM_COMMIT=45576ef6e62b5ff59da67f1697ee8c57809c7719 # branch 3.1-stable used to create tag 3.1.13
    ;;
  *)
    >&2 echo ""
    >&2 echo -e "${YELLOW}No upstream commit known for version '$VER'. Please set it in '$0'${RESET}."
    >&2 echo -e "Stopping here."
    exit 1
    ;;
esac

components_to_package=()
parent_dir=$(tar -tf ../"${PKG}_${VER}".orig.tar.* | head -n1)

for component in tests user_guide_src; do
  if ! tar -tf ../"${PKG}_${VER}".orig.tar.* | grep -q -c "${parent_dir}$component/"; then
    components_to_package+=("$component")
  fi
done

echo "Need to package these components: ${components_to_package[*]}"

echo "Getting latest upstream repository..."
if [ ! -d "$PACKAGE_DIR/../${PKG}_repack_repo" ]; then
  git clone https://github.com/bcit-ci/CodeIgniter.git "$PACKAGE_DIR/../${PKG}_repack_repo"
  cd "$PACKAGE_DIR/../${PKG}_repack_repo"
else
  cd "$PACKAGE_DIR/../${PKG}_repack_repo"
  git fetch --all --prune --tags
fi

echo "Moving to commit $UPSTEAM_COMMIT..."
git checkout "$UPSTEAM_COMMIT"

# remove rtd theme
if [ -d user_guide_src/source/_themes/ ]; then
  rm -r user_guide_src/source/_themes/
fi

create_orig_component() {
  # According to dpkg-source manpage, component can only contain alphanumeric ('a-zA-Z0-9')
  # characters and hyphens ('-'). With underscore ('_') it fails. So we can't use it.
  echo "Building orig.tar for component $component"
  filename="$PACKAGE_DIR/../${PKG}_${VER}.orig-${component}.tar.xz"
  if [ -f "$filename" ]; then rm "$filename"; fi
  tar -cJf "$filename" "$component"
  ls -sh "$filename"
}

append_to_orig_tar() {
  fakeroot tar -rvf "$PACKAGE_DIR/../${PKG}_${VER}.orig.tar" --transform "s|^|$parent_dir|" "$component"
}

for component in "${components_to_package[@]}"; do
  # We can't use "create_orig_component" with php-codeigniter-framework because user_guide_src contains underscore.
  # Use" append_to_orig_tar" instead

  #create_orig_component "$component"

  unxz "$PACKAGE_DIR/../${PKG}_${VER}.orig.tar.xz"
  append_to_orig_tar "$component"
  xz "$PACKAGE_DIR/../${PKG}_${VER}.orig.tar"
done
