#!/bin/bash
cvmfs_test_name="Swissknife filestats feature"
cvmfs_test_autofs_on_startup=false
cvmfs_test_suites="quick"

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

  echo "*** create a repository named $CVMFS_TEST_REPO with user $CVMFS_TEST_USER"
  create_empty_repo $CVMFS_TEST_REPO $CVMFS_TEST_USER NO -g || return 1
  disable_auto_garbage_collection $CVMFS_TEST_REPO || return 1
  check_repository $CVMFS_TEST_REPO -i  || return 1

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

  start_transaction $CVMFS_TEST_REPO || return $?
  echo "test file" > $repo_dir/testfile
  echo "test file" > $repo_dir/testfile2  # size 10
  echo "test file3" > $repo_dir/testfile3  # size 11
  publish_repo $CVMFS_TEST_REPO || return $?

  start_transaction $CVMFS_TEST_REPO || return $?
  echo "test file2" > $repo_dir/testfile  # size 11
  echo "test file" > $repo_dir/testfile4  # size 10
  publish_repo $CVMFS_TEST_REPO || return $?

  if [ x"$CVMFS_TEST_S3_CONFIG" != x"" ]; then
    repo_path=$(get_s3_repo_url "$CVMFS_TEST_REPO")
  else
    repo_path=/srv/cvmfs/$CVMFS_TEST_REPO
  fi

  cvmfs_swissknife filestats -r $repo_path -n $CVMFS_TEST_REPO -k /etc/cvmfs/keys -o filestats.db

  sqlite3 filestats.db "select count(*) from catalogs;"
  num_catalogs=$(sqlite3 filestats.db "select count(*) from catalogs;")
  [ $num_catalogs -eq 1 ] || return 2

  sqlite3 filestats.db "select count(*) from files;"
  num_files=$(sqlite3 filestats.db "select count(*) from files;")
  [ $num_files -eq 4 ] || return 3

  sqlite3 filestats.db "select count(*) from objects;"
  num_objects=$(sqlite3 filestats.db "select count(*) from objects;")
  [ $num_objects -eq 3 ] || return 4

  sqlite3 filestats.db "select size from objects;" | sort
  object_sizes=$(sqlite3 filestats.db "select size from objects;" | sort)
  object_sizes_formatted=$(echo $object_sizes)
  [ "x$object_sizes_formatted" == x"10 11 11" ] || return 5

  return 0
}
