#!/bin/bash

# to run : ./deploy_mk.sh
# This will backup the current contents of /opt/MarketData/MarketData to /opt/MarketData/MarketData/MarketData_Rollback
# and deploy the mk binary to /opt/MarketData/MarketData
# 1) Stop the cron service
# 2) Wait for any running mk to complete
# 3) Perform the backup
# 4) Perform the deployment

# set xtrace if you want to see trace level
#set -o xtrace

sudo service cron stop
sudo service cron status

# The name of the MK process that we will need to ensure is not running during the deployment
PROCESS_NAME="mk" 

# Define source and destination directories
SOURCE_DIR="/home/pi/ARM64/MarketData/MarketData/bin/Debug/net8.0"
DEST_DIR="/opt/MarketData/MarketData"
ROLLBACK_DIR="/opt/MarketData/MarketData_Rollback"

# Find the PID of the process.  We take into account that multiple mk could be running at any given time
# -e: Select all processes
# -o pid,comm: Output only PID and command name
# grep -w: Match whole words for the process name
# awk '{print $1}': Extract the PID
check_process() 
{
PID=$(ps -e -o "pid,comm" | grep -w "$PROCESS_NAME" | grep -v grep | awk '{print $1}')

# Check if the process was found
echo "Check run status "
if ! [ -z "$PID" ]; then

# Split $PID on LineFeed and create PID_ARRAY
  my_string="$PID"
  delimiter="\n"
  temp_string="${my_string//$delimiter/ }"
  PID_ARRAY=($temp_string)

# Display what we found
  for item in "${PID_ARRAY[@]}"; do
   echo "Found (PID: $item)"
  done

# Wait for each process to end
  for item in "${PID_ARRAY[@]}"; do
    echo "Waiting for process '$PROCESS_NAME' (PID: $item) to end..."
    while ps -p "$item" > /dev/null; do
     sleep 5 # Wait for 5 seconds before checking again
    done
  done
  echo "Process '$PROCESS_NAME' has ended."
  return 1
else 
  echo "Process '$PROCESS_NAME' (PID: $PID) is not running."
  return 0
fi
}

# This will wait on all mk processes that are currently running.
# We keep executing the check_process command until we do not encounter
# any mk processes that may have started while we were waiting for others to complete.
until check_process; do
  echo "Waiting for process to end..."
  sleep 1
done

# Here begins the actual deployment process

# Check if source directory exists
if [ ! -d "$SOURCE_DIR" ]; then
  echo "Error: Source directory '$SOURCE_DIR' not found."
  sudo service cron restart
  exit 1
fi

# Check if destination directory exists, create if not
if [ ! -d "$DEST_DIR" ]; then
  echo "Destination directory '$DEST_DIR' not found. Creating it..."
  mkdir -p "$DEST_DIR"
fi

# Check if rollback directory exists, create if not
if [ ! -d "$ROLLBACK_DIR" ]; then
  echo "Rollback directory '$ROLLBACK_DIR' not found. Creating it..."
  mkdir -p "$ROLLBACK_DIR"
fi

# Clean the rollback folder
echo "Clean the rollback folder"
rm -rf $ROLLBACK_DIR/*
num_files=$(find "$ROLLBACK_DIR" -maxdepth 1 -type f | wc -l)
echo "Number of files after clean '$ROLLBACK_DIR': $num_files"
echo ""

# Backup current release
echo "Backup the current release"
cp -rv "$DEST_DIR"/* "$ROLLBACK_DIR"/
num_files=$(find "$ROLLBACK_DIR" -maxdepth 1 -type f | wc -l)
echo "Number of files after copy to backup '$ROLLBACK_DIR': $num_files"
echo ""

# Remove files
echo "Clean the deployment folder"
find "$DEST_DIR" -mindepth 1 -path "$DEST_DIR/logs" -prune -o -exec rm -rf {} +
num_files=$(find "$DEST_DIR" -maxdepth 1 -type f | wc -l)
echo "Number of files after clean '$DEST_DIR': $num_files"
echo ""

# Copy all files from source to destination
# The -v option provides verbose output (shows files being copied)
# The -r option is for recursive copy, useful if source_folder contains subdirectories
echo "Deploy the release candidate"
cp -rv "$SOURCE_DIR"/* "$DEST_DIR"/
num_files=$(find "$DEST_DIR" -maxdepth 1 -type f | wc -l)
echo "Number of files after deployment '$DEST_DIR': $num_files"
echo ""

echo "Files copied from '$SOURCE_DIR' to '$DEST_DIR'."

sudo service cron restart
sudo service cron status

echo "Done."

