#!/bin/sh

# Vars {{{
readonly PROGNAME=$(basename "${0}")
readonly PROGDIR=$(readlink -m $(dirname "${0}"))
readonly ARGS="${*}"
readonly NBARGS="${#}"
[ -z "${DEBUG}" ] && DEBUG=0
## Export DEBUG for sub-script
export DEBUG

## Colors
readonly PURPLE='\033[1;35m'
readonly RED='\033[0;31m'
readonly RESET='\033[0m'
readonly COLOR_DEBUG="${PURPLE}"
# }}}
usage() {                                                       # {{{

	cat <<- EOF
usage: $PROGNAME

Try to open the given Youtube URL in embed mode in Browser

EXAMPLES :
    - Try with GhostBuster song
        ${PROGNAME} https://www.youtube.com/watch?v=_0SeGAi3II8

OPTIONS :
    -d,--debug
        Enable debug messages.

    -h,-help
        Print this help message.

    -u,-url
        Youtube URL to use.

EOF

}
# }}}
define_vars() {                                                 # {{{

	## Test if BROWSER is already defined (by parent script,…)
	[ -z "${BROWSER}" ] && BROWSER="qutebrowser"


	YOUTUBE_EMBED_URL_BASE="https://www.youtube.com/embed/"

	## ID is empty by default
	YOUTUBE_VIDEO_ID=""
}
# }}}
debug_message() {                                               # {{{

	local_debug_message="${1}"

	## Print message if DEBUG is enable (=0)
	[ "${DEBUG}" -eq "0" ] && printf '\e[1;35m%-6b\e[m\n' "DEBUG − ${PROGNAME} : ${local_debug_message}"

	return 0
}
# }}}
error_message() {                                               # {{{

	local_error_message="${1}"
	local_error_code="${2}"

	## Print message if DEBUG is enable (=0)
	[ "${DEBUG}" -eq "0" ] && printf '%b\n' "ERROR − ${PROGNAME} : ${RED}${local_error_message}${RESET}"

	exit "${local_error_code:=66}"
}
# }}}
is_youtube_url() {                                              # {{{

	local_youtube_url="${1}"
	## By default it's not a valid URL
	return_is_youtube_url="1"

	if printf -- '%s' "${local_youtube_url}" | grep --quiet --ignore-case --extended-regexp -- "youtube.com.*v="; then
		debug_message "is_youtube_url − \
The given argument seems to be a Youtube URL : ${local_youtube_url}."
		return_is_youtube_url="0"
	else
		debug_message "is_youtube_url − \
Verify that given URL really comes from Youtube with an ID (v=…) : ${local_youtube_url}."
	fi

	return "${return_is_youtube_url}"
}
# }}}
extract_video_id() {                                            # {{{

	local_youtube_url="${1}"
	## By default ID is not valid
	return_extract_video_id="1"

	local_youtube_video_id=$(printf -- '%s' "${local_youtube_url}" | sed -e 's;.*youtube.com.*v=\(.*\);\1;' -e 's;&.*;;')
	#local_youtube_video_id=""

	## If an ID was found
	if [ -n "${local_youtube_video_id}" ]; then
		debug_message "extract_video_id − \
successfully extract Youtube video ID : ${local_youtube_video_id}."
		YOUTUBE_VIDEO_ID="${local_youtube_video_id}"
		return_extract_video_id="0"
	else
		debug_message "extract_video_id − \
Error while extracting video ID (${local_youtube_video_id}), please check the URL."
	fi

	return "${return_extract_video_id}"
}
# }}}
open_in_browser() {                                             # {{{

	local_url="${1}"

	debug_message "open_in_browser − \
Try to open ${RED}${local_url}${COLOR_DEBUG} in ${BROWSER}."

	sh -c "${BROWSER} ${local_url}"
}
# }}}
main() {                                                        # {{{

	## Define all vars
	define_vars

	## Verify given argument
	is_youtube_url "${YOUTUBE_URL}" \
		|| exit 2

	## Try to extract the video ID
	extract_video_id "${YOUTUBE_URL}" \
		|| exit 3

	## Try to open embed version in browser
	open_in_browser "${YOUTUBE_EMBED_URL_BASE}${YOUTUBE_VIDEO_ID}"

}
# }}}

# Manage arguments                                                # {{{

## If there is argument(s)
if [ ! "${NBARGS}" -eq "0" ]; then

	## If the first argument is not an option
	if ! printf -- '%s' "${1}" | grep -q -E -- "^-+";
	then
		## Use this argument for Youtube URL
		YOUTUBE_URL="${1}"

		## Switch to the next argument
		shift
		manage_arg=$((manage_arg+1))
	fi

	manage_arg="0"

	# Parse all options (start with a "-") one by one
	while printf -- '%s' "${1}" | grep -q -E -- "^-+"; do

	case "${1}" in
		-d|--debug )           ## Enable debug mode
			## Enable DEBUG
			DEBUG="0"
			;;
		-h|--help )            ## help
			usage
			## Exit after help informations
			exit 0
			;;
		-u|--url )             ## URL
			## Move to the next argument
			shift
			## Set value to YOUTUBE_URL
			YOUTUBE_URL="${1}"
			;;
		* )                    ## unknow option
			printf '%b\n' "${RED}Invalid option: ${1}${RESET}"
			printf '%b\n' "---"
			usage
			exit 1
			;;
	esac

	debug_message "Arguments management − \
${RED}${1}${COLOR_DEBUG} option managed."

	## Move to the next argument
	shift
	manage_arg=$((manage_arg+1))

	done

	debug_message "Arguments management − \
${RED}${manage_arg}${COLOR_DEBUG} argument(s) successfully managed."
else
	usage
	error_message "Expect at least one argument (the Youtube URL)."
fi

# }}}

main

exit 255
