#!/usr/bin/env bash

MAINDIR=/opt/twitterbot_farm/
BOTS=${MAINDIR%/}_bots/
PYTHON="${PYTHON:-python2.7}"

set -eu

usage() {
	echo "Usage"
	echo "	init				- make farm possible to run"
	echo "	help				- show this help"
	echo "	start <bot>			- start bot"
	echo "	stop <bot>			- stop bot"
	echo "	list				- show list of bots"
	echo "	create <bot> <role> <db> <token> <secret> [<reader_db> <analyzer_db> <template>]"
	echo "					- create new reader/writer/analyzer bot"
	echo "	start-all			- start every bot"
	echo "	oneshot <bot>			- one tweet from bot"
	exit 1
}

init() {
	service redis restart
}

oneshot() {
	local bot="$1"
	local log="${2:-0}"
	export username="$bot"
	if [ "$log" = '0' ]; then
		$PYTHON $BOTS/$bot/bot.py &>>"/var/log/$bot.log"
	else
		$PYTHON $BOTS/$bot/bot.py
	fi
}

list() {
	ls $BOTS/ | xargs -L 1 echo
}

start() {
	local bot="$1"
	echo "starting: $bot"
	( cd $BOTS/$bot; ./run.sh )
}

create() {
	if [ "$#" -gt 4 ]; then
		tfctl.py ${FUNCNAME[0]} "$@"
		return
	fi
	set -xeu

	read name
	read role
	read db
	read token
	read secret

	if [ "$role" = 'writer' ]; then
		read reader_db
		read analyzer_db
		read template
		tfctl.py ${FUNCNAME[0]} $name $role $db $token $secret $reader_db $analyzer_db $template
		exit 0
	fi

	tfctl.py ${FUNCNAME[0]} $name $role $db $token $secret
}

start_all() {
	find $BOTS -maxdepth 1 -mindepth 1 -type d | xargs -L 1 start
}

stats() {
	tfctl.py stats
}

"${@:-usage}"
