#!/bin/sh

# A bot to toot (post on the fediverse) a song, by chunks taken from a
# text file.  Stéphane Bortzmeyer <stephane+framagit@bortzmeyer.org>

# Requires madonctl <https://github.com/McKael/madonctl>

CONFIGDIR="$HOME/.config/madonctl"
MAXSLEEP=3600

songfile=$1
if [ -z "$songfile" ]; then
    echo "Usage: $0 song-file config-file" >&2
    exit 1
fi
if [ ! -e "$songfile" ]; then
    echo "$songfile does not exist" >&2
    exit 1
fi
# Configuration file can be generated with:
# madonctl config dump -i $YOURINSTANCE -L $YOURID -P $YOURPASSWORD > ~/.config/madonctl/$YOURCONFIG.yml 
configfile=$2
if [ -z "$configfile" ]; then
    echo "Usage: $0 song-file config-file" >&2
    exit 1
fi
if [ ! -e "$CONFIGDIR/${configfile}.yml" ]; then
    echo "${configfile}.yml does not exist in $CONFIGDIR" >&2
    exit 1
fi

userandom=0
useshuf=0
useunsort=0
if [ -z "$RANDOM" ]; then
    if which shuf > /dev/null 2>&1; then
	useshuf=1
    else
	if which unsort > /dev/null 2>&1; then
	    useunsort=1
	fi
    fi
else
    userandom=1
fi
if [ $userandom = 0 ] && [ $useshuf = 0 ] && [ $userunsort = 0 ]; then
    echo "Sorry, no way to choose at random on this machine with this shell. Use another shell, or install unsort or shuf" >&2
    exit 1
fi

checkpoint="cp-$configfile.dat"
if [ -e $checkpoint ]; then
    read previous < $checkpoint 
    chunk=`(read previous; read chunk; echo $chunk) < $checkpoint`
else
    previous=""
    chunk=1
fi

i=0
tosend=""
while read line; do
    if [ -z "$line" ]; then
	i=$(echo $i+1 | bc)
	if [ $i -ge $chunk ]; then
	    break
	else
	    tosend=""
	fi	
    else
	if [ -z "$tosend" ]; then
	    tosend=$line
	else
	    tosend="""$tosend
$line"""
	fi
    fi
done < $songfile

if [ ! -z "$tosend" ]; then
    if [ $userandom = 1 ]; then
	# We assume that if we have $RANDOM, we have also modulo and arithmetic
	sleep $(echo $RANDOM % $MAXSLEEP)
    else
	if [ $useshuf = 1 ]; then
	   sleep $(seq 1 $MAXSLEEP | shuf -r -n 1)
	else
	    if [ $useunsort = 1 ]; then
	       sleep $(seq 1 $MAXSLEEP | unsort -r | head -n 1)
	    else
		echo "Internal error, no way to sleep a random time" >&2
		exit 1
	    fi
	fi
    fi
    if [ -z "$previous" ]; then
	reference=""
    else
	reference="--in-reply-to $previous"
    fi
    next=$(madonctl --config ${CONFIGDIR}/${configfile}.yml toot --visibility public $reference "$tosend" | awk '/Status ID:/ {print $4}')
    # TODO we should check the status code (and that we got a "next").
    chunk=$(echo $chunk+1 | bc)
    echo $next > $checkpoint
    echo $chunk >> $checkpoint
else
    rm -f $checkpoint
fi

