#!/bin/bash

cvmfs_test_name="404 on Root Catalog Download"
cvmfs_test_suites="quick"

do_faulty_mount() {
  cvmfs_mount "atlas.cern.ch"          \
              "CVMFS_TIMEOUT=3"        \
              "CVMFS_TIMEOUT_DIRECT=3" \
              "CVMFS_HTTP_PROXY=DIRECT"
}

cvmfs_run_test() {
  logfile=$1
  local scratch_dir=$(pwd)
  local http_pid
  local cmd
  local retval=0
  local stratum1="http://cvmfs-stratum-one.cern.ch/opt"

  echo -n "checking for wget... "
  which wget > /dev/null 2>&1 && echo "done" || { echo "not found"; return 1; }

  echo "restarting autofs"
  autofs_switch off || return 10
  autofs_switch on  || return 11

  echo "configure cvmfs with a host serving an empty directory"
  sudo sh -c "echo \"CVMFS_SERVER_URL=\\\"http://127.0.0.1:8000/@org@;$stratum1/@org@\\\"\" > /etc/cvmfs/domain.d/cern.ch.local" || return 1

  echo "create the empty directory to be served and add .cvmfspublished, .cvmfswhitelist and certificate to it"
  mkdir -p empty/atlas/data            || return 1
  cd empty/atlas                       || return 2
  wget $stratum1/atlas/.cvmfspublished || return 3
  wget $stratum1/atlas/.cvmfswhitelist || return 4
  for line in $(cat .cvmfspublished); do
    if [ $(echo $line | head -c1) = "X" ]; then
      local cert
      cert=$(echo $line | tail -c41)
      echo "found certificate $cert in .cvmfspublished. downloading..."
      mkdir -p data/$(echo $cert | head -c2) || return 5
      cd data/$(echo $cert | head -c2)       || return 6
      wget $stratum1/atlas/data/$(echo $cert | head -c2)/$(echo $cert | tail -c39)X || return 7
      cd ../.. || return 8
      break
    fi
  done
  cd ..

  echo "run a simple HTTP server"
  export PYTHON_VERSION=`python -c 'import sys; version=sys.version_info[:1]; print("{0}".format(*version))'`
   if [  $PYTHON_VERSION -gt 2  ]; then
     cmd="python -m http.server 8000"
   else
     cmd="python -m SimpleHTTPServer 8000"
   fi

  http_pid=$(run_background_service $logfile "$cmd")
  if [ $? -ne 0 ]; then return 9; fi
  echo "simple HTTP server serving empty directory started with PID $http_pid"

  echo "try to mount cvmfs"
  local milliseconds=$(stop_watch do_faulty_mount)

  echo "try to list the repository"
  ls /cvmfs/atlas.cern.ch || retval=10

  echo "killing simple HTTP server"
  sudo kill $http_pid || retval=11

  sudo rm -f /etc/cvmfs/domain.d/cern.ch.local || retval=12

  if running_on_osx; then 
    #expanding expected max timeout as we sleep for 3 seconds after a mount with FUSE-T
    local expected_max=20000
  else
    local expected_max=6000  
  fi

  if [ $milliseconds -gt $expected_max ]; then
    echo "mounting took too long with $milliseconds seconds (expected $expected_max)"
    CVMFS_TIME_WARNING_FLAG=1
  fi

  return $retval
}
