#!/bin/bash

# 检测权限
echo "Detect permissions as root"

if [ "$(id -u)" -ne 0 ]; then
   echo "This script must be run as root"
   exit 1
fi

# 检测系统版本
echo "Detecting system versions"
sys_num=$(cut -f2 <<< "$(lsb_release -r| sed "s/\.//g")" )
sys_des=$(lsb_release -d)
echo "$sys_num"
echo "$sys_des"

if [ -f /etc/debian_version ] && [ "$sys_num" -ge 2004 ] && [[ $sys_des =~ Ubuntu ]] ; then
  echo "此系统版本为Ubuntu20.04及以上"
	dependencies="wget curl vim python3 python3-setuptools python3-pip"
	update_cmd='apt-get update -y'
	install_cmd="apt-get install -y ${dependencies}"
else
	install_cmd=''
fi

if [ -z "${install_cmd}" ]; then
        echo "此操作系统不被支持，该脚本只支持系统Ubuntu20.04及以上版本，部署停止"
	exit 1
fi

# 是为了确保即使"$dependencies"包含破折号，它们也不会被解释为命令行选项
# set -- "$dependencies"
echo "Installing environment"
${update_cmd}
sleep 5
${install_cmd}

# 关闭防火墙
ufw disable

# 修复inotify 项目的数量限制
echo 1048576 > /proc/sys/fs/inotify/max_user_watches


## 判断本地网络是否加入wireguard集群
wire_ip=$(ip addr | grep nm- | grep -o '[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}'| head -1)

if [ -z "${wire_ip}" ]; then
	echo "此服务器没有加入服务集群，transmission监听所有网卡"
    transmission_port=" -p 9091:9091 -p 51413:51413 -p 51413:51413/udp "
    echo transmission的web配置为:"$transmission_port"
else
    echo 本服务器在集群内IP为"$wire_ip"
    transmission_port="-p $wire_ip:9091:9091 -p 127.0.0.1:9091:9091 -p 51413:51413 -p 51413:51413/udp "
    echo transmission的web配置为"$transmission_port"
fi





# 由于分发节点是需要使用脚本进行部署，因此在这里我使用docker脚本进行部署。
curl -fsSL https://get.docker.com -o get-docker.sh
sh get-docker.sh

systemctl enable docker.service
systemctl enable containerd.service

# 为了安全起见，最好使用特定用户和组运行服务。
adduser --system  --gecos "Cor Service" --disabled-password --group --home /var/lib/cor cor

# 放置配置文件,将settings.json放入该文件夹下
mkdir -p /var/lib/cor/transmission/config
# cp /root/settings.json /var/lib/cor/transmission/config/settings.json

cat > /var/lib/cor/transmission/config/settings.json << EOF
{
    "alt-speed-down": 50,
    "alt-speed-enabled": false,
    "alt-speed-time-begin": 540,
    "alt-speed-time-day": 127,
    "alt-speed-time-enabled": false,
    "alt-speed-time-end": 1020,
    "alt-speed-up": 50,
    "bind-address-ipv4": "0.0.0.0",
    "bind-address-ipv6": "::",
    "blocklist-enabled": false,
    "blocklist-url": "http://www.example.com/blocklist",
    "cache-size-mb": 4,
    "dht-enabled": true,
    "download-dir": "/downloads/complete",
    "download-queue-enabled": true,
    "download-queue-size": 5,
    "encryption": 1,
    "idle-seeding-limit": 30,
    "idle-seeding-limit-enabled": false,
    "incomplete-dir": "/downloads/incomplete",
    "incomplete-dir-enabled": false,
    "lpd-enabled": true,
    "message-level": 2,
    "peer-congestion-algorithm": "",
    "peer-id-ttl-hours": 6,
    "peer-limit-global": 2000,
    "peer-limit-per-torrent": 50,
    "peer-port": 51413,
    "peer-port-random-high": 65535,
    "peer-port-random-low": 49152,
    "peer-port-random-on-start": false,
    "peer-socket-tos": "default",
    "pex-enabled": true,
    "port-forwarding-enabled": true,
    "preallocation": 1,
    "prefetch-enabled": true,
    "queue-stalled-enabled": false,
    "queue-stalled-minutes": 30,
    "ratio-limit": 2,
    "ratio-limit-enabled": false,
    "rename-partial-files": false,
    "rpc-authentication-required": true,
    "rpc-bind-address": "0.0.0.0",
    "rpc-enabled": true,
    "rpc-host-whitelist": "",
    "rpc-host-whitelist-enabled": false,
    "rpc-password": "{4f683ea4d4dbf7fd336e879a046c75251a1a2872IagIKSDT",
    "rpc-port": 9091,
    "rpc-url": "/transmission/",
    "rpc-username": "cor",
    "rpc-whitelist": "",
    "rpc-whitelist-enabled": false,
    "scrape-paused-torrents-enabled": true,
    "script-torrent-done-enabled": false,
    "script-torrent-done-filename": "",
    "seed-queue-enabled": false,
    "seed-queue-size": 10,
    "speed-limit-down": 100,
    "speed-limit-down-enabled": false,
    "speed-limit-up": 100,
    "speed-limit-up-enabled": false,
    "start-added-torrents": true,
    "trash-original-torrent-files": false,
    "umask": 2,
    "upload-slots-per-torrent": 14,
    "utp-enabled": true,
    "watch-dir": "/watch",
    "watch-dir-enabled": true
}

EOF

chmod 755 /var/lib/cor/transmission/config/settings.json

# 提取cor的UID与GID
DUID=$(id -u cor)
DGID=$(id -g cor)

# 部署transmission
## 生成账户密码
transmission_user=$(tr -dc A-Za-z0-9 </dev/urandom | head -c 5 ; echo '')
transmission_pass=$(tr -dc A-Za-z0-9 </dev/urandom | head -c 16 ; echo '')

## 开始部署

transmission_docker_cmd="
docker run -itd \
  --name=transmission \
  -e PUID=$DUID \
  -e PGID=$DGID \
  -e TZ=Asia/Shanghai \
  -e TRANSMISSION_WEB_HOME=/transmission-web-control/  \
  -e USER=$transmission_user  \
  -e PASS=$transmission_pass   \
  $transmission_port \
  --mount type=bind,source=/etc/hosts,target=/etc/hosts,readonly \
  -v /var/lib/cor/transmission/config:/config \
  -v /var/lib/cor/transmission/downloads:/downloads \
  -v /var/lib/cor/transmission/watch:/watch \
  --restart=always \
  --log-opt max-size=10m --log-opt max-file=3 \
  linuxserver/transmission
"
echo 运行的transmission_docker命令是:"$transmission_docker_cmd"
${transmission_docker_cmd}

# 开始部署flexget
## 安装环境
pip3 install --upgrade pip -i https://mirrors.aliyun.com/pypi/simple/
pip3 install flexget -i https://mirrors.aliyun.com/pypi/simple/
pip3 install transmission-rpc -i https://mirrors.aliyun.com/pypi/simple/
## 创建配置文件
mkdir -p /var/lib/cor/flexget/torrent/
cat > /var/lib/cor/flexget/config.yml << EOF
# 预设模板
templates:
# 剩余空间模板，当 path 对应的路径的剩余空间小于 space 规定的数值的时候停止 RSS 下载（以 MB 为单位）
  freespace:
    free_space:
      path: /var/lib/cor/transmission/downloads/
      space: 10240
# qb 的模板，之后写 qb 就是指把种子推送到 qb 进行下载；下面 tr de rt 也是如此
# 我脚本里账号密码都帮你写好了，除非你自己改了账号、密码或者端口，不然以下这些客户端设置不用修改
  tr:
    transmission:
      path: /downloads/complete/
      host: localhost
      port: 9091
      username: $transmission_user
      password: $transmission_pass

# 任务
tasks:
# cor-torrent-cache是任务名称，基本上随便起
  cor-torrent-cache:
  # RSS 链接请自己修改成你实际的链接
    rss: http://file.rmrts.com/srv/feed.xml
    # 因为日冕有时候用的标题是一样的， 因此下过一次后
    # 之后新发出来的文件由于标题一样，flexget 会当成是以前已经下过的种子
    # 为了避免这个问题，对 seen 插件设定为只检查 pubDate 是否一致
    seen:
      fields:
        - pubDate
  # 调用上边的 tr 模板
    template: tr
  # 允许所有的下载
    accept_all: yes
  # 种子临时下载目录
    download: /var/lib/cor/flexget/torrent/
  # 调试时禁止使用hash匹配，使用no参数，实际使用时把下面的这段注销掉。
    # seen_info_hash: no
  # 自动限制上传速度到 100MB/s（防止超速 ban）
    transmission:
      # Limit upload speed to 100 MiB/s in case of being auto-banned
      max_up_speed: 102400


# tasks 处写要执行 RSS 的任务名称，minutes: 3 表示每隔 3 分钟执行一次上述任务
schedules:
  - tasks: [cor-torrent-cache]
    interval:
      minutes: 5
EOF

## 自动运行
cat > /etc/systemd/system/flexget.service << EOF
[Unit]
Description=Flexget Daemon
After=network.target

[Service]
Type=simple
User=root
WorkingDirectory=/var/lib/cor/flexget/
ExecStart=/usr/local/bin/flexget daemon start
ExecStop=/usr/local/bin/flexget daemon stop
ExecReload=/usr/local/bin/flexget daemon reload

[Install]
WantedBy=multi-user.target
EOF
systemctl enable flexget
systemctl start flexget


echo 为日常检查状态，可前往ip:9091检查当前分发情况
echo transmission的账户是:"$transmission_user" | tee -a transmission.log 
echo transmission的密码是:"$transmission_pass" | tee -a transmission.log 

echo 部署完成,请保存所有项目后重启服务器。

echo "The deployment is complete, if you are ready to restart the server, please select 1"

select yn in "Yes" "No"; do
    case $yn in
        "Yes") reboot ;;
        "No") echo "Please be ready to restart the server" ;;
        * ) echo "Please enter 1 or 2";;
    esac
done
