#!/bin/bash

read -p "Enter the original MySql root password: " ORI_MYSQL_ROOT_PASSWORD

# Check if the original MySql root password is correct
if mysql -u root -p$ORI_MYSQL_ROOT_PASSWORD -e "exit"; then
    echo "The original MySQL root password is correct. Starting update new password!"
else
    echo "The original MySQL root password is incorrect. Please try again!"
    exit 1
fi

# Update the password for the relevant MySQL user
mysql -u root -p"$ORI_MYSQL_ROOT_PASSWORD" <<EOF
ALTER USER 'root'@'localhost' IDENTIFIED BY '$MYSQL_ROOT_PASSWORD';
ALTER USER 'root'@'%' IDENTIFIED BY '$MYSQL_ROOT_PASSWORD';
ALTER USER 'admin'@'%' IDENTIFIED BY '$ERPNEXT_PASSWORD';
ALTER USER 'erpnext'@'127.0.0.1' IDENTIFIED BY '$MYSQL_PASSWORD';
ALTER USER 'erpnext'@'localhost' IDENTIFIED BY '$MYSQL_PASSWORD';
FLUSH PRIVILEGES;
EOF

# Check if the password update was successful
if mysql -u root -p$MYSQL_ROOT_PASSWORD -e "exit"; then
    echo "Password update successful. Starting modify site config file"
else
    echo "Password update failed. Please check manually!"
    exit 1
fi

# Modify mysql erpnext password in configuration file
sed -i "s/\"db_password\": \".*\"/\"db_password\": \"${MYSQL_PASSWORD}\"/" /cloudclusters/erpnext/frappe-bench/sites/default/site_config.json

# Check if the configuration file update was successful
if grep -q ${MYSQL_PASSWORD} /cloudclusters/erpnext/frappe-bench/sites/default/site_config.json; then
     echo "Configuration file update successful!"
else
     echo "Configuration file update failed. Please check manually!"
     exit 1
fi

# Flush the cache
cd /cloudclusters/erpnext/frappe-bench/ && bench --site default clear-cache
