#!/bin/sh
set -eu

usage() {
	cat <<-'EOF'
	Usage:
	  commit-md [COMMIT]
	  commit-md -h
EOF
}

help() {
	cat <<-'EOF'

	Options:
	  -h, --help    show this message
EOF
}

for flag in "$@"; do
	case "$flag" in
		--)
			break
			;;
		--help)
			usage
			help
			exit
			;;
		*)
			;;
	esac
done

while getopts 'h' flag; do
	case "$flag" in
		h)
			usage
			help
			exit
			;;
		*)
			usage >&2
			exit 2
			;;
	esac
done
shift $((OPTIND - 1))

COMMIT="${1:-$(git rev-parse HEAD)}"
REPOSITORY="$(basename "$PWD")"

LINK="$(printf 'https://euandreh.xyz/%s.git/commit/?id=%s' "$REPOSITORY" "$COMMIT")"
# shellcheck disable=2016
MD="$(printf '[`%s`](%s)' "$COMMIT" "$LINK")"

xdg-open "$LINK"
printf '  Done in\n%s.' "$MD" | xclip -sel clip
printf 'Copied %s to the clipboard!\n' "$MD" >&2
