#!/bin/bash

######################################################################
#
#  Copyright (c) 2015 arakasi72 (https://github.com/arakasi72)
#
#  --> Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
#
######################################################################

PATH=/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/bin:/sbin

RTFILE=/usr/local/bin/rt

duoversion="0.13.2/0.9.2 0.13.3/0.9.3 0.13.4/0.9.4 0.13.5/0.9.5 0.13.6/0.9.6"
OSNAME=$(cat /etc/issue.net | cut -d' ' -f1)


installed() {
hash $1 2>/dev/null
}

ask_version() {
while [ -z "$verschoice" ]
do
  echo "Please select libtorrent/rtorrent version."
  select verschoice in ${duoversion[*]}
  do
    libvers=$(echo $verschoice | cut -d/ -f1)
    rtvers=$(echo $verschoice | cut -d/ -f2)
    break
  done
done
}

confirm_answer() {
while true
      do
      read -p "Sure you wish to install libtorrent-"$libvers" and rtorrent-"$rtvers"?" answer
      case $answer in [Yy]* ) return 0 ;;
                      [Nn]* ) exit ;;
                          * ) echo "Enter y or n";;
      esac
    done

}

if [ "$(id -u)" != "0" ]; then
  echo "Must be run as root, or with sudo"
  exit 1
fi

if ( installed rtorrent ); then
  rtorrent_current=$(rtorrent -h | grep -m 1 'version')
  rtorrent_current=${rtorrent_current#*version }
  echo "rtorrent $rtorrent_current detected"
  echo
else
  echo "rtorrent NOT installed"
  echo "This script is for upgrading/downgrading only, not for initial install"
  exit 1
fi

ask_version
confirm_answer

echo
echo "Installing $libvers/$rtvers"

cd $HOME

if [ -d source ]; then
  cd source
else
  mkdir source && cd source
fi
rm -r -f libtorrent* rtorrent*

echo "Fetching source files"
curl -# http://rtorrent.net/downloads/libtorrent-$libvers.tar.gz | tar xz
curl -# http://rtorrent.net/downloads/rtorrent-$rtvers.tar.gz | tar xz

echo "Compiling libtorrent"
cd $HOME/source/libtorrent-$libvers
./autogen.sh >> /dev/null 2>&1
if [ "$OSNAME" = "Raspbian" ]; then
    ./configure --prefix=/usr --disable-instrumentation >> /dev/null 2>&1
  else
    ./configure --prefix=/usr >> /dev/null 2>&1
fi
make -j2 >> /dev/null 2>&1
make install >> /dev/null 2>&1

echo "Compiling rtorrent"
cd $HOME/source/rtorrent-$rtvers
./autogen.sh >> /dev/null 2>&1
./configure --prefix=/usr --with-xmlrpc-c >> /dev/null 2>&1
make -j2 >> /dev/null 2>&1
make install >> /dev/null 2>&1
ldconfig

cd /var/www/rutorrent/conf/users
user_list=*

for user in $user_list
  do
    if [ ! "$user" = '*' ]; then
      echo "Restarting rtorrent for $user"
      su $user -c 'rt restart >> /dev/null 2>&1'
    fi
  done

cd $HOME

echo
echo "$libvers/$rtvers installed"
echo
echo "Your .rtorrent.rc file, and download, watch, and .session directories have not been altered in any way"
