#!/bin/bash

# Update and upgrade system packages
echo "Updating system packages..."
sudo apt update
sudo apt full-upgrade -y

# Install qbittorrent-nox (headless version)
echo "Installing qBittorrent-nox..."
sudo apt install -y qbittorrent-nox

# Create a system user for qBittorrent (optional but recommended)
echo "Creating qBittorrent user..."
sudo useradd -r -m qbt

# Add your normal user (pi) to the qbt group to access downloaded files
sudo usermod -a -G qbt $USER

# Create systemd service file for qBittorrent
echo "Creating systemd service file..."
sudo tee /etc/systemd/system/qbittorrent-nox.service > /dev/null <<EOF
[Unit]
Description=qBittorrent Command Line Client
After=network.target

[Service]
User=$USER
ExecStart=/usr/bin/qbittorrent-nox
Restart=always

[Install]
WantedBy=multi-user.target
EOF

# Reload systemd, enable and start qBittorrent service
echo "Enabling and starting qBittorrent service..."
sudo systemctl daemon-reload
sudo systemctl enable qbittorrent-nox
sudo systemctl start qbittorrent-nox

echo "qBittorrent installation and service setup complete."
echo "Access the Web UI at http://<your_pi_ip>:8080"
echo "Default credentials: username: admin, password: adminadmin"
echo "It's highly recommended to change the default login credentials in the Web UI."
