#!/usr/bin/env bash

SERVER=$1
TARGET=$2

shift
shift

PERCENTAGE=$1

# special handling for qdbus variants
_qdbus=${KONVERSATION_DBUS_BIN:-qdbus-qt6}
if ! [ "$(which $_qdbus 2> /dev/null)" ]; then
    _qdbus=qdbus
    if ! [ "$(which $_qdbus 2> /dev/null)" ]; then
        echo "Error: The qdbus (or qdbus-qt6) utility is missing."
        exit 1
    fi
fi

if [ ! $TARGET ]
then
  $_qdbus org.kde.konversation /irc error "Can't write into status view."
else
  if [ ! $PERCENTAGE ]
  then
    $_qdbus org.kde.konversation /irc error "USAGE: $0 <percentage>"
  else
    PERCENTAGE=`echo $PERCENTAGE | sed 's/^0\+//'`
    LEFT=$(($PERCENTAGE/5))
    RIGHT=$((20-$LEFT))

    if [[ $PERCENTAGE -lt 0 ]]; then
      $_qdbus org.kde.konversation /irc error "Percentage has to be bigger than 0"
      exit
    fi
    
    if [[ $PERCENTAGE -gt 100 ]]; then
      $_qdbus org.kde.konversation /irc error "Percentage has to be smaller than 100"
      exit
    fi


    if [ $PERCENTAGE = 50 ]
    then
      METER="|"
    else
      if [[ $PERCENTAGE -lt 50 ]]
      then
        METER="\\"
      else
        METER="/"
      fi
    fi

    for (( i=$LEFT ; $i != 0 ; i-- ))
    do
      OUTPUT="$OUTPUT,"
    done

    OUTPUT="$OUTPUT$METER"

    for (( i=$RIGHT ; $i != 0 ; i-- ))
    do
      OUTPUT="$OUTPUT,"
    done

    OUTPUT=`echo $OUTPUT | sed 's/,/ /g'`
    
    OUTPUT="[$OUTPUT] $PERCENTAGE%"

    if [ $PERCENTAGE = 100 ]
    then
	OUTPUT="$OUTPUT *ding*"
    fi

    $_qdbus org.kde.konversation /irc say $SERVER "$TARGET" "Beer load $OUTPUT"
  fi
fi
