99 lines
2.4 KiB
Bash
Executable file
99 lines
2.4 KiB
Bash
Executable file
#!/usr/bin/env bash
|
|
|
|
[ -z $SQL_PROXY_HOST ] && SQL_PROXY_HOST="localhost"
|
|
CACHE_FILE="$HOME/.cache/sqlproxy_$SQL_PROXY_HOST"
|
|
|
|
HELP="Usage: myssh [ls|connect]
|
|
SUBCOMMANDS:
|
|
ls: list available database hosts
|
|
connect: connect to a database host
|
|
|
|
SYNTAX connect host [-u user] [-p password] [-c client]
|
|
"
|
|
|
|
ls() {
|
|
echo $(ssh $SQL_PROXY_HOST ls)
|
|
}
|
|
|
|
read_cache() {
|
|
if [ -f $CACHE_FILE ]
|
|
then
|
|
mapfile -t HOST_LIST < $CACHE_FILE
|
|
LAST_CHANGED=$(expr $(date +"%s") - "${HOST_LIST[0]}")
|
|
# Refresh cache if cache is older than a minute
|
|
if [ $LAST_CHANGED -gt 60 ]
|
|
then
|
|
write_cache $(ls)
|
|
read_cache
|
|
fi
|
|
else
|
|
write_cache $(ls)
|
|
read_cache
|
|
fi
|
|
}
|
|
|
|
write_cache() {
|
|
touch $CACHE_FILE
|
|
echo -e $(date +"%s")"\n"$1 > $CACHE_FILE
|
|
}
|
|
|
|
run_client() {
|
|
# wait for port to open
|
|
while ! nc -z localhost 3306 > /dev/null
|
|
do
|
|
sleep 0.1
|
|
done
|
|
|
|
if [ $(uname -s) = "Linux" ]
|
|
then
|
|
mysql --protocol=TCP -u $1 -p$2 -h localhost -P 3306
|
|
else
|
|
open "mysql://$1:$2@localhost:3306" -a "Sequel Ace"
|
|
fi
|
|
}
|
|
|
|
MAIN_OPTION=$1
|
|
shift
|
|
|
|
case $MAIN_OPTION in
|
|
ls)
|
|
RESPONSE=$(ls)
|
|
write_cache $RESPONSE
|
|
echo $RESPONSE;;
|
|
connect)
|
|
# Kill open connections on exit
|
|
# https://stackoverflow.com/questions/360201/how-do-i-kill-background-processes-jobs-when-my-shell-script-exits
|
|
trap "trap - SIGTERM && kill -- -$$" SIGINT SIGTERM EXIT
|
|
|
|
# check/update cache
|
|
read_cache
|
|
|
|
# check if host is valid
|
|
TARGET_HOST=$1
|
|
shift
|
|
tail -n +2 $CACHE_FILE | grep -qe "^$TARGET_HOST$"
|
|
GREP_EXIT_CODE=$?
|
|
if [ $GREP_EXIT_CODE -eq 0 ]
|
|
then
|
|
while getopts "u:p:" o
|
|
do
|
|
case "$o" in
|
|
u) MYSQL_USERNAME="$OPTARG" ;;
|
|
p) MYSQL_PASSWORD="$OPTARG" ;;
|
|
esac
|
|
done
|
|
ssh -L 3306:$TARGET_HOST:3306 $SQL_PROXY_HOST > /dev/null 2>&1 &
|
|
if [ ! -z $MYSQL_USERNAME ] && [ ! -z $MYSQL_PASSWORD ]
|
|
then
|
|
run_client $MYSQL_USERNAME $MYSQL_PASSWORD
|
|
else
|
|
echo 'Press CTRL C to quit this connection'
|
|
wait
|
|
fi
|
|
else
|
|
echo "Invalid Hostname: $2."
|
|
fi
|
|
;;
|
|
*)
|
|
echo -e "Usage: myssh [ls|connect]\n\n";;
|
|
esac
|