#!/bin/bash
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
#=================================================================#
#   System Required: Debian 9 X86_64                              #
#   Description: Download Tools For Debian 9 X86_64 Install       #
#   Author: LALA <QQ1062951199>                                   #
#   Website: https://www.lala.im                                  #
#=================================================================#

clear
echo
echo "#############################################################"
echo "# Download Tools For Debian 9 X86_64 Install                #"
echo "# Author: LALA <QQ1062951199>                               #"
echo "# Website: https://www.lala.im                              #"
echo "# System Required: Debian 9 X86_64                          #"
echo "#############################################################"
echo

# Color
red='\033[0;31m'
green='\033[0;32m'
yellow='\033[0;33m'
font="\033[0m"

Aria2_install(){
# HostIP input
read -p "请输入你的服务器公网IP地址:" HostIP

# Aria2RPCPassword Setting
read -p "请设置Aria2RPC密码:" RPCPasswd

# CPUcore input
read -p "选择使用多少个CPU线程编译Aria2（多个线程将有效提升编译效率）:" CPUcore

# Create Swap
read -p "如果机器内存小于2GB需临时创建Swap,是否创建Swap?（yes/no）:" Choose
if [ $Choose = "yes" ];then
    dd if=/dev/zero of=/var/swap bs=1024 count=2097152
    mkswap /var/swap
    chmod 0600 /var/swap
    swapon /var/swap
fi
if [ $Choose = "no" ]
then
    echo -e "${yellow} 你选择不创建swap,脚本将立即开始安装Aria2 ${font}"
fi

# Update System
apt -y update
apt -y dist-upgrade
if [ $? -eq 0 ];then
    echo -e "${green} 系统更新完成 ${font}"
else 
    echo -e "${red} 系统更新失败 ${font}"
    exit 1
fi

# Install Nginx1.14
echo "deb http://nginx.org/packages/debian/ stretch nginx" >> /etc/apt/sources.list
echo "deb-src http://nginx.org/packages/debian/ stretch nginx" >> /etc/apt/sources.list
wget http://nginx.org/keys/nginx_signing.key
apt-key add nginx_signing.key
apt -y update
apt -y install nginx
if [ $? -eq 0 ];then
    echo -e "${green} Nginx安装完成 ${font}"
else 
    echo -e "${red} Nginx安装失败 ${font}"
    exit 1
fi

# Install PHP7.0
apt -y install php7.0 php7.0-cli php7.0-common php7.0-curl php7.0-fpm php7.0-gd php7.0-mysql php7.0-opcache php7.0-xml php7.0-xmlrpc php7.0-sqlite3 php7.0-mbstring
if [ $? -eq 0 ];then
    echo -e "${green} PHP7安装完成 ${font}"
else 
    echo -e "${red} PHP7安装失败 ${font}"
    exit 1
fi
systemctl start php7.0-fpm
systemctl enable php7.0-fpm
if [ $? -eq 0 ];then
    echo -e "${green} PHP-FPM启动成功 ${font}"
else 
    echo -e "${red} PHP-FPM启动失败 ${font}"
    exit 1
fi

# Install Build Tools and UNZIP WGET
apt -y install build-essential unzip wget
if [ $? -eq 0 ];then
    echo -e "${green} 编译工具安装成功 ${font}"
else 
    echo -e "${red} 编译工具安装失败 ${font}"
    exit 1
fi

# Install Build Package
apt -y install libssl-dev libssh2-1-dev libc-ares-dev libexpat1-dev zlib1g-dev libsqlite3-dev pkg-config
if [ $? -eq 0 ];then
    echo -e "${green} 编译Aria2所需依赖安装成功 ${font}"
else 
    echo -e "${red} 编译Aria2所需依赖安装失败 ${font}"
    exit 1
fi

# Compile and install Aria2
cd
wget --no-check-certificate https://github.com/aria2/aria2/releases/download/release-1.34.0/aria2-1.34.0.tar.gz
if [ $? -eq 0 ];then
    echo -e "${green} Aria2源码下载成功 ${font}"
else 
    echo -e "${red} Aria2源码下载失败 ${font}"
    exit 1
fi
tar -xzvf aria2-1.34.0.tar.gz
cd aria2-1.34.0
cd src
rm -rf bignum.h
wget https://raw.githubusercontent.com/aria2/aria2/master/src/bignum.h
cd ..
./configure --prefix=/usr
make -j${CPUcore}
make install
if [ $? -eq 0 ];then
    echo -e "${green} Aria2安装成功 ${font}"
else 
    echo -e "${red} Aria2安装失败 ${font}"
    exit 1
fi

# Create Aria2 ConfigFile Folder and SessionFile
mkdir -p /etc/aria2
touch /etc/aria2/aria2.session

# Create Aria2.conf
cat > /etc/aria2/aria2.conf <<EOF

## '#'开头为注释内容, 选项都有相应的注释说明, 根据需要修改 ##
## 被注释的选项填写的是默认值, 建议在需要修改时再取消注释  ##

## 文件保存相关 ##

# 文件的保存路径(可使用绝对路径或相对路径), 默认: 当前启动位置
dir=/usr/share/nginx/kodexplorer/data/User/admin/home
# 启用磁盘缓存, 0为禁用缓存, 需1.16以上版本, 默认:16M
disk-cache=32M
# 文件预分配方式, 能有效降低磁盘碎片, 默认:prealloc
# 预分配所需时间: none < falloc ? trunc < prealloc
# falloc和trunc则需要文件系统和内核支持
# NTFS建议使用falloc, EXT3/4建议trunc, MAC 下需要注释此项
#file-allocation=none
# 断点续传
continue=true

## 下载连接相关 ##

# 最大同时下载任务数, 运行时可修改, 默认:5
max-concurrent-downloads=50
# 同一服务器连接数, 添加时可指定, 默认:1
max-connection-per-server=5
# 最小文件分片大小, 添加时可指定, 取值范围1M -1024M, 默认:20M
# 假定size=10M, 文件为20MiB 则使用两个来源下载; 文件为15MiB 则使用一个来源下载
min-split-size=10M
# 单个任务最大线程数, 添加时可指定, 默认:5
#split=5
# 整体下载速度限制, 运行时可修改, 默认:0
#max-overall-download-limit=0
# 单个任务下载速度限制, 默认:0
#max-download-limit=0
# 整体上传速度限制, 运行时可修改, 默认:0
#max-overall-upload-limit=0
# 单个任务上传速度限制, 默认:0
#max-upload-limit=0
# 禁用IPv6, 默认:false
#disable-ipv6=true
# 连接超时时间, 默认:60
#timeout=60
# 最大重试次数, 设置为0表示不限制重试次数, 默认:5
#max-tries=5
# 设置重试等待的秒数, 默认:0
#retry-wait=0

## 进度保存相关 ##

# 从会话文件中读取下载任务
input-file=/etc/aria2/aria2.session
# 在Aria2退出时保存错误/未完成的下载任务到会话文件
save-session=/etc/aria2/aria2.session
# 定时保存会话, 0为退出时才保存, 需1.16.1以上版本, 默认:0
save-session-interval=60
# 即使下载完成或删除也全部保存
#force-save=true

## RPC相关设置 ##

# 启用RPC, 默认:false
enable-rpc=true
# 允许所有来源, 默认:false
rpc-allow-origin-all=true
# 允许非外部访问, 默认:false
rpc-listen-all=true
# 事件轮询方式, 取值:[epoll, kqueue, port, poll, select], 不同系统默认值不同
#event-poll=select
# RPC监听端口, 端口被占用时可以修改, 默认:6800
rpc-listen-port=6800
# 设置的RPC授权令牌, v1.18.4新增功能, 取代 --rpc-user 和 --rpc-passwd 选项
rpc-secret=${RPCPasswd}
# 设置的RPC访问用户名, 此选项新版已废弃, 建议改用 --rpc-secret 选项
#rpc-user=<USER>
# 设置的RPC访问密码, 此选项新版已废弃, 建议改用 --rpc-secret 选项
#rpc-passwd=<PASSWD>
# 是否启用 RPC 服务的 SSL/TLS 加密,
# 启用加密后 RPC 服务需要使用 https 或者 wss 协议连接
#rpc-secure=true
# 在 RPC 服务中启用 SSL/TLS 加密时的证书文件,
# 使用 PEM 格式时，您必须通过 --rpc-private-key 指定私钥
#rpc-certificate=/path/to/certificate.pem
# 在 RPC 服务中启用 SSL/TLS 加密时的私钥文件
#rpc-private-key=/path/to/certificate.key

## BT/PT下载相关 ##

# 当下载的是一个种子(以.torrent结尾)时, 自动开始BT任务, 默认:true
#follow-torrent=true
# BT监听端口, 当端口被屏蔽时使用, 默认:6881-6999
listen-port=51888
# 单个种子最大连接数, 默认:55
bt-max-peers=5000
# 打开DHT功能, PT需要禁用, 默认:true
enable-dht=true
# 打开IPv6 DHT功能, PT需要禁用
enable-dht6=true
# DHT网络监听端口, 默认:6881-6999
dht-listen-port=6881-6999
# 本地节点查找, PT需要禁用, 默认:false
bt-enable-lpd=true
# 种子交换, PT需要禁用, 默认:true
enable-peer-exchange=true
# 每个种子限速, 对少种的PT很有用, 默认:50K
#bt-request-peer-speed-limit=50K
# 客户端伪装, PT需要
#peer-id-prefix=-TR2770-
#user-agent=Transmission/2.77
# 当种子的分享率达到这个数时, 自动停止做种, 0为一直做种, 默认:1.0
#seed-ratio=0
# 做种时间，0为下载完成禁止做种，任务直接完成
seed-time=0
# BT校验相关, 默认:true
#bt-hash-check-seed=true
# 继续之前的BT任务时, 无需再次校验, 默认:false
bt-seed-unverified=true
# 保存磁力链接元数据为种子文件(.torrent文件), 默认:false
bt-save-metadata=true
EOF

# Change Permission For www-data
chown -R www-data:www-data /etc/aria2

# Create ConfigFile
cat > /etc/systemd/system/aria2.service <<EOF

[Unit]
Description=aria2
[Service]
User=www-data
Group=www-data
ExecStart=/usr/bin/aria2c --conf-path=/etc/aria2/aria2.conf
Restart=on-abort
[Install]
WantedBy=multi-user.target
EOF

# Overload Systemd
systemctl daemon-reload

# Start Aria2 and Setting boot
systemctl start aria2
systemctl enable aria2

# Download and Install AriaNG
mkdir -p /usr/share/nginx/ariang && cd /usr/share/nginx/ariang
wget --no-check-certificate https://github.com/mayswind/AriaNg/releases/download/1.0.0/AriaNg-1.0.0.zip
unzip AriaNg-1.0.0.zip
rm -rf AriaNg-1.0.0.zip

# Download and Install KodExplorer
mkdir -p /usr/share/nginx/kodexplorer && cd /usr/share/nginx/kodexplorer
wget --no-check-certificate https://lala.im/static/script/kodexplorer4.37.zip
unzip kodexplorer4.37.zip
rm -rf kodexplorer4.37.zip

# Change Permission For www-data
chown -R www-data:www-data /usr/share/nginx/kodexplorer
chown -R www-data:www-data /usr/share/nginx/ariang

# Create Nginx ConfigFile
cat > /etc/nginx/conf.d/ariang.conf <<EOF

server {
    listen       1585;
    server_name  ${HostIP};

    #charset koi8-r;
    #access_log  /var/log/nginx/host.access.log  main;

    location / {
        root   /usr/share/nginx/ariang;
        index  index.html index.htm index.php;
    }
}
EOF

cat > /etc/nginx/conf.d/kodexplorer.conf <<EOF

server {
    listen       1586;
    server_name  ${HostIP};

    #charset koi8-r;
    #access_log  /var/log/nginx/host.access.log  main;

    location / {
        root   /usr/share/nginx/kodexplorer;
        index  index.html index.htm index.php;
    }

    location ~ \.php$ {
        root           /usr/share/nginx/kodexplorer;
        fastcgi_pass   unix:/run/php/php7.0-fpm.sock;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  /usr/share/nginx/kodexplorer\$fastcgi_script_name;
        include        fastcgi_params;
    }

}
EOF

# Change Nginx Running User For www-data
sed -i 's/user  nginx;/user  www-data;/g' /etc/nginx/nginx.conf

# Start and Boot Nginx
systemctl restart nginx
systemctl enable nginx

echo
echo "#############################################################"
echo "Aria2 + AriaNG + KodExplorer Installation Complete"
echo "AriaNG WebSite: http://${HostIP}:1585"
echo "KodExplorer WebSite: http://${HostIP}:1586"
echo "Default Aria2 RPC Password: ${RPCPasswd}"
echo "Aria2 Config File: /etc/aria2/aria2.conf"
echo
}

