#!/bin/bash
# DEPLOYMENT LOCATION: /opt/docker/jellyfin/setup.sh
# Deploy with: sudo cp config/docker/jellyfin/setup.sh /opt/docker/jellyfin/ && sudo chmod +x /opt/docker/jellyfin/setup.sh

set -e

echo "Setting up Jellyfin media server..."

# Create necessary directories
echo "Creating Jellyfin directories..."
sudo mkdir -p /opt/docker/jellyfin/{config,cache}

# Set proper ownership for Jellyfin directories
echo "Setting directory ownership..."
sudo chown -R 1000:1000 /opt/docker/jellyfin/

# Copy docker-compose.yml if it doesn't exist
if [ ! -f /opt/docker/jellyfin/docker-compose.yml ]; then
    echo "Copying docker-compose.yml..."
    sudo cp /home/hoborg/homelab/config/docker/jellyfin/docker-compose.yml /opt/docker/jellyfin/
fi

# Check if media directories exist, create if needed
echo "Checking media directories..."
for dir in Music Videos shared; do
    if [ ! -d "/home/hoborg/$dir" ]; then
        echo "Creating /home/hoborg/$dir directory..."
        mkdir -p "/home/hoborg/$dir"
    fi
done

# Start Jellyfin container
echo "Starting Jellyfin container..."
cd /opt/docker/jellyfin
sudo docker-compose pull
sudo docker-compose up -d

echo "Jellyfin setup complete!"
echo "Access URL: http://localhost:8096"
echo "External URL: https://ak-homelab.duckdns.org/media (after nginx setup)"
echo ""
echo "Media folders mapped:"
echo "  - Music: /home/hoborg/Music → /media/music"
echo "  - Videos: /home/hoborg/Videos → /media/videos" 
echo "  - Shared: /home/hoborg/shared → /media/shared"
echo ""
echo "To check status: cd /opt/docker/jellyfin && sudo docker-compose logs -f jellyfin"