#!/usr/bin/env bash
#
# This script tunnels to the bastion host

PORT=1080
PROFILE=twitch-cb-aws

# Make sure we can use the desired, local port.
if [ `lsof -i TCP:$PORT | grep LISTEN | wc -l` -gt "0" ]; then
    echo "Another program is using port $PORT"
    exit 1
fi

# Use relative files
cd "${BASH_SOURCE%/*}" || exit

function get_instance_id {
    aws ec2 describe-instances \
        --profile $PROFILE \
        --filter 'Name=tag:Name,Values=BastionHost' \
        --query "Reservations[].Instances[?State.Name == 'running'].InstanceId[]" \
        --output text
}

INSTANCE_ID=$(get_instance_id)

AWS_PROFILE=$PROFILE ssh -o ProxyCommand='./ssh-proxy %h %r %p ~/.ssh/id_rsa.pub' ec2-user@$INSTANCE_ID -D 127.0.0.1:1080