# qBittorrent Install
qBittorrent_install(){

# HostIP input
read -p "请输入你的服务器公网IP地址:" HostIP

# CPUcore input
read -p "选择使用多少个CPU线程编译qBittorrent（多个线程将有效提升编译效率）:" CPUcore

# Create Swap
read -p "如果机器内存小于2GB需临时创建Swap,是否创建Swap?（yes/no）:" Choose
if [ $Choose = "yes" ];then
    dd if=/dev/zero of=/var/swap bs=1024 count=2097152
    mkswap /var/swap
    chmod 0600 /var/swap
    swapon /var/swap
fi
if [ $Choose = "no" ]
then
    echo -e "${yellow} 你选择不创建swap,脚本将立即开始安装qBittorrent ${font}"
fi

apt -y update
apt -y dist-upgrade
if [ $? -eq 0 ];then
    echo -e "${green} 系统更新完成 ${font}"
else 
    echo -e "${red} 系统更新失败 ${font}"
    exit 1
fi
apt -y install build-essential pkg-config automake libtool git wget python-setuptools
apt -y install libboost-dev libboost-system-dev libboost-chrono-dev libboost-random-dev libboost-python-dev libssl-dev libgeoip-dev
apt -y install qtbase5-dev qttools5-dev-tools libqt5svg5-dev
if [ $? -eq 0 ];then
    echo -e "${green} 依赖安装完成 ${font}"
else 
    echo -e "${red} 依赖安装失败 ${font}"
    exit 1
fi

# Judge libtorrent Installation status
libtorrentPatch="/usr/local/lib/libtorrent-rasterbar.so.9.0.0"

# Download libtorrent and install
if [ ! -f "$libtorrentPatch" ];then
    cd
    wget --no-check-certificate https://github.com/arvidn/libtorrent/releases/download/libtorrent_1_1_11/libtorrent-rasterbar-1.1.11.tar.gz
    tar -xzvf libtorrent-rasterbar-1.1.11.tar.gz
    cd libtorrent-rasterbar-1.1.11
    ./configure --enable-encryption --enable-python-binding --with-libiconv --with-libgeoip=system CXXFLAGS=-std=c++11
    make -j${CPUcore}
    make install
fi

# ldconfig
ldconfig -v
if [ $? -eq 0 ];then
    echo -e "${green} libtorrent-rasterbar安装完成 ${font}"
else 
    echo -e "${red} libtorrent-rasterbar安装失败 ${font}"
    exit 1
fi

# Download qBittorrent and install
cd
wget --no-check-certificate https://github.com/qbittorrent/qBittorrent/archive/release-4.1.4.tar.gz
tar -xzvf release-4.1.4.tar.gz
cd qBittorrent-release-4.1.4
./configure --prefix=/usr --disable-gui CXXFLAGS=-std=c++11
make -j${CPUcore}
make install
ldconfig -v
if [ $? -eq 0 ];then
    echo -e "${green} qBittorrent安装完成 ${font}"
else 
    echo -e "${red} qBittorrent安装失败 ${font}"
    exit 1
fi

# Create qBittorrent ConfigFile
cat > /etc/systemd/system/qbittorrent.service <<EOF

[Unit]
Description=qBittorrent Daemon Service
After=network.target

[Service]
User=root
ExecStart=/usr/bin/qbittorrent-nox
ExecStop=/usr/bin/killall -w qbittorrent-nox

[Install]
WantedBy=multi-user.target
EOF

# Systemd Restart
systemctl daemon-reload

# Start and Boot qBittorrent
systemctl start qbittorrent
systemctl enable qbittorrent

echo
echo "#############################################################"
echo "qBittorrent + libTorrent Installation Complete"
echo "qBittorrent WebSite: http://${HostIP}:8080"
echo "Default Web Account: admin"
echo "Default Web Password: adminadmin"
echo
}

