#!/bin/bash
# Copyright (c) 2020-2022:
#   Darren 'Tadgy' Austin <darren (at) afterdark.org.uk>
# Licensed under the terms of the GNU General Public License version 3.
#
# $1 == The rtorrent profile to start (eg. slackware-15.0).

DAEMON_EXEC="/usr/bin/daemon"
RTORRENT_EXEC="/opt/bin/rtorrent"
DAEMON_ARGS=('-N' '-n' "seeder-$1" '-r' '-a' '600' '-A' '5' '-L' '3600' '-M' '3' '-f' '--')
RTORRENT_ARGS=('-I' '-o' "import=$1/rtorrent.rc")
WORKINGDIR=""	# Default is: ~/seeds

source /etc/mail.conf "seeding" || exit 1

log() {
  printf "%(%Y/%m/%d %H:%M:%S)T: %s\n" "-1" "$*" >>~/rtorrent-wrapper.log
}

[[ -z "$1" ]] && {
  printf "%s: %s\\n" "$0" "missing profile name" >&2
  printf "  %s: %s\\n" "Usage" "$0 <profile>" >&2
  log "called with midding profile name"
  exit 1
}

for EXEC in "$DAEMON_EXEC" "$RTORRENT_EXEC"; do
  [[ ! -e "$EXEC" ]] && {
    printf "%s: %s: %s\\n" "$0" "$EXEC" "not found" >&2
    log "$EXEC not found"
    exit 1
  }
  [[ ! -x "$EXEC" ]] && {
    printf "%s: %s: %s\\n" "$0" "$EXEC" "not executable" >&2
    log "$EXEC not executable"
    exit 1
  }
done

"$DAEMON_EXEC" --list | grep "\<seeder-$1\>" >/dev/null && {
  printf "%s: %s: %s\\n" "$0" "profile already started" "$1" >&2
  log "profile already started: $1"
  exit 2
}

cd "${WORKINGDIR:-~/seeds}" || {
  printf "%s: %s: %s\\n" "$0" "failed to change to working directory" "${WORKINGDIR:-~/seeds}" >&2
  log "failed to change to working directory: ${WORKINGDIR:~/seeds}"
  exit 1
}

[[ ! -e "$1/rtorrent.rc" ]] && {
  printf "%s: %s: %s\\n" "$0" "configuration for profile does not exist" "$1/rtorrent.rc" >&2
  log "configuration for profile does not exist: $1/rtorrent.rc"
  exit 1
}

log "starting profile: $1"

# The call to daemon will only return if the process exits or fails to start.
"$DAEMON_EXEC" ${DAEMON_ARGS[*]} "$RTORRENT_EXEC" ${RTORRENT_ARGS[*]}
ERR=$?

(( ERR == 0 )) && exit 0

log "failed to start profile: $1 - Exit code: $ERR"
mailx "${MAILX_ARGS[@]}" -r "$EMAIL_FROM" -s "rtorrent seeding status" "${EMAIL_TO[@]}" <<EOF
The rtorrent instance '$1' has repeatidly failed to run for any length of time - please investigate!
Exit code: $ERR.
EOF

exit $ERR
