#!/bin/bash
# `pip install mysqlclient` on macOS with the Oracle install of MySQL Community edition does not appear to work out of the box. This script attempts to fix it.
#
# No guarantees, mind you.
set -ue

if [ "$(which python)" != "$(pwd)/bin/python" ]
then
	echo "you probably want to source bin/activate first" >&2
	exit 1
fi

echo "Checking for mysql_config..."
if ! which mysql_config > /dev/null 2>&1
then
	PATH=$PATH:/usr/local/mysql/bin
fi

if ! mysql_config --version > /dev/null 2>&1
then
	echo mysql_config not found or failed >&2
	exit 1
fi

echo "Checking for existing mysqlclient version..."
VERSION=$(pip show mysqlclient | awk '/Version/{print "=="$2}' || "")
if echo $VERSION | grep -q =2
then
	export MYSQLCLIENT_CFLAGS=$(mysql_config --cflags)
	export MYSQLCLIENT_LDFLAGS=$(mysql_config --libs)
fi

echo "Installing mysqlclient${VERSION}..."
LDFLAGS="-rpath $(mysql_config --variable=pkglibdir)" pip install mysqlclient${VERSION} --force --no-cache-dir 2>&1 | sed -e 's/^/[pip] /'

echo "Finding .so file..."
MYSQLFILE=$(python -c '
import sys
try:
  import MySQLdb
except ImportError as e:
  print(e.path)
')

if [ "${MYSQLFILE}" != "" ]
then
	BARELIBS=$(otool -L $MYSQLFILE | awk '/^[ 	]*lib/{print $1}')
	for lib in $BARELIBS
	do
		echo "Patching $lib entry..."
		install_name_tool -change $lib '@rpath/'$lib $MYSQLFILE
	done
fi

# Validate
python -c 'import MySQLdb; print("Successfuly installed mysqlclient")'


