#!/bin/sh
# SPDX-License-Identifier: GPL-2.0
# Copyright (C) 2016-present Team LibreELEC (https://libreelec.tv)

. /etc/profile
oe_setup_addon service.emby4

libs="${ADDON_DIR}/libs"
ff="/storage/.kodi/addons/tools.ffmpeg-tools/bin"

if [ ! -e "${libs}" ]; then
  url="https://github.com/MediaBrowser/Emby.Releases/releases"
  url_latest="${url}/latest"
  release="$(basename $(curl -fso /dev/null -w %{redirect_url} ${url_latest}))"
  url_download="${url}/download/${release}/embyserver-netcore_${release}.zip"
  zip="${ADDON_DIR}/bootstrap.zip"
  tmp="${ADDON_DIR}/tmp"
  rm -fr "${tmp}" "${zip}"
  mkdir -p "${tmp}"
  wget -q "${url_download}" -O "${zip}" && \
  unzip "${zip}" -d "${tmp}" && \
  mv "${tmp}" "${libs}" && \
  rm -f "${zip}" || \
  exit 1
fi

exec \
nice -n "$emby_nice" \
dotnet "${libs}/system/EmbyServer.dll" \
  -programdata "${ADDON_HOME}" \
  -ffmpeg "${ff}/ffmpeg" \
  -ffprobe "${ff}/ffprobe"