# Deluge Install
Deluge_install(){

# HostIP input
read -p "请输入你的服务器公网IP地址:" HostIP

# CPUcore input
read -p "选择使用多少个CPU线程编译qBittorrent（多个线程将有效提升编译效率）:" CPUcore

# Create Swap
read -p "如果机器内存小于2GB需临时创建Swap,是否创建Swap?（yes/no）:" Choose
if [ $Choose = "yes" ];then
    dd if=/dev/zero of=/var/swap bs=1024 count=2097152
    mkswap /var/swap
    chmod 0600 /var/swap
    swapon /var/swap
fi
if [ $Choose = "no" ]
then
    echo -e "${yellow} 你选择不创建swap,脚本将立即开始安装qBittorrent ${font}"
fi

apt -y update
apt -y dist-upgrade
if [ $? -eq 0 ];then
    echo -e "${green} 系统更新完成 ${font}"
else 
    echo -e "${red} 系统更新失败 ${font}"
    exit 1
fi
apt -y install build-essential pkg-config automake libtool git wget python-setuptools
apt -y install libboost-dev libboost-system-dev libboost-chrono-dev libboost-random-dev libboost-python-dev libssl-dev libgeoip-dev
apt -y install qtbase5-dev qttools5-dev-tools libqt5svg5-dev
if [ $? -eq 0 ];then
    echo -e "${green} 依赖安装完成 ${font}"
else 
    echo -e "${red} 依赖安装失败 ${font}"
    exit 1
fi

# Judge libtorrent Installation status
libtorrentPatch="/usr/local/lib/libtorrent-rasterbar.so.9.0.0"

# Download libtorrent and install
if [ ! -f "$libtorrentPatch" ];then
    cd
    wget --no-check-certificate https://github.com/arvidn/libtorrent/releases/download/libtorrent_1_1_11/libtorrent-rasterbar-1.1.11.tar.gz
    tar -xzvf libtorrent-rasterbar-1.1.11.tar.gz
    cd libtorrent-rasterbar-1.1.11
    ./configure --enable-encryption --enable-python-binding --with-libiconv --with-libgeoip=system CXXFLAGS=-std=c++11
    make -j${CPUcore}
    make install
fi

# ldconfig
ldconfig -v
if [ $? -eq 0 ];then
    echo -e "${green} libtorrent-rasterbar安装完成 ${font}"
else 
    echo -e "${red} libtorrent-rasterbar安装失败 ${font}"
    exit 1
fi

# Install PIP
easy_install pip
if [ $? -eq 0 ];then
    echo -e "${green} PIP安装成功 ${font}"
else 
    echo -e "${red} PIP安装失败 ${font}"
    exit 1
fi

# Install Deluge Build Package
pip install twisted pyopenssl simplejson pyxdg chardet geoip setproctitle pillow mako service_identity
if [ $? -eq 0 ];then
    echo -e "${green} Deluge编译所需依赖安装完成 ${font}"
else 
    echo -e "${red} Deluge编译所需依赖安装失败 ${font}"
    exit 1
fi

# Download Deluge
cd
wget http://download.deluge-torrent.org/source/deluge-1.3.15.tar.gz
tar -xzvf deluge-1.3.15.tar.gz
cd deluge-1.3.15

# Install Deluge
python setup.py build
python setup.py install
if [ $? -eq 0 ];then
    echo -e "${green} Deluge安装成功 ${font}"
else 
    echo -e "${red} Deluge安装失败 ${font}"
    exit 1
fi

# Create DelugeConfigFile
cat > /etc/systemd/system/deluged.service <<EOF

[Unit]
Description=Deluge Bittorrent Client Daemon
Documentation=man:deluged
After=network-online.target
[Service]
Type=simple
User=root
Group=root
UMask=007
ExecStart=/usr/local/bin/deluged -d
Restart=on-failure
TimeoutStopSec=300
[Install]
WantedBy=multi-user.target
EOF

cat > /etc/systemd/system/deluge-web.service <<EOF

[Unit]
Description=Deluge Bittorrent Client Web Interface
Documentation=man:deluge-web
After=network-online.target deluged.service
Wants=deluged.service
[Service]
Type=simple
User=root
Group=root
UMask=027
ExecStartPre=/bin/sleep 5
ExecStart=/usr/local/bin/deluge-web
Restart=on-failure
[Install]
WantedBy=multi-user.target
EOF

# Systemd Restart
systemctl daemon-reload

# Start and Boot Deluge
systemctl start deluged
systemctl start deluge-web
systemctl enable deluged
systemctl enable deluge-web

echo
echo "#############################################################"
echo "Deluge + libTorrent Installation Complete"
echo "Deluge WebSite: http://${HostIP}:8112"
echo "Default Web Password: deluge"
echo
}

