#!/bin/bash

VER_LIBTORRENT="0.12.5";
VER_RTORRENT="0.8.5";
VER_RTGUI="0.2.7";

echo "##################################################################"
echo "#           Installation automatisée de rtorrent/rtgui           #"
echo "#                                                                #"
echo "#               Yoann QUERET - yoann@queret.net                  #"
echo "#               http://www.queret.net/rtorrent/                  #"
echo "#                                                                #"
echo "#                                                                #"
echo "### ---------------------------------------------------------- ###"
echo "-> libtorrent ${VER_LIBTORRENT}"
echo "-> rtorrent ${VER_RTORRENT}"
echo "-> rtgui ${VER_RTGUI}"
echo "### ---------------------------------------------------------- ###"
echo "#               Appuyez sur <Entrer> pour continuer              #"
echo "##################################################################"
read

echo "##################################################################"
echo "#   == PRE-REQUIS SYSTEME ==                                     #"
echo "#     Ce script d'installation est prévu pour fonctionner sur    #"
echo "#     un Linux à base de Debian                                  #"
echo "#                                                                #"
echo "#   == PRE-REQUIS RESEAU ==                                      #"
echo "#     Votre serveur doit être connecté à internet, afin de       #"
echo "#     télécharger les paquets nécessaires.                       #"
echo "#                                                                #"
echo "#     Le fichier /etc/apt/sources.list doit être à jour          #"
echo "#                                                                #"
echo "### ---------------------------------------------------------- ###"
echo "#               Appuyez sur <Entrer> pour continuer              #"
echo "##################################################################"
read

echo "+----------------------------------------------------------------+"
echo "| Vérification que le script est bien exécuté depuis             |"
echo "| l'utilisateur root (uid 0)                                     |"
echo "+----------------------------------------------------------------+"
echo " Appuyez sur <Entrer> pour continuer"
read

if [ $UID != "0" ]; then
	echo " ERREUR : Ce script doit être lancé depuis l'utilisateur ROOT (UID 0)"
	echo " (Utilisez su ou sudo)"
	echo ""
	echo " L'installation ne peut continuer"
	exit
fi
echo " UID 0 trouvé, on peut continuer ..."


echo "+----------------------------------------------------------------+"
echo "| Test de votre système (Version de Linux)                       |"
echo "+----------------------------------------------------------------+"
echo " Appuyez sur <Entrer> pour continuer"
read

if [ ! -f /etc/debian_version ]; then
	echo " ERREUR : Ce script est prévu pour être utilisé sur une distribution basée sur Debian."
	echo " L'installation ne peut continuer"
	exit
fi

echo " Vous utilisez une distribution basée sur Debian. Nous pouvons lancer l'installation"
echo " Appuyer sur <Entrer> pour continuer"
read

clear
echo "##################################################################"
echo "# PART 1 - Installation de libtorrent                            #"
echo "### ---------------------------------------------------------- ###"
echo "#               Appuyez sur <Entrer> pour continuer              #"
echo "##################################################################"
read

echo "+----------------------------------------------------------------+"
echo "| Téléchargement des sources dans /tmp/                          |"
echo "+----------------------------------------------------------------+"
echo " Appuyez sur <Entrer> pour continuer"
read

wget http://libtorrent.rakshasa.no/downloads/libtorrent-${VER_LIBTORRENT}.tar.gz -O /tmp/libtorrent-${VER_LIBTORRENT}.tar.gz

echo "+----------------------------------------------------------------+"
echo "| Construction de l'environnement de compilation                 |"
echo "+----------------------------------------------------------------+"
echo " Appuyez sur <Entrer> pour continuer"
read
aptitude update
aptitude -y install make libcurl4-openssl-dev libsigc++-2.0-0c2a libsigc++-2.0-dev g++

echo "+----------------------------------------------------------------+"
echo "| Décompression des sources dans /usr/src/                       |"
echo "+----------------------------------------------------------------+"
echo " Appuyez sur <Entrer> pour continuer"
read
cd /usr/src/
tar zxvf /tmp/libtorrent-${VER_LIBTORRENT}.tar.gz

echo "+----------------------------------------------------------------+"
echo "| Compilation & Installation de libtorrent                       |"
echo "+----------------------------------------------------------------+"
echo " Appuyez sur <Entrer> pour continuer"
read
cd /usr/src/libtorrent-${VER_LIBTORRENT}
./configure
make
make install

