#!/usr/bin/env bash
#
# Creates a TinyURL from a long URL
#
# SPDX-License-Identifier: GPL-2.0-or-later
#
# SPDX-FileCopyrightText: 2007 Terence Simpson

SERVER=$1
TARGET=$2
export URL="$3"
NICK="$4"

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

if test ! -z $URL; then
  if test $(which curl); then
    TINYURL="$(curl -s -i https://tinyurl.com/api-create.php?url=$URL|tail -1)"
  else
    TINYURL="$(wget -T10 -t2 -qO- https://tinyurl.com/api-create.php?url=$URL|tail -1)"
  fi
else $_qdbus org.kde.konversation /irc error "No url given: usage is \"/tinyurl URL [NickName]\""
    exit 1
fi

if test -z $TINYURL; then
    $_qdbus org.kde.konversation /irc error "Unable run tinyurl script, please make sure you have curl or wget installed"
else
    if test ! -z $NICK; then
        $_qdbus org.kde.konversation /irc say $SERVER "$TARGET" "${NICK}: $TINYURL"
    else
        $_qdbus org.kde.konversation /irc say $SERVER "$TARGET" "$TINYURL"
    fi
fi
