Skip to content

Instantly share code, notes, and snippets.

@twonds
Created June 9, 2020 16:13
Show Gist options
  • Save twonds/547d4af7e8ade4e31af9316ae5964335 to your computer and use it in GitHub Desktop.
Save twonds/547d4af7e8ade4e31af9316ae5964335 to your computer and use it in GitHub Desktop.
A script to check ngrok and reset if necessary.
#!/usr/bin/env bash
#
#
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
set -xe
NGROK_DIR=${SCRIPT_DIR}/ngrok
mkdir -p $NGROK_DIR || true
NGROK_CONFIG=${NGROK_DIR}/ngrok.yml
which ngrok || brew install ngrok
which jq || brew install jq
PARAMS=""
while (( "$#" )); do
case "$1" in
-c|--config)
if [ -n "$2" ] && [ ${2:0:1} != "-" ]; then
NGROK_CONFIG=$2
shift 2
else
echo "Error: Argument for $1 is missing" >&2
exit 1
fi
;;
-*|--*=) # unsupported flags
echo "Error: Unsupported flag $1" >&2
exit 1
;;
*) # preserve positional arguments
PARAMS="$PARAMS $1"
shift
;;
esac
done
# set positional arguments in their proper place
eval set -- "$PARAMS"
function get_proxy_url() {
# Check ngrok's api for the alexa tunnel
# See: https://ngrok.com/docs#list-tunnels
echo $(curl -s http://localhost:4040/api/tunnels |jq '.tunnels[] | select(.name=="demo") | .public_url' -r || echo "")
}
# Use ngrok for the proxy to the laptop. https://ngrok.com/
#
# Run ngrok
#
proxy_url=$(get_proxy_url)
# If a ngrok proxy is running then check if it has an active session
if [ ! -z ${proxy_url} ]; then
proxy_status_code=$(curl -s -o /dev/null -I -w "%{http_code}" $proxy_url || echo 0)
if [ $proxy_status_code == 402 ]; then proxy_url=""; fi
fi
if [ -z ${proxy_url} ]; then
NGROK_PID=$(cat ${NGROK_DIR}/ngrok.pid || echo "")
if [ ! -z ${NGROK_PID} ]; then kill ${NGROK_PID} || true; fi
ngrok start alexa --config ${NGROK_CONFIG} >> ${NGROK_DIR}/ngrok.log 2>&1 &
echo $! > ${NGROK_DIR}/ngrok.pid
sleep 1
proxy_url=$(get_proxy_url)
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment