#!/usr/bin/env bash

# Copyright (c) 2021-2026 community-scripts ORG
# Author: ekke85
# License: MIT | https://github.com/community-scripts/ProxmoxVE/raw/main/LICENSE
# Source: https://github.com/Dispatcharr/Dispatcharr

source /dev/stdin <<<"$FUNCTIONS_FILE_PATH"
color
verb_ip6
catch_errors
setting_up_container
network_check
update_os
setup_hwaccel

msg_info "Installing Dependencies"
$STD apt install -y \
  build-essential \
  python3-dev \
  libpq-dev \
  nginx \
  redis-server \
  ffmpeg \
  procps \
  vlc-bin \
  vlc-plugin-base \
  streamlink
msg_ok "Installed Dependencies"

setup_uv
NODE_VERSION="24" setup_nodejs
PG_VERSION="16" setup_postgresql
PG_DB_NAME="dispatcharr_db" PG_DB_USER="dispatcharr_usr" setup_postgresql_db
fetch_and_deploy_gh_release "dispatcharr" "Dispatcharr/Dispatcharr" "tarball"

msg_info "Installing Python Dependencies with uv"
cd /opt/dispatcharr
$STD uv venv --clear
$STD uv sync
$STD uv pip install uwsgi gevent celery redis daphne
msg_ok "Installed Python Dependencies"

msg_info "Configuring Dispatcharr"
install -d -m 755 \
  /data/{logos,recordings,plugins,db} \
  /data/uploads/{m3us,epgs} \
  /data/{m3us,epgs}
chown -R root:root /data
DJANGO_SECRET=$(openssl rand -base64 48 | tr -dc 'a-zA-Z0-9' | cut -c1-50)
export DATABASE_URL="postgresql://${PG_DB_USER}:${PG_DB_PASS}@localhost:5432/${PG_DB_NAME}"
export POSTGRES_DB=$PG_DB_NAME
export POSTGRES_USER=$PG_DB_USER
export POSTGRES_PASSWORD=$PG_DB_PASS
export POSTGRES_HOST=localhost
export DJANGO_SECRET_KEY=$DJANGO_SECRET
$STD uv run python manage.py migrate --noinput
$STD uv run python manage.py collectstatic --noinput
cat <<EOF >/opt/dispatcharr/.env
DATABASE_URL=postgresql://${PG_DB_USER}:${PG_DB_PASS}@localhost:5432/${PG_DB_NAME}
POSTGRES_DB=$PG_DB_NAME
POSTGRES_USER=$PG_DB_USER
POSTGRES_PASSWORD=$PG_DB_PASS
POSTGRES_HOST=localhost
CELERY_BROKER_URL=redis://localhost:6379/0
DJANGO_SECRET_KEY=$DJANGO_SECRET
EOF
cd /opt/dispatcharr/frontend
node -e "const p=require('./package.json');p.overrides=p.overrides||{};p.overrides['webworkify-webpack']='2.1.3';require('fs').writeFileSync('package.json',JSON.stringify(p,null,2));"
rm -f package-lock.json
$STD npm install --no-audit --progress=false
$STD npm run build
msg_ok "Configured Dispatcharr"

msg_info "Configuring Nginx"
cat <<EOF >/etc/nginx/sites-available/dispatcharr.conf
map \$http_x_forwarded_proto \$real_forwarded_proto {
    ""      \$scheme;
    default \$http_x_forwarded_proto;
}

map \$http_x_forwarded_port \$real_forwarded_port {
    ""      \$server_port;
    default \$http_x_forwarded_port;
}

server {
    listen 9191;
    server_name _;
    client_max_body_size 100M;

    # Serve static assets with correct MIME types
    location /assets/ {
        alias /opt/dispatcharr/frontend/dist/assets/;
        expires 30d;
        add_header Cache-Control "public, immutable";

        # Explicitly set MIME types for webpack-built assets
        types {
            text/javascript js;
            text/css css;
            image/png png;
            image/svg+xml svg svgz;
            font/woff2 woff2;
            font/woff woff;
            font/ttf ttf;
        }
    }

    location /static/ {
        alias /opt/dispatcharr/static/;
        expires 30d;
        add_header Cache-Control "public, immutable";
    }

    location /media/ {
        alias /opt/dispatcharr/media/;
    }

    location /ws/ {
        proxy_pass http://127.0.0.1:8001;
        proxy_http_version 1.1;
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection "Upgrade";
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$real_forwarded_proto;
    }

    # All other requests proxy to uWSGI
    location / {
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$real_forwarded_proto;
        proxy_set_header X-Forwarded-Port \$real_forwarded_port;
        proxy_pass http://127.0.0.1:5656;
    }
}
EOF
nginx_enable_site dispatcharr.conf
msg_ok "Configured Nginx"

