#!/bin/sh

IMAGE_NAME=80x86/qbittorrent
WEB_PORT=$(nvram get app.qb.listen_port)
[ -z "$WEB_PORT" ] && WEB_PORT=8082
DOWNLOAD_PATH=$(cat /var/lib/qbittorrent/.config/qBittorrent/qBittorrent.conf | grep -i 'Downloads\\SavePath' | cut -d'=' -f2)
BT_PORT=$(cat /var/lib/qbittorrent/.config/qBittorrent/qBittorrent.conf | grep -i 'Connection\\PortRangeMin' | cut -d'=' -f2)
[ -z "$BT_PORT" ] && BT_PORT=8999
QBT_AUTH_SERVER_ADDR=$(ip -4 addr show docker0 | grep inet | awk '{print $2}' | cut -d'/' -f1)
if [ "$DOWNLOAD_PATH" = "/downloads" ] || [ "$DOWNLOAD_PATH" = "/downloads/" ] || [ "$DOWNLOAD_PATH" = "" ]; then
    echo "please set correct DOWNLOAD_PATH"
    exit -1
fi

docker pull ${IMAGE_NAME} && \
docker run -d --name qbittorrent \
        -e PUID=$(id -u qbittorrent) \
	    -e PGID=$(cat /etc/group | grep -e '^users' | cut -d':' -f3) \
        -e WEB_PORT=$WEB_PORT \
        -e BT_PORT=$BT_PORT \
        -e QBT_AUTH_SERVER_ADDR=$QBT_AUTH_SERVER_ADDR \
        --restart unless-stopped \
        -p $WEB_PORT:$WEB_PORT -p $BT_PORT:$BT_PORT/tcp -p $BT_PORT:$BT_PORT/udp \
        -v /var/lib/qbittorrent/.config/qBittorrent:/config \
        -v /var/lib/qbittorrent/.local/share/data/qBittorrent:/data \
        -v "$DOWNLOAD_PATH":/downloads \
        --mount type=tmpfs,destination=/tmp \
        ${IMAGE_NAME}