echo "##################################################################"
echo "# PART 1 - Installation de libtorrent ---->> Finalisé !!         #"
echo "### ---------------------------------------------------------- ###"
echo "#               Appuyez sur <Entrer> pour continuer              #"
echo "##################################################################"
read

clear
echo "##################################################################"
echo "# PART 2 - Installation de rttorrent                             #"
echo "### ---------------------------------------------------------- ###"
echo "#               Appuyez sur <Entrer> pour continuer              #"
echo "##################################################################"
read

echo "+----------------------------------------------------------------+"
echo "| Téléchargement des sources dans /tmp/                          |"
echo "+----------------------------------------------------------------+"
echo " Appuyez sur <Entrer> pour continuer"
read

wget http://libtorrent.rakshasa.no/downloads/rtorrent-${VER_RTORRENT}.tar.gz -O /tmp/rtorrent-${VER_RTORRENT}.tar.gz

echo "+----------------------------------------------------------------+"
echo "| Construction de l'environnement de compilation                 |"
echo "+----------------------------------------------------------------+"
echo " Appuyez sur <Entrer> pour continuer"
read
aptitude -y install libncurses5-dev libxmlrpc-c3-dev screen

echo "+----------------------------------------------------------------+"
echo "| Décompression des sources dans /usr/src/                       |"
echo "+----------------------------------------------------------------+"
echo " Appuyez sur <Entrer> pour continuer"
read
cd /usr/src/
tar zxvf /tmp/rtorrent-${VER_RTORRENT}.tar.gz

echo "+----------------------------------------------------------------+"
echo "| Compilation de rtorrent                                        |"
echo "+----------------------------------------------------------------+"
echo " Appuyez sur <Entrer> pour continuer"
read
cd /usr/src/rtorrent-${VER_RTORRENT}
./configure --with-xmlrpc-c 
make
make install

echo "+----------------------------------------------------------------+"
echo "| Creation de l'utilisateur rtorrent                             |"
echo "+----------------------------------------------------------------+"
echo " Appuyez sur <Entrer> pour continuer"
read
useradd -m rtorrent

echo "+----------------------------------------------------------------+"
echo "| Creation des repertoires de travail de rtorrent                |"
echo "+----------------------------------------------------------------+"
echo " Appuyez sur <Entrer> pour continuer"
read

mkdir -p /data/torrent/downloading
mkdir -p /data/torrent/downloaded
mkdir -p /data/torrent/session
mkdir -p /data/torrent/watch

echo "+----------------------------------------------------------------+"
echo "| Configuration des droits sur les repertoires de rtorrent       |"
echo "+----------------------------------------------------------------+"
echo " Appuyez sur <Entrer> pour continuer"
read

chown rtorrent:www-data /data/torrent/ -R
chmod 775 /data/torrent -R

echo "+----------------------------------------------------------------+"
echo "| Creation du fichier de configuration de rtorrent               |"
echo "+----------------------------------------------------------------+"
echo " Appuyez sur <Entrer> pour continuer"
read

