#!/usr/bin/env bash

BOLD="\033[1m"
CYAN="\033[1;36m"
GREEN="\033[1;33m"
END="\033[0m"

help() {
	cat <<EOF

ssh-serve-files

usage: ssh-serve-files [user@]hostname [-p port] [-d dir]

optional flags:
  -h, --help   show this help text
  -p, --port   port to tunnel and start http server at
  -d, --dir    directory of files to serve [default: ~/]
EOF
}

if [[ $# -eq 0 ]]; then
	echo "please provide [user@]hostname"
	help
	exit 1
fi

if [[ -z $BROWSER ]]; then
	echo 'please set $BROWSER'
	exit 1
fi

PORT=8090
DIR='~/'

USER_HOST=$1
case $USER_HOST in
-h | --help)
	help
	exit 0
	;;
*)
	shift
	;;
esac

while [[ $1 =~ ^- && $1 != "--" ]]; do
	case $1 in
	-p | --port)
		shift
		PORT=${PORT:+$1}
		;;
	-d | --dir)
		shift
		DIR=${DIR:+$1}
		;;
	-*)
		echo "Invalid option: $1"
		help
		exit 1
		;;
	esac
	shift
done

URL="http://localhost:$PORT"

printf "connecting to ${BOLD}%s${END} with port ${GREEN}%s${END}\n" \
	"$USER_HOST" "$PORT"
echo "serving directory:"
printf "  ${BOLD}->>${CYAN} %s${END}\n" "${DIR}"

printf "opening ${BOLD}%s${END} using %s\n" "$URL" "$BROWSER"
echo '---------------'
"$BROWSER" "$URL" >/dev/null 2>&1 &

# first change directory in case python<3.7
ssh -tL localhost:"$PORT":localhost:"$PORT" "$USER_HOST" \
	"cd $DIR && python3 -m http.server $PORT"