#!/bin/bash

CM_DIR=$(dirname "$0")
ATM_DIR=$(dirname "$(dirname "$(readlink -f "$0")")")
FLAG_FILE="recipe_updated"

# Check if the flag file exists (indicating that previous changes were applied)
if [[ -f "$FLAG_FILE" ]]; then
	echo "`date +%H:%M:%S` Changes already applied. recipes.cfg is updated Skipping." >> $ATM_DIR/log/add/coffee.log
    exit 0
fi

echo "$CM_DIR"
echo "$ATM_DIR"

# Counting the number of non-commented lines in recipes.cfg
rows=$(grep -vE '^\s*//' recipes.cfg | grep -cE '^\S')
echo "`date +%H:%M:%S` Number of rows: $rows" >> $ATM_DIR/log/add/coffee.log

# Extracting and displaying unique values in the 7th column
prices=$(awk -F, '{gsub(/ /,"",$7); print $7}' recipes.cfg | sort -u)
echo "`date +%H:%M:%S` Unique prices in the 7th column: $prices" >> $ATM_DIR/log/add/coffee.log

# Check conditions and apply changes if necessary
if [[ "$rows" -eq 12 && $(echo "$prices" | wc -l) -eq 1 ]]; then
	echo "`date +%H:%M:%S` No changes required." >> $ATM_DIR/log/add/coffee.log
	echo "`date +%H:%M:%S` Rows: $rows" >> $ATM_DIR/log/add/coffee.log
    echo "`date +%H:%M:%S` Prices: $prices" >> $ATM_DIR/log/add/coffee.log
elif [[ "$rows" -eq 16 && $(echo "$prices" | wc -l) -gt 1 && $(echo "$prices" | grep -cE '200|300') -eq 2 ]]; then
    sed -i -E 's/^(([^,]*,){6}\s*)300(\s*,\s*)/\1400\3/' recipes.cfg
    sed -i -E 's/^(([^,]*,){6}\s*)200(\s*,\s*)/\1300\3/' recipes.cfg
	echo "`date +%H:%M:%S` Changes applied successfully. recipes.cfg prices changed from 200|300 to 300|400." >> $ATM_DIR/log/add/coffee.log
    touch "$FLAG_FILE"
	echo "`date +%H:%M:%S` Created flag file after successful changes." >> $ATM_DIR/log/add/coffee.log
	rm $CM_DIR/Data/cmcsysdata.db
	echo "`date +%H:%M:%S` cmcsysdata.db was deleted." >> $ATM_DIR/log/add/coffee.log
elif [[ "$rows" -eq 16 && $(echo "$prices" | wc -l) -gt 1 && $(echo "$prices" | grep -cE '300|400') -eq 2 ]]; then
    sed -i -E 's/^(([^,]*,){6}\s*)400(\s*,\s*)/\1500\3/' recipes.cfg
    sed -i -E 's/^(([^,]*,){6}\s*)300(\s*,\s*)/\1400\3/' recipes.cfg
	echo "`date +%H:%M:%S` Changes applied successfully. recipes.cfg prices changed from 300|400 to 400|500." >> $ATM_DIR/log/add/coffee.log
    touch "$FLAG_FILE"
	echo "`date +%H:%M:%S` Created flag file after successful changes." >> $ATM_DIR/log/add/coffee.log
	rm $CM_DIR/Data/cmcsysdata.db
	echo "`date +%H:%M:%S` cmcsysdata.db was deleted." >> $ATM_DIR/log/add/coffee.log
else
	echo "`date +%H:%M:%S` No changes required." >> $ATM_DIR/log/add/coffee.log
	echo "`date +%H:%M:%S` Rows: $rows" >> $ATM_DIR/log/add/coffee.log
	echo "`date +%H:%M:%S` Prices: $prices" >> $ATM_DIR/log/add/coffee.log
fi