RTORRENTRC="/home/rtorrent/.rtorrent.rc"
echo '# SCGI port' >> ${RTORRENTRC}
echo 'scgi_port = 127.0.0.1:5000' >> ${RTORRENTRC}
echo '' >> ${RTORRENTRC}
echo '# Peer limits configuration' >> ${RTORRENTRC}
echo 'min_peers = 5' >> ${RTORRENTRC}
echo 'max_peers = 400' >> ${RTORRENTRC}
echo '' >> ${RTORRENTRC}
echo '# If not set same as download' >> ${RTORRENTRC}
echo '#min_peers_seed = 10' >> ${RTORRENTRC}
echo '#max_peers_seed = 50' >> ${RTORRENTRC}
echo '' >> ${RTORRENTRC}
echo '# Maximum number of simultanious uploads per torrent.' >> ${RTORRENTRC}
echo 'max_uploads = 15' >> ${RTORRENTRC}
echo '' >> ${RTORRENTRC}
echo '# Maximum global upload rate' >> ${RTORRENTRC}
echo 'upload_rate = 4000' >> ${RTORRENTRC}
echo '' >> ${RTORRENTRC}
echo '# Maximum global download rate' >> ${RTORRENTRC}
echo 'download_rate = 6000' >> ${RTORRENTRC}
echo '' >> ${RTORRENTRC}
echo '' >> ${RTORRENTRC}
echo '######################################################################' >> ${RTORRENTRC}
echo '# DIRECTORY' >> ${RTORRENTRC}
echo '######################################################################' >> ${RTORRENTRC}
echo '# Default directory to save the downloaded torrents.' >> ${RTORRENTRC}
echo 'directory = /data/torrent/downloading' >> ${RTORRENTRC}
echo '' >> ${RTORRENTRC}
echo '# Session directory' >> ${RTORRENTRC}
echo 'session = /data/torrent/session' >> ${RTORRENTRC}
echo '' >> ${RTORRENTRC}
echo '# Watch a directory for new torrents, and stop those that have been deleted.' >> ${RTORRENTRC}
echo 'schedule = watch_directory,15,15,load_start=/data/torrent/watch/*.torrent' >> ${RTORRENTRC}
echo '' >> ${RTORRENTRC}
echo '# Move downloaded files when download on finished' >> ${RTORRENTRC}
echo 'system.method.set_key = event.download.finished,move_complete,"execute=mv,-u,$d.get_base_path=,/data/torrent/downloaded/; d.set_directory=/data/torrent/downloaded/"' >> ${RTORRENTRC}
echo '' >> ${RTORRENTRC}
echo 'schedule = tied_directory,5,5,start_tied=' >> ${RTORRENTRC}
echo 'schedule = untied_directory,5,5,close_untied=' >> ${RTORRENTRC}
echo '' >> ${RTORRENTRC}
echo '######################################################################' >> ${RTORRENTRC}
echo '# CONFIGURATION' >> ${RTORRENTRC}
echo '######################################################################' >> ${RTORRENTRC}
echo '# Close torrents when diskspace is low.' >> ${RTORRENTRC}
echo 'schedule = low_diskspace,5,60,close_low_diskspace=900M' >> ${RTORRENTRC}
echo '' >> ${RTORRENTRC}
echo '# Enable the default ratio group.' >> ${RTORRENTRC}
echo '###ratio.enable=' >> ${RTORRENTRC}
echo '' >> ${RTORRENTRC}
echo '# Change the limits, the defaults should be sufficient.' >> ${RTORRENTRC}
echo '# (stop at ratio 4.0 with at least 200 MB uploaded, or else ratio 10.0)' >> ${RTORRENTRC}
echo '###ratio.min.set=400' >> ${RTORRENTRC}
echo '###ratio.max.set=1000' >> ${RTORRENTRC}
echo '###ratio.upload.set=1000M' >> ${RTORRENTRC}
echo '' >> ${RTORRENTRC}
echo '# Changing the command triggered when the ratio is reached.' >> ${RTORRENTRC}
echo 'system.method.set = group.seeding.ratio.command, d.close=, d.erase=' >> ${RTORRENTRC}
echo '' >> ${RTORRENTRC}
echo '# Port range for bittorrent' >> ${RTORRENTRC}
echo '#port_range = 49160-49299' >> ${RTORRENTRC}
echo 'port_range = 6890-6999' >> ${RTORRENTRC}
echo '' >> ${RTORRENTRC}
echo 'port_random = no' >> ${RTORRENTRC}
echo 'check_hash = yes' >> ${RTORRENTRC}
echo 'use_udp_trackers = yes' >> ${RTORRENTRC}
echo 'encryption = allow_incoming,try_outgoing,enable_retry' >> ${RTORRENTRC}
echo 'dht = auto' >> ${RTORRENTRC}
echo 'dht_port = 49300' >> ${RTORRENTRC}

echo "+----------------------------------------------------------------+"
echo "| Lancement de rtorrent au demarrage du serveur                  |"
echo "+----------------------------------------------------------------+"
echo " Appuyez sur <Entrer> pour continuer"
read
wget http://libtorrent.rakshasa.no/raw-attachment/wiki/RTorrentCommonTasks/rtorrentInit.sh -O /etc/init.d/rtorrent
chmod 775 /etc/init.d/rtorrent
sed -i "s/\(^user=*\)\(.*\)/\1\"rtorrent\"/" /etc/init.d/rtorrent
update-rc.d rtorrent defaults

/etc/init.d/rtorrent start

echo "##################################################################"
echo "# PART 2 - Installation de rtorrent ---->> Finalisé !!           #"
echo "### ---------------------------------------------------------- ###"
echo "#               Appuyez sur <Entrer> pour continuer              #"
echo "##################################################################"
read

clear
echo "##################################################################"
echo "# PART 3 - Installation de rtgui                                 #"
echo "### ---------------------------------------------------------- ###"
echo "#               Appuyez sur <Entrer> pour continuer              #"
echo "##################################################################"
read

