#!/bin/bash
cvmfs_test_name="Use CernVM-FS Backend with Symlinked /var/spool/cvmfs"
cvmfs_test_autofs_on_startup=false

produce_files_in() {
  local working_dir=$1

  pushdir $working_dir

  cp_bin $working_dir

  popdir
}

desaster_cleanup() {
  sudo cvmfs_server rmfs -f $CVMFS_TEST_REPO
  if has_selinux; then
    sudo setenforce 1
  fi
}

cvmfs_run_test() {
  logfile=$1
  local repo_dir=/cvmfs/$CVMFS_TEST_REPO

  local scratch_dir=$(pwd)
  mkdir reference_dir
  local reference_dir=$scratch_dir/reference_dir

  local spool_dir="/var/spool/cvmfs/${CVMFS_TEST_REPO}"
  local spool_dir_destination="${scratch_dir}/spool/${CVMFS_TEST_REPO}"

  echo "remove previously created traces of $CVMFS_TEST_REPO if present"
  if has_repo $CVMFS_TEST_REPO; then
    destroy_repo $CVMFS_TEST_REPO || return 1
    sudo rm -fR $spool_dir && echo "removed '$spool_dir' as well"
  fi

  echo "create symlinked spooler directory for $CVMFS_TEST_REPO"
  mkdir -p $spool_dir_destination || return 2
  chown $CVMFS_TEST_USER:$CVMFS_TEST_USER $spool_dir_destination || { desaster_cleanup; return 3; }
  sudo ln --symbolic $spool_dir_destination $spool_dir || { desaster_cleanup; return 4; }
  sudo chown -h $CVMFS_TEST_USER:$CVMFS_TEST_USER $spool_dir || { desaster_cleanup; return 5; }

  # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

  # Required, e.g., on EL9
  if has_selinux; then
    sudo setenforce 0
  fi

  echo "create a fresh repository named $CVMFS_TEST_REPO with user $CVMFS_TEST_USER"
  create_empty_repo $CVMFS_TEST_REPO $CVMFS_TEST_USER || { desaster_cleanup; return 6; }

  # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

  echo "check that repository spooler is redirected"
  [ -f ${spool_dir_destination}/client.local ] || { desaster_cleanup; return 7; }
  [ -d ${spool_dir_destination}/cache ]        || { desaster_cleanup; return 8; }
  [ -d ${spool_dir_destination}/rdonly ]       || { desaster_cleanup; return 9; }

  # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

  echo "starting transaction to edit repository"
  start_transaction $CVMFS_TEST_REPO || { desaster_cleanup; return 10; }

  echo "putting some stuff in the new repository"
  produce_files_in $repo_dir || { desaster_cleanup; return 11; }

  echo "putting exactly the same stuff in the scratch space for comparison"
  produce_files_in $reference_dir || { desaster_cleanup; return 12; }

  echo "creating CVMFS snapshot"
  publish_repo $CVMFS_TEST_REPO || { desaster_cleanup; return 13; }

  echo "compare the results of cvmfs to our reference copy"
  compare_directories $repo_dir $reference_dir || { desaster_cleanup; return 14; }

  echo "check catalog and data integrity"
  check_repository $CVMFS_TEST_REPO -i || { desaster_cleanup; return 15; }

  echo "remove repository garbage"
  desaster_cleanup

  return 0
}

