#!/bin/bash

cvmfs_test_name="Garbage Collection Until Specified Timestamp With Named Snapshots"
cvmfs_test_autofs_on_startup=false

inflate_file() {
  local destination_file=$1
  local source_file=$2
  local desired_file_size=$3

  touch $destination_file
  while [ $(stat -c %s $destination_file) -lt $desired_file_size ]; do
    cat $source_file >> $destination_file
  done
}

produce_files_1_in() {
  local working_dir=$1
  pushdir $working_dir

  mkdir dir1
  mkdir dir1/sub1
  touch dir1/sub1/.cvmfscatalog
  mkdir dir1/sub2
  touch dir1/sub2/.cvmfscatalog
  mkdir dir1/sub3
  touch dir1/sub3/.cvmfscatalog

  touch dir1/shakespeare
  echo "That thou art blamed shall not be thy defect,"       >> dir1/shakespeare
  echo "For slander's mark was ever yet the fair;"           >> dir1/shakespeare
  echo "The ornament of beauty is suspect,"                  >> dir1/shakespeare
  echo "A crow that flies in heaven's sweetest air."         >> dir1/shakespeare
  echo "So thou be good, slander doth but approve"           >> dir1/shakespeare
  echo "Thy worth the greater, being wooed of time;"         >> dir1/shakespeare
  echo "For canker vice the sweetest buds doth love,"        >> dir1/shakespeare
  echo "And thou present'st a pure unstained prime."         >> dir1/shakespeare
  echo "Thou hast passed by the ambush of young days"        >> dir1/shakespeare
  echo "Either not assailed, or victor being charged;"       >> dir1/shakespeare
  echo "Yet this thy praise cannot be so thy praise,"        >> dir1/shakespeare
  echo "To tie up envy, evermore enlarged,"                  >> dir1/shakespeare
  echo "   If some suspect of ill masked not thy show,"      >> dir1/shakespeare
  echo "   Then thou alone kingdoms of hearts shouldst owe." >> dir1/shakespeare

  touch dir1/sub1/many_shakespeares
  touch dir1/sub2/alotof_shakespeares
  touch dir1/sub3/shakespeare_army
  inflate_file dir1/sub1/many_shakespeares dir1/shakespeare              1000000
  inflate_file dir1/sub2/alotof_shakespeares dir1/sub1/many_shakespeares 10000000
  inflate_file dir1/sub3/shakespeare_army dir1/sub2/alotof_shakespeares  50000000

  popdir
}

produce_files_2_in() {
  local working_dir=$1
  pushdir $working_dir

  mkdir dir2
  mkdir dir2/sub1
  touch dir2/sub1/.cvmfscatalog
  mkdir dir2/sub2
  touch dir2/sub2/.cvmfscatalog
  mkdir dir2/sub3
  touch dir2/sub3/.cvmfscatalog

  cp_bin dir2/sub1
  cp_bin dir2/sub2
  cp_bin dir2/sub3

  touch dir1/sub1/warfield
  echo "Our life is like a thorny rose"                                                   >> dir1/sub1/warfield
  echo "Not perfect, but always beautiful"                                                >> dir1/sub1/warfield
  echo "The thorns represent the hardships in our lives. "                                >> dir1/sub1/warfield
  echo "The delicate red petals represent the fun and beautiful things in our .........." >> dir1/sub1/warfield

  touch dir1/sub2/jackson
  echo "Didn't want a battle,"                                >> dir1/sub2/jackson
  echo "Yet you declared war,"                                >> dir1/sub2/jackson
  echo "Each knock you gave me made me stronger than before," >> dir1/sub2/jackson
  echo "I will not give up,"                                  >> dir1/sub2/jackson
  echo "I will not give in,"                                  >> dir1/sub2/jackson
  echo "You won't make me fall,"                              >> dir1/sub2/jackson
  echo "I won't let you win."                                 >> dir1/sub2/jackson

  popdir
}