echo "+----------------------------------------------------------------+"
echo "| Téléchargement des sources dans /tmp/                          |"
echo "+----------------------------------------------------------------+"
echo " Appuyez sur <Entrer> pour continuer"
read

wget http://rtgui.googlecode.com/files/rtgui-${VER_RTGUI}.tgz -O /tmp/rtgui-${VER_RTGUI}.tgz

echo "+----------------------------------------------------------------+"
echo "| Construction de l'environnement de compilation                 |"
echo "+----------------------------------------------------------------+"
echo " Appuyez sur <Entrer> pour continuer"
read
aptitude -y install php5 php5-xmlrpc libapache2-mod-scgi 

echo "+----------------------------------------------------------------+"
echo "| Décompression des sources dans /usr/src/                       |"
echo "+----------------------------------------------------------------+"
echo " Appuyez sur <Entrer> pour continuer"
read
cd /tmp/
tar zxvf /tmp/rtgui-${VER_RTGUI}.tgz

echo "+----------------------------------------------------------------+"
echo "| Installation & configuration de rtgui                          |"
echo "+----------------------------------------------------------------+"
echo " Appuyez sur <Entrer> pour continuer"
read
mv /tmp/rtgui/ /usr/share
mv /usr/share/rtgui/config.php.example /usr/share/rtgui/config.php

sed -i "s/\(\$watchdir=*\)\(.*\)/\1\"\/data\/torrent\/watch\/\";/" /usr/share/rtgui/config.php
sed -i "s/\(\$downloaddir=*\)\(.*\)/\1\"\/data\/torrent\/downloading\/\";/" /usr/share/rtgui/config.php

LOCAL_IP=`ifconfig eth0 | egrep -o '([0-9]{1,3}\.){3}[0-9]{1,3}' | egrep -v '255|(127\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})'`
sed -i "s/\(\$rtguiurl=*\)\(.*\)/\1\"\http:\/\/${LOCAL_IP}\/rtgui\/\";/" /usr/share/rtgui/config.php

RTGUIAPACHE="/etc/apache2/conf.d/rtgui.conf"
echo '# rtgui default Apache configuration' >> ${RTGUIAPACHE}
echo '' >> ${RTGUIAPACHE}
echo 'Alias /rtgui /usr/share/rtgui' >> ${RTGUIAPACHE}
echo '' >> ${RTGUIAPACHE}
echo '<Directory /usr/share/rtgui>' >> ${RTGUIAPACHE}
echo '        Options Indexes FollowSymLinks' >> ${RTGUIAPACHE}
echo '        DirectoryIndex index.php' >> ${RTGUIAPACHE}
echo '</Directory>' >> ${RTGUIAPACHE}

echo "+----------------------------------------------------------------+"
echo "| Configuration du mod scgi de apache                            |"
echo "+----------------------------------------------------------------+"
echo " Appuyez sur <Entrer> pour continuer"
read

sed -i "s/\(<\/VirtualHost>*\)\(.*\)//" /etc/apache2/sites-enabled/000-default
echo 'LoadModule scgi_module /usr/lib/apache2/modules/mod_scgi.so' >> /etc/apache2/sites-enabled/000-default
echo 'SCGIMount /RPC2 127.0.0.1:5000' >> /etc/apache2/sites-enabled/000-default
echo '</VirtualHost>' >> /etc/apache2/sites-enabled/000-default

echo "+----------------------------------------------------------------+"
echo "| Configuration du directory index de apache                     |"
echo "+----------------------------------------------------------------+"
echo " Appuyez sur <Entrer> pour continuer"
read
mkdir /var/www/indexoverride/

STYLE="/var/www/indexoverride/STYLE.css";
echo '' > ${STYLE}
echo 'body { padding:0; margin:0; background : #EEEEEE; font-family: Arial, Helvetica, sans-serif; font-size:12px; color : #494949; }' >> ${STYLE}
echo '#header, #content { border: 1px solid #AAAAAA; background: #FFFFFF; margin: 20px; padding: 5px; }' >> ${STYLE}
echo '#header #title { font-size: 24px; }' >> ${STYLE}
echo '#content hr { border:none; background:transparent; color : #f5f8fb; }' >> ${STYLE}
echo '#content img { background : #FFFFFF; padding-bottom:5px; padding-left:10px; border:0px solid #AAAAAA; padding-bottom:5px; }' >> ${STYLE}
echo 'A, A:link, A:active { font-size : 12px; color : #494949; }' >> ${STYLE}
echo 'A:visited { color : #B099AF; }' >> ${STYLE}
echo 'A:hover { color : #DAA520; }' >> ${STYLE}


