#!/bin/bash

usage() {
	echo "$0 command [args]"
	echo ""
	echo "Command in:"
	echo "-h|--help                    Usage"
	echo "-o|--ownuser  <username>      Set User Name"
	echo "-u|--username <username>      Set User Name"
	echo "-p|--password <password>      Set Password"
	echo "-sta|--start                  Start services"
	echo "-sto|--stop                   Stop services"
	echo ""
	exit
}

while [ $# -ne 0 ]; do
	case $1 in
		-o|--ownuser) 
	shift
			OWNUSER=$1
		;;
		-u|--username) 
	shift
			USERNAME=$1
		;;
		-p|--password) 
	shift
			PASSWORD=$1
		;;
		-sta|--start) 
	shift
			START=1
		;;
		-sto|--stop) 
	shift
                        STOP=1
		;;
		-h|-help|--help)
	usage
		;;
		*) 
			DEFAULTFILE=$1
			if [ ! -f "$DEFAULTFILE" ]; then
				echo "ERROR: Unknown option $DEFAULTFILE"
				usage
			fi
		;;
	esac
	shift
done

if [ $# == "" ] ; then
	echo "ERROR: Unknown option"
	usage
	exit 1
fi

if [ "$STOP" == 1 ] ; then
	killall -w aria2c
	exit 1
fi

if [ "$OWNUSER" == "" ] || [ "$USERNAME" == "" ] || [ "$PASSWORD" == "" ] || [ "$START" == "" ]; then
	echo "ERROR: MIssing Some Options"
	usage
	exit 1
fi

if [ "$OWNUSER" == "root" ]; then
	aria2c --enable-rpc --rpc-listen-all=true --rpc-allow-origin-all --rpc-listen-port=6800 --rpc-user=$USERNAME --rpc-passwd=$PASSWORD
	exit 1
fi

su -l $OWNUSER -c "aria2c --enable-rpc --rpc-listen-all=true --rpc-allow-origin-all --rpc-listen-port=6800 --rpc-user=$USERNAME --rpc-passwd=$PASSWORD"

exit 1
