#!/bin/sh
#
# petname
#
# Copyright 2014 Dustin Kirkland <dustin.kirkland@gmail.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -e


error() {
	printf "ERROR: %s\n" "$@"
	exit 1
}

PKG=petname
DIR="/usr/share/$PKG"
WORDS=2
SEPARATOR="-"
while [ ! -z "$1" ]; do
	case "${1}" in
		-w|--words)
			WORDS="$2"
			shift 2
		;;
		-s|--separator)
			SEPARATOR="$2"
			shift 2
		;;
		-h|--help)
			exec man $PKG
		;;
		-d|--dir)
			DIR="$2"
			shift 2
		;;
		--adverb)
			ADVERB=1
			shift
		;;
		--adjective)
			ADJECTIVE=1
			shift
		;;
		--name)
			NAME=1
			shift
		;;
		*)
			error "Unknown options [$1]"
		;;
	esac
done

Adverb() {
	shuf -n 1 $DIR/adverbs.txt
}

Adjective() {
	shuf -n 1 $DIR/adjectives.txt
}

Name() {
	shuf -n 1 $DIR/names.txt
}

Generate() {
	if [ "$NAME" = "1" ]; then
		printf "%s\n" "$(Name)"
		return
	elif [ "$ADJECTIVE" = "1" ]; then
		printf "%s\n" "$(Adjective)"
		return
	elif [ "$ADVERB" = "1" ]; then
		printf "%s\n" "$(Adverb)"
		return
	elif [ "$WORDS" = "1" ]; then
		printf "%s\n" "$(Name)"
		return
	elif [ "$WORDS" = "2" ]; then
		adj="$(Adjective)"
		name="$(Name)"
		printf "%s%s%s\n" "$adj" "$SEPARATOR" "$name"
		return
	else
		count=$((WORDS-2))
		adverbs=
		for i in $(seq 1 $count); do
			if [ -z "$adverbs" ]; then
				adverbs=$(printf "%s%s" "$(Adverb)" "$SEPARATOR")
			else
				adverbs=$(printf "%s%s%s" "$adverbs" "$(Adverb)" "$SEPARATOR")
			fi
		done
		adj="$(Adjective)"
		name="$(Name)"
		printf "%s%s%s%s\n" "$adverbs" "$adj" "$SEPARATOR" "$name"
	fi
}

Generate
