#!/bin/bash
#
# Purpose: keep a set of nicks on ~freenode~ Libera active so they are not dropped in the random purges
#          or on request after (currently) 60 days
#
# Caveats: does not handle PING/PONG or timeouts
#
# Requires: bash (compiled with TCP support (so anything NOT Debian/Ubuntu pre-Karmic), timeout
#
# Autor:  Daniel Lange, http://daniel-lange.com/software/
# License: GPL v3 or later, http://www.gnu.org/licenses/
# Version: v0.1, 09-09-27, initial release
#          v0.2, 10-05-16, prepare for SSL use
#          v0.3, 19-10-26, remove ping test as this requires root these days :(
#          v0.4, 21-06-22, convert to Libera. Freenode is ... done.
#

IRC_HOST="irc.libera.chat"
#IRC_HOST="127.0.0.1"
IRC_PORT="6667"
#IRC_PORT="7070"

KEEPNICK_VERSION="v0.4"
KEEPNICK_MYNICK="KN$RANDOM"
KEEPNICK_SLEEP_INITIAL=10
KEEPNICK_SLEEP_NICKCHANGE=30

if [ "$1" = "-h" -o "$1" = "--help" ] ; then
 echo "$0 $KEEPNICK_VERSION (c) Daniel Lange, 2009-2022. Released under the GNU GPL v3 or later."
 echo "Usage: $0 <accountname> <password> <altnick1> <altnick2> ..."
 echo "       <accountname> - the name of the libera account to authenticate as (via nickserv)"
 echo "       <password>    - the nickserv password for the above accountname"
 echo "       <altnick1>    - an alternate linked nickname to nick to after identifying"
 echo "       <altnick2> ... <altnickN>   - further linked nicks to keep viewed as active"
 exit 0
fi

if [ "$#" -lt 2 ] ; then
 echo "Error: too few arguments, use -h for help"
 exit 1
fi

KEEPNICK_ACCOUNTNAME="$1"
if [ -z "$KEEPNICK_ACCOUNTNAME" ] ; then
 echo "Error: Accountname cannot be empty, use -h for help"
 exit 2
fi

shift

KEEPNICK_PASSWORD="$1"
if [ -z "$KEEPNICK_PASSWORD" ] ; then
 echo "Error: Password cannot be empty, use -h for help"
 exit 3
fi

shift


# ping -q -c 1 -w 10 -W 10 $IRC_HOST > /dev/null 2>&1

# if [ $? -ne 0 ] ; then
#  echo "Error: Could not ping $IRC_HOST (down, DNS error or ping missing)."
#  exit 4
# fi

if [ ! -x $(which timeout) ] ; then
        echo "Error: timeout not found. Exiting."
        exit 5
fi

exec 3<>/dev/tcp/$IRC_HOST/$IRC_PORT

echo -ne "USER $KEEPNICK_MYNICK 127.0.0.1 $IRC_HOST :Keepnick script $KEEPNICK_VERSION\r\n" >&3
echo -ne "NICK $KEEPNICK_MYNICK\r\n" >&3
echo -ne "NICKSERV IDENTIFY $KEEPNICK_ACCOUNTNAME $KEEPNICK_PASSWORD\r\n" >&3
timeout $KEEPNICK_SLEEP_INITIAL cat <&3
echo -ne "NICK $KEEPNICK_ACCOUNTNAME\r\n" >&3

while (( "$#" )); do
 timeout $KEEPNICK_SLEEP_NICKCHANGE cat <&3
 echo -ne "NICK $1\r\n" >&3
 shift
done

timeout $KEEPNICK_SLEEP_INITIAL cat <&3
exec 3<&-
