#!/bin/sh
# 
# amulectl - Control amule from the command line
#
# (C) 2006 2007 Emanuele Rocca <ema@debian.org>
# Released under the terms of the Artistic License 2.0
#
# amulectl allows to use a remote amule instance, trying to output only
# relevant stuff and only if needed (search results, status).
#
# The script reads the hostname of the remote aMule instance and your
# aMule password from a remote.conf configuration file. An example
# follows.
#
# >--- snip here ---<
# [EC]
# Host=sluggy.home
# Port=4172
# Password=13425372D2142B83049790766BD6A528
# >--- snip here ---<

CONFFILE="/var/tmp/remote.conf"
if [ ! -f "$CONFFILE" ];then
    echo "ERROR: Configuration file missing."
    exit 1
fi

AMULECMD="/usr/bin/amulecmd -f $CONFFILE"
SCRIPTNAME="amulectl"

usage() {
    echo "Usage: $SCRIPTNAME command [option]
    show [ downloads | uploads | logs | results ]
    search filename
    download filenumber
    cancel hashnumber
    status
    fullstats
    console 
    help
    "

    exit 
}

exec_verbose() {
    $AMULECMD -c "$1"
}

exec_quiet() {
    $AMULECMD -c "$1" | grep ">" | sed s/"^[ |>]*"//
}

LANG=C

[ -z "$1" ] && usage 

command=$1
arg=$2

case "$command" in 
    help)
        usage
        ;;

    show)
        if [ "$arg" == "downloads" ];then
            cmd="Show DL" 
        elif [ "$arg" == "uploads" ];then
            cmd="Show UL"
        elif [ "$arg" == "logs" ];then
            cmd="Show Log"
        elif [ "$arg" == "results" ];then
            cmd="Results"
        else
            usage
        fi
        ;;

    search)
        # search keyword required
        [ -z "$arg" ] && usage
        exec_verbose "Search global $arg" > /dev/null 2>&1

        # waiting a few seconds
        sleep 5
        # calling again myself to show the search results
        $SCRIPTNAME show results

        exit 0
        ;;

    download)
        # file number required
        [ -z "$arg" ] && usage
        cmd="Download $arg"
        ;;

    cancel)
        # hash number required
        [ -z "$arg" ] && usage
        cmd="Cancel $arg"
        ;;

    status)
        cmd="Status"
        ;;

    fullstats)
        cmd="Statistics"
        ;;

    console)
        $AMULECMD
        ;;
    *)
        usage
        ;;
esac


case "$cmd" in 
    Results)
        # sort by # of sources (last column)
        exec_verbose "$cmd" | grep -E "^[0-9]" \
            | sed -r s/"([0-9]+$)"/"#\1"/ | sort -t "#" -k 2 -n -r
        ;;

    Download*)
        # to download a file we need to perform two operations:
        # 1) listing the search results
        # 2) actually starting the download of the requested file
        $AMULECMD > /dev/null <<EOF
results
$cmd
EOF
        ;;
    Cancel*)
        # warn the user if the cancelation fails
        err=`exec_quiet "$cmd" | grep "failed"`
        [ -n "$err" ] && echo $err
        ;;

    *)
        exec_quiet "$cmd"
        ;;
esac

exit 0
