# SPDX-License-Identifier: GPL-2.0-or-later
# Copyright (C) 2009-2016 Stephan Raue (stephan@openelec.tv)
# Copyright (C) 2018-present Team LibreELEC (https://libreelec.tv)

msg_color() {
  echo $(
    cd "${ROOT}"
    PROJECT=Generic ARCH=x86_64 . config/options ""
    echo $(print_color "$1" "$2")
  )
}

msg_warn() {
  msg_color CLR_WARNING "$1"
}

msg_error() {
  msg_color CLR_ERROR "$1"
}

msg_info() {
  echo "$1"
}

git_clone() {
  # git_clone https://repo.url branch ./target_dir [githash]
  echo "[mkpkg] Checking out $1 ..."
  if [ ! -d "$3" ]; then
    git clone "$1" "$3"
    # Try to switch to specified branch if it exist, if not then use default branch
    if [ -n "$2" ]; then
      cd "$3"
      git checkout $2 >/dev/null 2>/dev/null
      cd ..
    fi
  else
    if [ -d "$3" ] ; then
      cd "$3"
      git checkout $2 >/dev/null 2>/dev/null
      git pull
      cd ..
    fi
  fi

  if [ ! -z "$4" ] ; then
    cd "$3"
    git fetch >/dev/null 2>/dev/null
    git branch -D $4 >/dev/null 2>/dev/null
    git checkout $4 >/dev/null 2>/dev/null
    git checkout -b ref-$4 >/dev/null 2>/dev/null
    cd ..
  fi
}

get_pkg_var() {
  local pkg_name="$1" pkg_var="$2"
  cd "${ROOT}"
  PROJECT=Generic ARCH=x86_64 source config/options ${pkg_name} &>/dev/null
  echo "${!pkg_var}"
}

resolve_hash() {
  if [ -d "$1" ] ; then
    cd "$1"
    git rev-parse $2 2>/dev/null
  fi
}

resolve_tag() {
  if [ -d "$1" ] ; then
    cd "$1"
    git describe --abbrev=0 --tags $2 2>/dev/null
  fi
}

check_package_excluded() {
  local package="$1" local packages_to_exclude="$2" pkg
  [ -z "${package}" -o -z "${packages_to_exclude}" ] && return 1
  if [[ ${packages_to_exclude} =~ (^|[[:space:]])${package}($|[[:space:]]) ]]; then
    msg_info "SKIPPING excluded package ${package}"
    return 0
  fi
  return 1
}

set_pkg_version() {
  local package_mk="$1/package.mk" pkg_version="$2"
  sed -e "s|PKG_VERSION=.*|PKG_VERSION=\"${pkg_version}\"|g" -i "${package_mk}"
}

download_pkg_file() {
  local pkg_name="$1"
  local pkg_url=$(get_pkg_var "${pkg_name}" PKG_URL)
  wget -q -O "${TMP_PKG_FILE}" "${pkg_url}"
}

extract_pkg_file() {
  mkdir -p "${TMP_PKG_DIR}"
  tar xf "${TMP_PKG_FILE}" --strip-components=1 -C "${TMP_PKG_DIR}"
}

cleanup_pkg_tmp() {
  rm -rf "${TMP_PKG_FILE}" "${TMP_PKG_DIR}"
}

set_pkg_sha256() {
  local package_mk="$1/package.mk"
  local new_sha256=$(sha256sum < "${TMP_PKG_FILE}" | awk '{print $1}')
  sed -e "s|PKG_SHA256=.*|PKG_SHA256=\"${new_sha256}\"|g" -i "${package_mk}"
}

bump_pkg_rev() {
  local package_mk="$1/package.mk" pkg_name="$2"
  local pkg_rev=$(get_pkg_var "${pkg_name}" PKG_REV)
  local new_pkg_rev=$((${pkg_rev}+1))

  sed -e "s|PKG_REV=.*|PKG_REV=\"${new_pkg_rev}\"|" -i "${package_mk}"
  msg_info "BUMPED ${pkg_name} PKG_REV from ${pkg_rev} to ${new_pkg_rev}"
}

update_pkg() {
  local pkg_path="$1" pkg_name="$2" pkg_version="$3"

  local old_version pkg_url new_sha256 pkg_rev

  old_version=$(get_pkg_var "${pkg_name}" PKG_VERSION)

  if [ "${old_version}" != "${pkg_version}" ]; then
    [ -n "${pkg_version}" ] && set_pkg_version "${pkg_path}" "${pkg_version}"

    download_pkg_file "${pkg_name}"
    set_pkg_sha256 "${pkg_path}"

    if [ "${BUMP_PKG_REV}" = "yes" ]; then
      bump_pkg_rev "${pkg_path}" "${pkg_name}"
    fi
  fi
}

update_to_latest_tag() {
  local pkg_path="$1" pkg_name="$2" repo="$3" branch="$4" ref="$5"
  local gitdir=${pkg_name}.git
  local resolved_version

  git_clone "${repo}" "${branch}" "${gitdir}" "${ref}"

  resolved_version=$(resolve_tag "${gitdir}" "${ref}")
  if [ -z "${resolved_version}" ]; then
    echo "========================================================================"
    msg_warn "WARNING: no tag found for package ${pkg_name}, falling back to HEAD"
    echo "========================================================================"
    resolved_version=$(resolve_hash "${gitdir}" "${ref}")
  fi

  echo "Resolved version for ${pkg_name}: ${ref} => ${resolved_version}"

  update_pkg "${pkg_path}" "${pkg_name}" "${resolved_version}"

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

# Get url in git:// notation for a package.mk, assuming it is a github.com url
# Return 1 if not a github domain
geturl() {
  local addon="$1"
  local domain owner repo PKG_URL

  PKG_URL="$(get_pkg_var ${addon} PKG_URL)"

  domain="$(echo "${PKG_URL}" | cut -d/ -f3)"
  [ "${domain}" = "github.com" ] || return 1

  owner="$(echo "${PKG_URL}" | cut -d/ -f4)"
  repo="$(echo "${PKG_URL}" | cut -d/ -f5)"

  echo "git://${domain}/${owner}/${repo}.git"
  return 0
}

# For the specified addon, verify that the package url
# matches the url retrieved from Kodi
validate_pkg_url() {
  local addon="$1" url1="$2"
  local domain owner repo url2

  domain="$(echo "${url1}" | cut -d/ -f3)"
  owner="$(echo "${url1}" | cut -d/ -f4)"
  repo="$(echo "${url1}" | cut -d/ -f5)"

  url1="git://${domain}/${owner}/${repo}.git"
  url2="$(geturl "${addon}")"

  [ "${url1}" = "${url2}" ] && return 0 || return 1
}
 

