#!/bin/sh
set -eu

usage() {
	cat <<-'EOF'
	Usage:
	  copy [-n] < STDIN
	  copy -h
EOF
}

help() {
	cat <<-'EOF'

	Options:
	  -n            remove newlines
	  -h, --help    show this message

	Examples:

	  Copy numbers to clipboard:
	    seq 10 | copy

	  Copy string without newline:
	    echo 'with automatic newline' | copy -n
EOF
}

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

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

if [ "$TRIM" = 'true' ]; then
	cat - | tr -d '\n' | xclip -sel clip
else
	cat - |              xclip -sel clip
fi