msg_info "Creating Services"
cat <<EOF >/opt/dispatcharr/start-uwsgi.sh
#!/usr/bin/env bash
cd /opt/dispatcharr
set -a
source .env
set +a
exec .venv/bin/uwsgi \\
    --chdir=/opt/dispatcharr \\
    --module=dispatcharr.wsgi:application \\
    --master \\
    --workers=4 \\
    --gevent=400 \\
    --http=0.0.0.0:5656 \\
    --http-keepalive=1 \\
    --http-timeout=600 \\
    --socket-timeout=600 \\
    --buffer-size=65536 \\
    --post-buffering=4096 \\
    --lazy-apps \\
    --thunder-lock \\
    --die-on-term \\
    --vacuum
EOF
chmod +x /opt/dispatcharr/start-uwsgi.sh

cat <<EOF >/opt/dispatcharr/start-celery.sh
#!/usr/bin/env bash
cd /opt/dispatcharr
set -a
source .env
set +a
exec uv run celery -A dispatcharr worker -l info -c 4 -Q celery,recordings,dvr,default
EOF
chmod +x /opt/dispatcharr/start-celery.sh

cat <<EOF >/opt/dispatcharr/start-celerybeat.sh
#!/usr/bin/env bash
cd /opt/dispatcharr
set -a
source .env
set +a
exec uv run celery -A dispatcharr beat -l info
EOF
chmod +x /opt/dispatcharr/start-celerybeat.sh

cat <<EOF >/opt/dispatcharr/start-daphne.sh
#!/usr/bin/env bash
cd /opt/dispatcharr
set -a
source .env
set +a
exec uv run daphne -b 0.0.0.0 -p 8001 dispatcharr.asgi:application
EOF
chmod +x /opt/dispatcharr/start-daphne.sh

cat <<EOF >/etc/systemd/system/dispatcharr.service
[Unit]
Description=Dispatcharr Web Server
After=network.target postgresql.service redis-server.service

[Service]
Type=simple
WorkingDirectory=/opt/dispatcharr
ExecStart=/opt/dispatcharr/start-uwsgi.sh
Restart=on-failure
RestartSec=10
User=root

[Install]
WantedBy=multi-user.target
EOF

cat <<EOF >/etc/systemd/system/dispatcharr-celery.service
[Unit]
Description=Dispatcharr Celery Worker
After=network.target redis-server.service
Requires=dispatcharr.service

[Service]
Type=simple
WorkingDirectory=/opt/dispatcharr
ExecStart=/opt/dispatcharr/start-celery.sh
Restart=on-failure
RestartSec=10
User=root

[Install]
WantedBy=multi-user.target
EOF

cat <<EOF >/etc/systemd/system/dispatcharr-celerybeat.service
[Unit]
Description=Dispatcharr Celery Beat Scheduler
After=network.target redis-server.service
Requires=dispatcharr.service

[Service]
Type=simple
WorkingDirectory=/opt/dispatcharr
ExecStart=/opt/dispatcharr/start-celerybeat.sh
Restart=on-failure
RestartSec=10
User=root

[Install]
WantedBy=multi-user.target
EOF

cat <<EOF >/etc/systemd/system/dispatcharr-daphne.service
[Unit]
Description=Dispatcharr WebSocket Server (Daphne)
After=network.target
Requires=dispatcharr.service

[Service]
Type=simple
WorkingDirectory=/opt/dispatcharr
ExecStart=/opt/dispatcharr/start-daphne.sh
Restart=on-failure
RestartSec=10
User=root

[Install]
WantedBy=multi-user.target
EOF
systemctl enable -q --now dispatcharr dispatcharr-celery dispatcharr-celerybeat dispatcharr-daphne
msg_ok "Created Services"

motd_ssh
customize
cleanup_lxc
