#!/usr/bin/with-contenv bashio
# shellcheck shell=bash

#################
# NGINX SETTING #
#################

declare admin_port
declare qbittorrent_protocol=http

# Generate Ingress configuration
if bashio::config.true 'ssl'; then
    qbittorrent_protocol=https
fi

cp /etc/nginx/templates/ingress.gtpl /etc/nginx/servers/ingress.conf
sed -i "s|{{ .interface }}|$(bashio::addon.ip_address)|g" /etc/nginx/servers/ingress.conf
sed -i "s|{{ .port }}|$(bashio::addon.ingress_port)|g" /etc/nginx/servers/ingress.conf
sed -i "s|{{ .protocol }}|${qbittorrent_protocol}|g" /etc/nginx/servers/ingress.conf
sed -i "s|{{ .certfile }}|$(bashio::config 'certfile')|g" /etc/nginx/servers/ingress.conf
sed -i "s|{{ .keyfile }}|$(bashio::config 'keyfile')|g" /etc/nginx/servers/ingress.conf
sed -i "s|{{ .ssl }}|$(bashio::config 'ssl')|g" /etc/nginx/servers/ingress.conf

######################
# VUETORRENT INSTALL #
######################

LATEST_RELEASE=$(curl -s -L https://api.github.com/repos/wdaan/vuetorrent/releases/latest |
    grep "browser_download_url.*zip" |
    cut -d : -f 2,3 |
    tr -d \" |
    xargs)

curl -s -S -O -J -L $LATEST_RELEASE
unzip -o vuetorrent.zip -d / >/dev/null
rm /vuetorrent.zip >/dev/null