HEADER="/var/www/indexoverride/HEADER.html";
echo '' > ${HEADER}
echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' >> ${HEADER}
echo '<html xmlns="http://www.w3.org/1999/xhtml">' >> ${HEADER}
echo '<head>' >> ${HEADER}
echo '<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />' >> ${HEADER}
echo '<title>StuFF</title>' >> ${HEADER}
echo '<link href="/indexoverride/STYLE.css" rel="stylesheet" type="text/css" />' >> ${HEADER}
echo '</head>' >> ${HEADER}
echo '<body>' >> ${HEADER}
echo '<div id="header">' >> ${HEADER}
echo '        <div id="title">SeedBox</div>' >> ${HEADER}
echo '        <div id="infos">' >> ${HEADER}
echo '        <p>Raccourci : <a href="/rtgui/">RTgui</a></p>' >> ${HEADER}
echo '        </div>' >> ${HEADER}
echo '</div>' >> ${HEADER}
echo '<div id="content">' >> ${HEADER}
echo '<pre>' >> ${HEADER}

FOOTER="/var/www/indexoverride/FOOTER.html";
echo '' > ${FOOTER}
echo '</pre></div></body></html>' > ${FOOTER}

HTACCESS="/var/www/.htaccess"
echo '' >> ${HTACCESS}
echo 'HeaderName /indexoverride/HEADER.html' >> ${HTACCESS}
echo 'ReadmeName /indexoverride/FOOTER.html' >> ${HTACCESS}
echo 'IndexIgnore .htaccess .htpasswd indexoverride' >> ${HTACCESS}
echo '' >> ${HTACCESS}
echo 'IndexOptions +FancyIndexing +FoldersFirst -SuppressLastModified +SuppressDescription +IconsAreLinks +NameWidth=*' >> ${HTACCESS}
echo '# +IconWidth=32 +IconHeight=32' >> ${HTACCESS}
echo 'IndexOrderDefault Ascending Name' >> ${HTACCESS}
echo 'DefaultIcon /indexoverride/default.png' >> ${HTACCESS}

rm /var/www/index.html
ln -s /data/torrent/downloaded/ /var/www/

echo "+----------------------------------------------------------------+"
echo "| Configuration de l'authentification apache                     |"
echo "+----------------------------------------------------------------+"
echo " Appuyez sur <Entrer> pour continuer"
read

sed -i "s/\(AllowOverride *\)\(.*\)/\1All/" /etc/apache2/sites-enabled/000-default

echo "Veuillez saisir un login et un mot de passe.";
echo "Ils vous permettront de vous connecter à l'interface WEB."
key=""
while [ "$key" == "" ];do
	read -p "Login : " key
done
login=$key

key=""
while [ "$key" == "" ];do
	read -p "Mot de passe : " key
done
passwd=$key

htpasswd -bc /var/www/.htpasswd $login $passwd

HTACCESS="/var/www/.htaccess"
echo '' >> ${HTACCESS}
echo 'AuthType basic' >> ${HTACCESS}
echo 'AuthUserFile /var/www/.htpasswd' >> ${HTACCESS}
echo 'AuthName "Private"' >> ${HTACCESS}
echo 'Require valid-user' >> ${HTACCESS}

/etc/init.d/apache2 restart

echo "##################################################################"
echo "# PART 3 - Installation de rtgui ---->> Finalisé !!              #"
echo "### ---------------------------------------------------------- ###"
echo "#               Appuyez sur <Entrer> pour continuer              #"
echo "##################################################################"
read

clear
echo "+----------------------------------------------------------------+"
echo "| L'installation est désormais terminée                          |"
echo "|                                                                |"
echo "| Pour lancer rtorrent vous devez utiliser la commande :         |"
echo "| # /etc/init.d/rtorrent start                                   |"
echo "|                                                                |"
echo "| Pour arreter rtorrent :                                        |"
echo "| # /etc/init.d/rtorrent stop                                    |"
echo "|                                                                |"
echo "|   ----------------------------------------------------------   |"
echo "| L'interface web est accessible à cette URL :"
echo "| -> http://${LOCAL_IP}"
echo "|      | login : ${login}"
echo "|      | password : ${passwd}"
echo "|   ----------------------------------------------------------   |"
echo "|                                                                |"
echo "+----------------------------------------------------------------+"

echo "+----------------------------------------------------------------+"
echo "| C'est fini !                                                   |"
echo "+----------------------------------------------------------------+"

