#!/bin/bash

# MySQL Script Runner
# Usage: ./run_mysql_script.sh <DBurl> <DBuser> <DBpassword> <SQLscriptName>
# Example: ./run_mysql_script.sh localhost:3306 mydb myuser mypassword script.sql

# MySQL path - update this if your installation is different
MYSQL_PATH="/usr/local/mysql-8.0.30-macos12-x86_64/bin/mysql"

# Check if correct number of arguments are provided
if [ $# -ne 4 ]; then
    echo "Error: Incorrect number of arguments"
    echo "Usage: $0 <DBurl> <DBuser> <DBpassword> <SQLscriptName>"
    echo "Example: $0 localhost:3306 myuser mypassword script.sql"
    exit 1
fi

# Assign parameters to variables
DB_URL="$1"
DB_USER="$2"
DB_PASSWORD="$3"
SQL_SCRIPT="$4"

# Check if SQL script file exists
if [ ! -f "$SQL_SCRIPT" ]; then
    echo "Error: SQL script file '$SQL_SCRIPT' not found"
    exit 1
fi

# Check if mysql command is available at the specified path
if [ ! -f "$MYSQL_PATH" ]; then
    echo "Error: MySQL client not found at $MYSQL_PATH"
    echo "Please update the MYSQL_PATH variable in this script"
    exit 1
fi

echo ""
echo "DB data upload. Connecting to MySQL database..."
echo "URL: $DB_URL"
echo "User: $DB_USER"
echo "Script: $SQL_SCRIPT"
echo "MySQL Path: $MYSQL_PATH"

export MYSQL_PWD="$DB_PASSWORD"
# Execute the SQL script
"$MYSQL_PATH" -h "$(echo $DB_URL | cut -d: -f1)" \
      -P "$(echo $DB_URL | cut -d: -f2)" \
      -u "$DB_USER" \
      < "$SQL_SCRIPT"
unset MYSQL_PWD

# Check if the command was successful
if [ $? -eq 0 ]; then
    echo "SQL script executed successfully:"
    echo "MySQL DB DBFOsociology has been uploaded"
    echo ""
else
    echo "Error: Failed to execute SQL script"
    exit 1
fi 
