#!/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
[ -d "$SNAP/share/$PKG" ] && DIR="$SNAP/share/$PKG" || DIR="/usr/share/$PKG"
WORDS=2
SEPARATOR="-"
LETTERS=99
COMPLEXITY=
UBUNTU=
while [ ! -z "$1" ]; do
	case "${1}" in
		-w|--words)
			WORDS="$2"
			shift 2
		;;
		-l|--letters)
			LETTERS="$2"
			shift 2
		;;
		-s|--separator)
			SEPARATOR="$2"
			shift 2
		;;
		-h|--help)
			exec man $PKG
		;;
		-d|--dir)
			DIR="$2"
			shift 2
		;;
		-c|--complexity)
			COMPLEXITY="$2"
			shift 2
		;;
		-u|--ubuntu)
			UBUNTU=$(cat $DIR/*.txt | shuf -n 1 | head -c 1)
			shift
		;;
		--adverb)
			ADVERB=1
			shift
		;;
		--adjective)
			ADJECTIVE=1
			shift
		;;
		--name)
			NAME=1
			shift
		;;
		*)
			error "Unknown options [$1]"
		;;
	esac
done

[ $LETTERS -lt 3 ] && LETTERS=3

case $COMPLEXITY in
	0)
		DIR="$DIR/small"
	;;
	1)
		DIR="$DIR/medium"
	;;
	2)
		DIR="$DIR/large"
	;;
	*)
		DIR="$DIR"
	;;
esac

Adverb() {
	grep "^$UBUNTU.\{0,$LETTERS\}$" $DIR/adverbs.txt | shuf -n 1
}

Adjective() {
	grep "^$UBUNTU.\{0,$LETTERS\}$" $DIR/adjectives.txt | shuf -n 1
}

Name() {
	grep "^$UBUNTU.\{0,$LETTERS\}$" $DIR/names.txt | shuf -n 1
}

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
		adj="$(Adjective)"
		name="$(Name)"
		count=$((WORDS-2))
		adverbs=
		for i in $(seq 1 $count); do
			adv="$(Adverb)"
			if [ -z "$adverbs" ]; then
				adverbs=$(printf "%s%s" "$adv" "$SEPARATOR")
			else
				adverbs=$(printf "%s%s%s" "$adverbs" "$adv" "$SEPARATOR")
			fi
		done
		printf "%s%s%s%s\n" "$adverbs" "$adj" "$SEPARATOR" "$name"
	fi
}

Generate