Start_BBR(){
echo "net.core.default_qdisc=fq" >> /etc/sysctl.conf
echo "net.ipv4.tcp_congestion_control=bbr" >> /etc/sysctl.conf
sysctl -p
if [ $? -eq 0 ];then
    echo -e "${green} BBR开启成功 ${font}"
else 
    echo -e "${red} BBR开启失败 ${font}"
    exit 1
fi
}

# 开始菜单设置
echo -e "${yellow} Debian9 下载工具一键安装脚本 For LALA.IM ${font}"
echo -e "${green} 1.安装Aria2+AriaNG+KodExplorer ${font}"
echo -e "${green} 2.安装qBittorrent4.1.4+libTorrent1.1.11 ${font}"
echo -e "${green} 3.安装Deluge1.3.15+libTorrent1.1.11 ${font}"
echo -e "${green} 4.开启GoogleBBR ${font}"
start_menu(){
    read -p "请输入数字(1-4)，选择你要安装的软件:" num
    case "$num" in
        1)
        Aria2_install
        ;;
        2)
        qBittorrent_install
        ;;
        3)
        Deluge_install
        ;;
        4)
        Start_BBR
        ;;
        *)
        echo -e "${Error} 请输入正确的数字 (1-4)"
        ;;
    esac
}

# 运行开始菜单
start_menu