#!/bin/bash

cvmfs_test_name="Path Traversal while Catalog Reloading"

reload_catalogs() {
  local loop_flag
  loop_flag=1
  trap "{ loop_flag=0; }" HUP

  while [ $loop_flag -eq 1 ]; do
    sudo cvmfs_config reload sft.cern.ch
    sleep 15
  done
}

cvmfs_run_test() {
  logfile=$1

  # process IDs of concurrent processes
  local find_cmd
  local reload_cmd

  # mount sft repository
  cvmfs_mount sft.cern.ch \
    "CVMFS_KCACHE_TIMEOUT=5" \
    "CVMFS_MAX_RETRIES=3" || return 1

  # decrease the kernel cache timeout to safe some time
  sudo cvmfs_config umount || return 4
  if running_on_osx; then
    cvmfs_mount_direct sft.cern.ch || return 5
  else
    sudo cvmfs_config probe  || return 5
  fi

  local find_stdout="$(pwd)/find_stdout.gz"
  local find_stderr="$(pwd)/find_stderr"

  # do a detached find call
  # (sudo because sometimes the permissions in the repo are scrambled)
  # TODO(jblomer): On Fedora23, this test works fine with the lcg subdirectory
  # but on the root directory it fails to list the remaining two regular files
  # in the root directory.  This remains to be solved!
  sudo find /cvmfs/sft.cern.ch/lcg -ignore_readdir_race 2> "$find_stderr" | gzip > "$find_stdout" &
  find_cmd=$!

  # reload the catalog every now and then
  reload_catalogs &
  reload_cmd=$!

  # always kill the detached processes
  trap "{ sudo kill -9 $find_cmd; kill -s HUP $reload_cmd; }" HUP INT TERM

  # wait for the find call to succeed
  wait $find_cmd
  local retval=$?

  # gracefully get rid of the catalog reload worker
  kill -s HUP $reload_cmd
  wait $reload_cmd

  # check if all went well
  if [ $retval -ne 0 ]; then
    echo "Find failed with return code: $retval"
    return 6
  fi

  rm -f "$find_stdout" "$find_stderr"

  return 0
}
