#!/bin/bash

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

BUMP_PKG_REV=""
FORCE_LIBRETRO_BUMP=""
KEEP_GIT_DIRS="yes"

usage() {
  echo "Usage: $0 [options] <kodi-branch> [<tag-suffix>]"
  echo " -b, --bump-pkg-rev: bump PKG_REV if package was not updated"
  echo " -d, --delete-git-dirs: delete cloned git dirs after update"
  echo " -f, --force-libretro-bump: check for new libretro package"
  echo "     even if kodi game package version has not changed"
  echo " -h, --help: display help"
}

while [ $# -ne 0 ]; do
  case "$1" in
  -b|--bump-pkg-rev)
    BUMP_PKG_REV="yes"
    shift
    ;;
  -d|--delete-git-dirs)
    KEEP_GIT_DIRS=""
    shift
    ;;
  -f|--force-libretro-bump)
    FORCE_LIBRETRO_BUMP="yes"
    shift
    ;;
  -h|--help)
    usage
    exit 1
    ;;
  -*)
    echo "illegal option $1"
    usage
    exit 1
    ;;
  *)
    break
    ;;
  esac
done


if [ $# -eq 0 -o $# -gt 2 ]; then
  usage
  exit 1
fi

KODI_BRANCH="$1"

if [ $# -eq 2 ]; then
  TAG_SUFFIX="$2"
else
  TAG_SUFFIX="${KODI_BRANCH}"
fi

# list of packages to exclude from update
EXCLUDED_PACKAGES="
	game.netplay
	game.shader.presets"

MY_DIR="$(dirname "$0")"
ROOT="$(cd "${MY_DIR}"/../.. && pwd)"
TMPDIR="$(pwd)/.update-retroplayer-tmp"
TMP_PKG_FILE="${TMPDIR}/package.tar.gz"
TMP_PKG_DIR="${TMPDIR}/package"

rm -rf "${TMPDIR}"
mkdir -p "${TMPDIR}"

. "${MY_DIR}/update_common_functions"

get_gh_token

# check if depends are available
if [ -n "${GITHUB_API_TOKEN}" ]; then
  command -v curl >/dev/null 2>&1 || die "please install curl"
  command -v jq >/dev/null 2>&1 || die "please install jq"
fi

ADDONS="game-binary-addons"
ADDONS_DIR="${ADDONS}.git"
ADDONS_REPO="https://github.com/kodi-game/repo-binary-addons.git"
git_clone ${ADDONS_REPO} ${ADDONS_DIR} ${KODI_BRANCH}

for addon in ${ADDONS_DIR}/*.*/ ; do
  GAME_ADDON=$(basename ${addon})

  [[ "${GAME_ADDON}" =~ ^game. ]] || continue

  check_package_excluded "${GAME_ADDON}" "${EXCLUDED_PACKAGES}" && continue

  if ! grep -q all $addon/platforms.txt && ! grep -q linux $addon/platforms.txt && ! grep -q ! $addon/platforms.txt; then
    continue
  fi

  GAME_GIT_DIR="${GAME_ADDON}.git"
  GAME_GIT_REPO=$(cat $addon/${GAME_ADDON}.txt | awk '{print $2}')
  GAME_GIT_BRANCH=$(cat $addon/${GAME_ADDON}.txt | awk '{print $3}')
  GAME_PATH="${ROOT}/packages/mediacenter/kodi-binary-addons/${GAME_ADDON}"

  if [ ! -d "$GAME_PATH" ] ; then
    msg_warn "SKIPPING ${GAME_ADDON}, not present in LE"
    continue
  fi

  if [[ "${GAME_ADDON}" =~ ^game.libretro. ]]; then
    RETRO_NAME="${GAME_ADDON#game.libretro.}"
    RETRO_ADDON="libretro-${RETRO_NAME}"
    RETRO_PATH="${ROOT}/packages/emulation/${RETRO_ADDON}"
  else
    RETRO_NAME=""
    RETRO_ADDON=""
    RETRO_PATH=""
  fi

  BUMPED_ADDON=""
  BUMPED_RETRO=""
  NO_TAG=""
  CHECK_RETRO=""

  if [ -z "$GITHUB_API_TOKEN" ]; then
    git_clone "${GAME_GIT_REPO}" "${GAME_GIT_DIR}"
    if [ -n "${TAG_SUFFIX}" ]; then
      GAME_NEW_VERSION=$(resolve_tag_in_branch "${GAME_GIT_DIR}" "${GAME_GIT_BRANCH}" ".*-${TAG_SUFFIX}$")
    else
      GAME_NEW_VERSION=$(resolve_tag_in_branch "${GAME_GIT_DIR}" "${GAME_GIT_BRANCH}")
    fi
  else
    REPO=$(basename "${GAME_GIT_REPO}")
    OWNER=$(basename "${GAME_GIT_REPO%/${REPO}*}")
    if [ -n "${TAG_SUFFIX}" ]; then
      GAME_NEW_VERSION=$(resolve_tag_on_gh "${OWNER}" "${REPO}" "-${TAG_SUFFIX}")
    else
      GAME_NEW_VERSION=$(resolve_tag_on_gh "${OWNER}" "${REPO}")
    fi
  fi

  if [ -z "${GAME_NEW_VERSION}" ]; then
    NO_TAG="yes"
    echo "========================================================================"
    msg_warn "WARNING: no tag found for addon ${GAME_ADDON}, falling back to HEAD"
    echo "========================================================================"
    if [ -z "$GITHUB_API_TOKEN" ]; then
      GAME_NEW_VERSION=$(resolve_hash_in_branch "${GAME_GIT_DIR}" "${GAME_GIT_BRANCH}")
    else
      GAME_NEW_VERSION=$(resolve_hash_on_gh "${GAME_GIT_REPO}" "${GAME_GIT_BRANCH}")
    fi
  fi

  if [ "${KEEP_GIT_DIRS}" != "yes" ]; then
    rm -rf "${GAME_GIT_DIR}"
  fi

  if update_pkg "${GAME_PATH}" "${GAME_ADDON}" "${GAME_NEW_VERSION}"; then
    BUMPED_ADDON="yes"
    [ -n "${RETRO_NAME}" ] && CHECK_RETRO="yes"
  else
    if [ -n "${FORCE_LIBRETRO_BUMP}" -a -n "${RETRO_NAME}" ]; then
      download_pkg_file "${GAME_ADDON}"
      CHECK_RETRO="yes"
    fi
  fi

  if [ -n "${CHECK_RETRO}" ]; then
    if [ ! -d "${RETRO_PATH}" ]; then
      msg_error "ERROR: ${RETRO_PATH} doesn't exist"
      cleanup_pkg_tmp
      exit 1
    fi

    extract_pkg_file

    RETRO_VERSION_FILE="${TMP_PKG_DIR}/depends/common/${RETRO_NAME}/${RETRO_NAME}.txt"

    if [ ! -f "${RETRO_VERSION_FILE}" ]; then
      msg_error "ERROR: ${RETRO_VERSION_FILE} does not exist"
      cleanup_pkg_tmp
      exit 1
    fi

    VERSION_INFO=$(grep "^${RETRO_NAME}" "${RETRO_VERSION_FILE}" | head -1)
    if [[ "$VERSION_INFO" =~ github\.com/[^/]+/[^/]+/archive/[^/]+\.tar\..*$ ]] ; then
      # version referenced by githash
      RETRO_NEW_VERSION=$(echo "${VERSION_INFO}" | sed -E -e 's|^(.+/archive/)([^/]+)(\.tar.*)$|\2|')
      RETRO_NEW_REPO=$(echo "${VERSION_INFO}" | sed -E -e 's|^(.+github\.com/)([^/]+/[^/]+)(/archive/.*)$|\2|')
      RETRO_NEW_URL="https://github.com/${RETRO_NEW_REPO}/archive/\${PKG_VERSION}.tar.gz"
    else
      msg_warn "UNSUPPORTED ${RETRO_ADDON} version info, update manually: ${VERSION_INFO}"
      RETRO_NEW_VERSION=""
      RETRO_NEW_REPO=""
      RETRO_NEW_URL=""
    fi

    if [ -n "${RETRO_NEW_VERSION}" ] && update_pkg_and_url "${RETRO_PATH}" "${RETRO_ADDON}" "${RETRO_NEW_VERSION}" "${RETRO_NEW_URL}"; then
      BUMPED_RETRO="yes"
    fi
  fi

  if [ -n "${NO_TAG}" ]; then
    # always bump PKG_REV on updates as we have no info if version changed
    if [ -n "${BUMPED_ADDON}" -o -n "${BUMPED_RETRO}" -o -n "${BUMP_PKG_REV}" ]; then
      bump_pkg_rev "${GAME_PATH}" "${GAME_ADDON}"
    fi
  else
    if [ -n "${BUMPED_ADDON}" ]; then
      # reset PKG_REV if version changed
      reset_pkg_rev "${GAME_PATH}" "${GAME_ADDON}"
    else
      # if addon version is unchanged but libretro changed bump PKG_REV
      if [ -n "${BUMPED_RETRO}" -o -n "${BUMP_PKG_REV}" ]; then
        bump_pkg_rev "${GAME_PATH}" "${GAME_ADDON}"
      fi
    fi
  fi

  cleanup_pkg_tmp
done

msg_info "Checking for orphaned addon packages in LE"
for addon in ${ROOT}/packages/mediacenter/kodi-binary-addons/game.libretro.* ; do
  GAME_ADDON=$(basename ${addon})
  if [ ! -d "${ADDONS_DIR}/${GAME_ADDON}" ] ; then
    msg_warn "ORHPANED ${GAME_ADDON}, not present in kodi game repo"
  fi
done

rm -rf "${TMPDIR}"

