#!/bin/bash
set -eu
THIS="$(realpath "$0")"
THISDIR="$(dirname "${THIS}")"
SRCDIR="$(dirname "${THISDIR}")"
SUT="${SRCDIR}/makeself.sh"

setUp() {
  temp="$(mktemp -dt datetest.XXXXX)"
  cd "${temp}"
  mkdir src
  echo "echo This is a test" > src/startup.sh
}

tearDown() {
  # Cleanup
  cd -
  rm -rf "${temp}"
}

# Default behaviour is to insert the current date in the
# generated file.
testCurrentDate() {
  ${SUT} src src.sh alabel startup.sh

  # Validate
  actual=`strings src.sh | grep packaging`

  expected=`LC_ALL=C date +"%b"`

  if [[ ${actual} == *${expected}* ]]
  then
    found=0
  else
    echo "Substring not found: ${expected} in ${actual}"
    found=1
  fi
  assertEquals 0 ${found}
}


# A fixed packaging date can be inserted
# into the generated package.  This way
# the package may be recreated from
# source and remain byte-for-bye 
# identical.
testDateSet() {
  expected='Sat Mar  5 19:35:21 EST 2016'

  # Exercise
  ${SUT} --packaging-date "${expected}" \
    src src.sh alabel startup.sh

  # Validate
  actual=`strings src.sh | grep "Date of packaging"`
  echo "actual="${actual}
  if [[ ${actual} == *${expected}* ]]
  then
    echo date set found
    found=0
  else
    echo "Substring not found: ${expected} in ${actual}"
    found=1
  fi
  assertEquals 0 ${found}
}


# Error if --packaging-date is passed as
# an argument but the date is missing
testPackagingDateNeedsParameter() {
  # Exercise
  ${SUT} --packaging-date  \
    src src.sh alabel startup.sh || true
  actual=`test -f src.sh`

  # Validate
  echo "actual="${actual}
  assertNotEquals 0 "${actual}"
}

# With the dates set we can get a byte for
# byte identical package.
testByteforbyte()
{
  date='Sat Mar  3 19:35:21 EST 2016'

  # bsdtar does not have option --mtime
  # TODO: unstable test: first second differ: char 242, line 10

  startSkipping

  # Exercise
  ${SUT} --packaging-date "${date}" --tar-extra "--mtime 20160303" \
    src src.sh alabel startup.sh
  mv src.sh first
  ${SUT} --packaging-date "${date}" --tar-extra "--mtime 20160303" \
    src src.sh alabel startup.sh
  mv src.sh second

  # Validate
  cmp first second

  assertEquals $? 0
}

# Load and run shUnit2.
source "./shunit2/shunit2"
