#!/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"

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
