#!/bin/bash
#
# Copyright 2022 Cohesity Inc.
#
# Author: Mahesh Kumar
#
# This script cleans up the older patches in the gold folder.
# After the completion, gold folder will have the last patch applied.
# This can be reverted. All the older patches would have been removed.
#
# Input Parameter: None
#

DATA_DIR="/home/cohesity/data"
PATCHES_DIR="${DATA_DIR}/patches"
GOLD_DIR="${PATCHES_DIR}/gold"

# This function should be called from patches folder.
# This changes to gold folder and returns in the patches folder.
function cleanup_service_patch() {
  local serv=$1
  local backup_file=$2
  local patch_file=$3
  if [ ! -d ${GOLD_DIR} ]; then
    return
  fi
  cd ${GOLD_DIR}
  patches=$(ls -1 ${serv}-* 2> /dev/null)
  if [ "$?" != "0" ]; then
    return
  fi

  for i in ${patches}
  do
    if [ "$i" = "${backup_file}" ]; then
      # echo "Skipping $i" >> /tmp/test_patch_log.txt
      continue
    fi
    if [[ ${i} =~ ${patch_file} ]]; then
      # echo "Skipping $i" >> /tmp/test_patch_log.txt
      continue
    fi
    # echo "Removing $i" >> /tmp/test_patch_log.txt
    rm -f $i
  done
}

#----------------------------------------------------------------------------
# Work starts here.
#
# Parameters are ignored.

cd ${PATCHES_DIR}
# Look for the reverse scripts and get the patch details from that.
revscripts=$(ls -1 revert_*_patch.sh 2> /dev/null)
if [ "$?" != "0" ]; then
  exit 0
fi

for revscr in ${revscripts}
do
  cd ${PATCHES_DIR}
  service=$(egrep '^COMPONENT=' ${revscr} | sed 's/COMPONENT=//')
  branch=$(egrep '^PATCH_NUM=' ${revscr} | sed 's/PATCH_NUM=//')
  cid=$(egrep '^PATCH_COMMIT_ID=' ${revscr} | sed 's/PATCH_COMMIT_ID=//')
  epoch=$(egrep '^PATCH_EPOCH=' ${revscr} | sed 's/PATCH_EPOCH=//')
  pdate=$(TZ=UTC date -d @${epoch} +"%Y%b%d")
  service_branch=${service}-${branch}
  patch_version=${pdate}-${cid}
  backup_file=${service_branch}-${cid}.tgz
  patch_file="${service_branch}-patch-.*-${cid}.tgz"
  cleanup_service_patch ${service} ${backup_file} ${patch_file}
done

exit 0