produce_files_3_in() {
  local working_dir=$1
  pushdir $working_dir

  mkdir dir3
  cp_bin dir3

  mkdir dir3/sub1
  touch dir3/sub1/.cvmfscatalog
  mkdir dir3/sub2
  touch dir3/sub2/.cvmfscatalog
  mkdir dir3/sub3
  touch dir3/sub3/.cvmfscatalog

  touch dir3/kafka
  echo "Deeply lost in the night."                                   >> dir3/kafka
  echo ""                                                            >> dir3/kafka
  echo "Just as one sometimes lowers one's head to reflect, "        >> dir3/kafka
  echo "thus to be utterly lost in the night. "                      >> dir3/kafka
  echo "All around people are asleep. It's just play acting, "       >> dir3/kafka
  echo "an innocent self-deception, that they sleep in houses, "     >> dir3/kafka
  echo "in safe beds, under a safe roof, stretched out or "          >> dir3/kafka
  echo "curled up on mattresses, in sheets, under blankets; "        >> dir3/kafka
  echo "in reality they have flocked together as they had once "     >> dir3/kafka
  echo "upon a time and again later in a deserted region, a camp "   >> dir3/kafka
  echo "in the open, a countless number of men, an army, a people, " >> dir3/kafka
  echo "under a cold sky on cold earth, collapsed where once they "  >> dir3/kafka
  echo "had stood, forehead pressed on the arm, face to the "        >> dir3/kafka
  echo "ground, breathing quietly."                                  >> dir3/kafka
  echo ""                                                            >> dir3/kafka
  echo "And you are watching, are one of the watchmen, you find "    >> dir3/kafka
  echo "the next one by brandishing a burning stick from the "       >> dir3/kafka
  echo "brushwood pile beside you."                                  >> dir3/kafka
  echo ""                                                            >> dir3/kafka
  echo "Why are you watching?"                                       >> dir3/kafka
  echo ""                                                            >> dir3/kafka
  echo "Someone must watch, it is said. Someone must be there."      >> dir3/kafka

  touch dir3/sub1/many_kafkas
  touch dir3/sub2/alotof_kafkas
  touch dir3/sub3/kafka_army
  inflate_file dir3/sub1/many_kafkas dir3/kafka              1000000
  inflate_file dir3/sub2/alotof_kafkas dir3/sub1/many_kafkas 10000000
  inflate_file dir3/sub3/kafka_army dir3/sub2/alotof_kafkas  50000000

  rm -f dir2/sub1/*

  touch dir2/sub1/tharrington
  echo "Forever we remain oblivious to the future, "    >> dir2/sub1/tharrington
  echo "lost to the past and enduring our torture. "    >> dir2/sub1/tharrington
  echo "Forever we take chances to settle our scores, " >> dir2/sub1/tharrington
  echo "losing some battles and winning some wars. "    >> dir2/sub1/tharrington
  echo "Forever .........."                             >> dir2/sub1/tharrington

  rm -fR dir1

  popdir
}

produce_files_4_in() {
  local working_dir=$1
  pushdir $working_dir

  rm -fR dir3

  popdir
}

cvmfs_run_test() {
  local logfile=$1
  local script_location=$2
  local scratch_dir=$(pwd)
  local repo_dir=/cvmfs/$CVMFS_TEST_REPO

  mkdir reference_dir1
  mkdir reference_dir2
  mkdir reference_dir3
  mkdir reference_dir4
  local reference_dir1=$scratch_dir/reference_dir1
  local reference_dir2=$scratch_dir/reference_dir2
  local reference_dir3=$scratch_dir/reference_dir3
  local reference_dir4=$scratch_dir/reference_dir4

  local timestamp0=0
  local timestamp1=0
  local timestamp2=0
  local timestamp3=0
  local timestamp4=0
  local timestamp5=0
  local timestamp6=0

  local root_catalog0=""
  local root_catalog1=""
  local root_catalog2=""
  local root_catalog3=""
  local root_catalog4=""
  local root_catalog5=""

  local tag1="shakespeare"
  local tag2="warfield"
  local tag3="kafka"
  local tag4="delete_kafka"
  local tag5="dummy"

  timestamp0="$(get_timestamp)"
  echo "*** {0} create a fresh repository named $CVMFS_TEST_REPO with user $CVMFS_TEST_USER and disabled auto-tagging ($(display_timestamp $timestamp0))"
  create_empty_repo $CVMFS_TEST_REPO $CVMFS_TEST_USER NO -g -z || return $?
  root_catalog0="$(get_current_root_catalog $CVMFS_TEST_REPO)"

  echo "*** {0} disable automatic garbage collection"
  disable_auto_garbage_collection $CVMFS_TEST_REPO || return $?

  # ============================================================================

  echo "*** {1} starting transaction to edit repository (1)"
  start_transaction $CVMFS_TEST_REPO || return $?

  echo "*** {1} putting some stuff in the new repository"
  produce_files_1_in $repo_dir || return 1

  echo "*** {1} putting exactly the same stuff in the scratch spaces for comparison"
  produce_files_1_in $reference_dir1 || return 2

  timestamp1="$(get_timestamp)"
  echo "*** {1} creating CVMFS snapshot ($(display_timestamp $timestamp1))"
  publish_repo $CVMFS_TEST_REPO -a "$tag1" > publish_1.log 2>&1 || return $?
  root_catalog1="$(get_current_root_catalog $CVMFS_TEST_REPO)"

  echo "*** {1} compare the results of cvmfs to our reference copy"
  compare_directories $repo_dir $reference_dir1 || return $?

  # ============================================================================

  echo "*** {2} starting transaction to edit repository"
  start_transaction $CVMFS_TEST_REPO || return $?

  echo "*** {2} putting some stuff in the new repository"
  produce_files_2_in $repo_dir || return 3

  echo "*** {2} putting exactly the same stuff in the scratch spaces for comparison"
  produce_files_1_in $reference_dir2 || return 4
  produce_files_2_in $reference_dir2 || return 4

  timestamp2="$(get_timestamp)"
  echo "*** {2} creating CVMFS snapshot ($(display_timestamp $timestamp2))"
  publish_repo $CVMFS_TEST_REPO -a "$tag2" > publish_2.log 2>&1 || return $?
  root_catalog2="$(get_current_root_catalog $CVMFS_TEST_REPO)"

  echo "*** {2} compare the results of cvmfs to our reference copy"
  compare_directories $repo_dir $reference_dir2 || return $?

  # ============================================================================

  echo "*** {3} starting transaction to edit repository"
  start_transaction $CVMFS_TEST_REPO || return $?

  echo "*** {3} putting some stuff in the new repository"
  produce_files_3_in $repo_dir || return 5

  echo "*** {3} putting exactly the same stuff in the scratch spaces for comparison"
  produce_files_1_in $reference_dir3 || return 6
  produce_files_2_in $reference_dir3 || return 6
  produce_files_3_in $reference_dir3 || return 6

  timestamp3="$(get_timestamp)"
  echo "*** {3} creating CVMFS snapshot ($(display_timestamp $timestamp3))"
  publish_repo $CVMFS_TEST_REPO -a "$tag3" > publish_3.log 2>&1 || return $?
  root_catalog3="$(get_current_root_catalog $CVMFS_TEST_REPO)"

  echo "*** {3} compare the results of cvmfs to our reference copy"
  compare_directories $repo_dir $reference_dir3 || return $?

  # ============================================================================

  echo "*** {4} starting transaction to edit repository"
  start_transaction $CVMFS_TEST_REPO || return $?

  echo "*** {4} putting some stuff in the new repository"
  produce_files_4_in $repo_dir || return 7

  echo "*** {4} putting exactly the same stuff in the scratch spaces for comparison"
  produce_files_1_in $reference_dir4 || return 8
  produce_files_2_in $reference_dir4 || return 8
  produce_files_3_in $reference_dir4 || return 8
  produce_files_4_in $reference_dir4 || return 8

  timestamp4="$(get_timestamp)"
  echo "*** {4} creating CVMFS snapshot ($(display_timestamp $timestamp4))"
  publish_repo $CVMFS_TEST_REPO -a "$tag4" > publish_4.log 2>&1 || return $?
  root_catalog4="$(get_current_root_catalog $CVMFS_TEST_REPO)"

  echo "*** {4} compare the results of cvmfs to our reference copy"
  compare_directories $repo_dir $reference_dir4 || return $?

  # ============================================================================

  echo "*** {5} starting transaction to move up the undo tags"
  start_transaction $CVMFS_TEST_REPO || return $?

  timestamp5="$(get_timestamp)"
  echo "*** {5} creating CVMFS snapshot ($(display_timestamp $timestamp5))"
  publish_repo $CVMFS_TEST_REPO -a "$tag5" > publish_5.log 2>&1 || return $?
  root_catalog5="$(get_current_root_catalog $CVMFS_TEST_REPO)"

  # ============================================================================

  local shakespeare_object="5ccb03a6d732ff70310ba5db25756a6cd4675710"
  local chopped_shakespeare_1="f58287c6c5a608d70491519d4f3dc3b3436b607aP"
  local chopped_shakespeare_2="1e3618d857695eab0e30da35fcd9ea5e3f52f266P"
  local chopped_shakespeare_3="c3cc8c92d5ea75da3207498fae45123b8a172d21P"
  local kafka_object="fd8370662e701313534bfc2d2b860a7bf0fbf5da"
  local chopped_kafka_1="1d4964dc2146c16f2f351b153347890e2513a8eaP"
  local chopped_kafka_2="78d66a3880097d4b4bcd5145fea11498c4306ed0P"
  local chopped_kafka_3="ed021be42b51c299560b9617c6585a4c40607158P"

  echo "*** {6} check if poem objects are there ($shakespeare_object)..."
  peek_backend $CVMFS_TEST_REPO $shakespeare_object || return 9
  peek_backend $CVMFS_TEST_REPO $kafka_object       || return 9

  echo "*** {6} check if the file chunks are there"
  peek_backend $CVMFS_TEST_REPO $chopped_shakespeare_1 || return 9
  peek_backend $CVMFS_TEST_REPO $chopped_shakespeare_2 || return 9
  peek_backend $CVMFS_TEST_REPO $chopped_shakespeare_3 || return 9
  peek_backend $CVMFS_TEST_REPO $chopped_kafka_1       || return 9
  peek_backend $CVMFS_TEST_REPO $chopped_kafka_2       || return 9
  peek_backend $CVMFS_TEST_REPO $chopped_kafka_3       || return 9

  echo "*** {6} check if all catalog revisions are still there"
  for clg_hash in $root_catalog0 $root_catalog1 $root_catalog2 \
                  $root_catalog3 $root_catalog4 $root_catalog5; do
    peek_backend $CVMFS_TEST_REPO ${clg_hash}C || return 10
  done

  echo "*** {6} list the tags"
  cvmfs_server tag $CVMFS_TEST_REPO;

  # ============================================================================

  echo "*** {7} try some invalid date formats for garbage collection"
  cvmfs_server gc -f -t 'foo'            $CVMFS_TEST_REPO && return 11
  cvmfs_server gc -f -t 'in the morning' $CVMFS_TEST_REPO && return 12
  cvmfs_server gc -f -t 'later today'    $CVMFS_TEST_REPO && return 13
  cvmfs_server gc -f -t '13.12.'         $CVMFS_TEST_REPO && return 14

  # ============================================================================

  echo "*** {8} perform garbage collection with initial time stamp (nothing to be deleted)"
  cvmfs_server gc -l -f -t "$timestamp0" $CVMFS_TEST_REPO  || return 16

  echo "*** {8} check if poem objects are there ($shakespeare_object)..."
  peek_backend $CVMFS_TEST_REPO $shakespeare_object || return 17
  peek_backend $CVMFS_TEST_REPO $kafka_object       || return 17

  echo "*** {8} check if the file chunks are there"
  peek_backend $CVMFS_TEST_REPO $chopped_shakespeare_1 || return 18
  peek_backend $CVMFS_TEST_REPO $chopped_shakespeare_2 || return 18
  peek_backend $CVMFS_TEST_REPO $chopped_shakespeare_3 || return 18
  peek_backend $CVMFS_TEST_REPO $chopped_kafka_1       || return 18
  peek_backend $CVMFS_TEST_REPO $chopped_kafka_2       || return 18
  peek_backend $CVMFS_TEST_REPO $chopped_kafka_3       || return 18

  echo "*** {8} check if all catalog revisions are still there"
  for clg_hash in $root_catalog0 $root_catalog1 $root_catalog2 \
                  $root_catalog3 $root_catalog4 $root_catalog5; do
    peek_backend $CVMFS_TEST_REPO ${clg_hash}C || return 19
  done

  # ============================================================================

  echo "*** {9} perform garbage collection with timestamp and revision threshold (should fail)"
  cvmfs_server gc -l -f -t "$timestamp0" -r 2 $CVMFS_TEST_REPO && return 20

  # ============================================================================

  echo "*** {10} perform garbage collection to delete initial (mkfs) revisions"
  cvmfs_server gc -l -f -t "$timestamp2" $CVMFS_TEST_REPO || return 21

  echo "*** {10} check if the catalog revisions 2-6 are preserved"
  for clg_hash in $root_catalog1 $root_catalog2 \
                  $root_catalog3 $root_catalog4 $root_catalog5; do
    peek_backend $CVMFS_TEST_REPO ${clg_hash}C || return 22
  done

  echo "*** {10} check if the initial catalog is gone"
  for clg_hash in $root_catalog0; do
    peek_backend $CVMFS_TEST_REPO ${clg_hash}C && return 23
  done

  echo "*** {10} check repository integrity"
  check_repository $CVMFS_TEST_REPO -i || return 24

  # ============================================================================

  echo "*** {10} perform garbage collection to delete shakespeare revisions"
  echo "         (should not delete anything since it still has a tag)"
  cvmfs_server gc -l -f -t "$timestamp4" $CVMFS_TEST_REPO || return 25

  echo "*** {10} check if shakespeare is still there"
  peek_backend $CVMFS_TEST_REPO $shakespeare_object    || return 26
  peek_backend $CVMFS_TEST_REPO $chopped_shakespeare_1 || return 26
  peek_backend $CVMFS_TEST_REPO $chopped_shakespeare_2 || return 26
  peek_backend $CVMFS_TEST_REPO $chopped_shakespeare_3 || return 26

  echo "*** {10} check if kafka is still there"
  peek_backend $CVMFS_TEST_REPO $kafka_object    || return 27
  peek_backend $CVMFS_TEST_REPO $chopped_kafka_1 || return 27
  peek_backend $CVMFS_TEST_REPO $chopped_kafka_2 || return 27
  peek_backend $CVMFS_TEST_REPO $chopped_kafka_3 || return 27

  echo "*** {10} check if the catalog revisions 2-6 are preserved"
  for clg_hash in $root_catalog1 $root_catalog2 \
                  $root_catalog3 $root_catalog4 $root_catalog5; do
    peek_backend $CVMFS_TEST_REPO ${clg_hash}C || return 28
  done

  echo "*** {10} check repository integrity"
  check_repository $CVMFS_TEST_REPO -i || return 29

  # ============================================================================

  echo "*** {11} remove the tag that just guarded shakespeare from extinction"
  cvmfs_server tag -r $tag1 -r $tag2 -f $CVMFS_TEST_REPO || return 30

  echo "*** {11} list tags"
  cvmfs_server tag -l $CVMFS_TEST_REPO || return 30

  echo "*** {11} perform garbage collection again to delete shakespeare revisions"
  cvmfs_server gc -l -f -t "$timestamp4" $CVMFS_TEST_REPO || return 31

  echo "*** {11} check if shakespeare is gone"
  peek_backend $CVMFS_TEST_REPO $shakespeare_object    && return 32
  peek_backend $CVMFS_TEST_REPO $chopped_shakespeare_1 && return 32
  peek_backend $CVMFS_TEST_REPO $chopped_shakespeare_2 && return 32
  peek_backend $CVMFS_TEST_REPO $chopped_shakespeare_3 && return 32

  echo "*** {11} check if kafka is still there"
  peek_backend $CVMFS_TEST_REPO $kafka_object    || return 33
  peek_backend $CVMFS_TEST_REPO $chopped_kafka_1 || return 33
  peek_backend $CVMFS_TEST_REPO $chopped_kafka_2 || return 33
  peek_backend $CVMFS_TEST_REPO $chopped_kafka_3 || return 33

  echo "*** {11} check if the catalog revisions 4-6 are preserved"
  for clg_hash in $root_catalog3 $root_catalog4 $root_catalog5; do
    peek_backend $CVMFS_TEST_REPO ${clg_hash}C || return 34
  done

  echo "*** {11} check if the catalogs 1-3 are gone"
  for clg_hash in $root_catalog0 $root_catalog1 $root_catalog2; do
    peek_backend $CVMFS_TEST_REPO ${clg_hash}C && return 35
  done

  echo "*** {11} check repository integrity"
  check_repository $CVMFS_TEST_REPO -i || return 36

  # ============================================================================

  echo "*** {12} let the clock move forward"
  sleep 5
  timestamp6="$(get_timestamp)"

  echo "*** {12} rollback to the time where kafka was still among us ($(display_timestamp $timestamp6))"
  rollback_repo $CVMFS_TEST_REPO $tag3 || return 37

  echo "*** {12} list tags"
  cvmfs_server tag -l $CVMFS_TEST_REPO || return 38

  echo "*** {12} perform garbage collection to delete everything but HEAD"
  cvmfs_server gc -l -f -t "$timestamp6" $CVMFS_TEST_REPO || return 39

  echo "*** {12} check if shakespeare is gone"
  peek_backend $CVMFS_TEST_REPO $shakespeare_object    && return 40
  peek_backend $CVMFS_TEST_REPO $chopped_shakespeare_1 && return 40
  peek_backend $CVMFS_TEST_REPO $chopped_shakespeare_2 && return 40
  peek_backend $CVMFS_TEST_REPO $chopped_shakespeare_3 && return 40

  echo "*** {12} check if kafka is still there (we rolled back to it)"
  peek_backend $CVMFS_TEST_REPO $kafka_object    || return 41
  peek_backend $CVMFS_TEST_REPO $chopped_kafka_1 || return 41
  peek_backend $CVMFS_TEST_REPO $chopped_kafka_2 || return 41
  peek_backend $CVMFS_TEST_REPO $chopped_kafka_3 || return 41

  echo "*** {12} check if the catalogs 1-5 are gone"
  for clg_hash in $root_catalog0 $root_catalog1 $root_catalog2 \
                  $root_catalog3 $root_catalog4; do
    peek_backend $CVMFS_TEST_REPO ${clg_hash}C && return 42
  done

  return 0
}
