# 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="${PROJECT:-Generic}" ARCH="${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 target_dir [branch]
  echo "[mkpkg] Checking out $1 ..."
  if [ ! -d "$2" ]; then
    git clone "$1" "$2"
  else
    cd "$2"
    git fetch
    cd ..
  fi
  if [ -n "$3" ]; then
    cd "$2"
    git checkout -q origin/"$3";
    cd ..
  fi
}

get_pkg_var() {
  local pkg_name="$1" pkg_var="$2"
  cd "${ROOT}"
  PROJECT="${PROJECT:-Generic}" ARCH="${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_hash_in_branch() {
  if [ -d "$1" ] ; then
    cd "$1"
    git rev-parse "origin/$2" 2>/dev/null
  fi
}

resolve_hash_on_gh() {
  curl -s -L -H "Authorization: token ${GITHUB_API_TOKEN}" \
    -H "Accept: application/vnd.github.VERSION.sha" \
    "${1/*github.com/https:\/\/api.github.com\/repos}/commits/$2"
}

resolve_tag_in_branch() {
  local tag tags
  if [ -d "$1" ] ; then
    cd "$1"
    tag=$(git describe --abbrev=0 --tags "origin/$2" 2>/dev/null)
    if [ -z "${tag}" ]; then
      return
    fi
    tags=( $(git tag --points-at "${tag}" | sort -r -n) )
    if [ $# -eq 3 -a ${#tags[@]} -gt 1 ]; then
      for tag in "${tags[@]}"; do
        if [[ "${tag}" =~ $3 ]]; then
          echo "$tag"
          return
        fi
      done
    fi
    echo "${tags[0]}"
  fi
}

resolve_tag_on_gh() {
  local tag

  local QUERY=$(tr '\n' ' ' <<EOF
{
  repository(owner: \\"${1}\\", name: \\"${2}\\") {
    refs(refPrefix: \\"refs/tags/\\", first: 100, orderBy: {field: TAG_COMMIT_DATE, direction: DESC}) {
      edges {
        node {
          name
       }
      }
    }
  }
}
EOF
)

  tag=$(curl -s -L -H 'Content-Type: application/json' \
          -H "Authorization: bearer ${GITHUB_API_TOKEN}" \
          -X POST -d "{ \"query\": \"${QUERY}\" }" https://api.github.com/graphql | \
          jq -r '[.data.repository.refs.edges[] | select(.node.name | contains("'${3}'"))][0].node.name | select (.!=null)')

  echo "${tag}"
}

check_package_excluded() {
  local package="$1" 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
}

# args: path var value
set_pkg_var() {
  local package_mk="$1/package.mk" pkg_var="$2" pkg_value="$3"
  sed -e "s|${pkg_var}=.*|${pkg_var}=\"${pkg_value}\"|" -i "${package_mk}"
}

set_pkg_version() {
  set_pkg_var "$1" "PKG_VERSION" "$2"
}

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 new_sha256=$(sha256sum < "${TMP_PKG_FILE}" | awk '{print $1}')
  set_pkg_var "$1" "PKG_SHA256" "${new_sha256}"
}

bump_pkg_rev() {
  local pkg_name="$2"
  local pkg_rev=$(get_pkg_var "${pkg_name}" PKG_REV)
  local new_pkg_rev=$((pkg_rev+1))
  set_pkg_var "$1" "PKG_REV" "${new_pkg_rev}"

  msg_info "BUMPED ${pkg_name} PKG_REV from ${pkg_rev} to ${new_pkg_rev}"
}

reset_pkg_rev() {
  local pkg_name="$2"
  local pkg_rev=$(get_pkg_var "${pkg_name}" PKG_REV)
  local new_pkg_rev="1"
  set_pkg_var "$1" "PKG_REV" "${new_pkg_rev}"

  msg_info "RESET ${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}"

    msg_info "UPDATED ${pkg_name} from ${old_version} to ${pkg_version}"

    return 0
  else
    return 1
  fi
}

update_pkg_and_url() {
  local pkg_path="$1" pkg_name="$2" pkg_version="$3" pkg_url="$4"
  local old_version old_url new_sha256
  local changed=0

  old_url=$(grep "^PKG_URL=" "${pkg_path}/package.mk" | sed -e 's|^PKG_URL="||' -e 's|"$||')

  if [ "${old_url}" != "${pkg_url}" ]; then
    set_pkg_var "${pkg_path}" "PKG_URL" "${pkg_url}"
    msg_info "CHANGED ${pkg_name} PKG_URL from ${old_url} to ${pkg_url}"
    changed=1
  fi

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

  if [ "${old_version}" != "${pkg_version}" ]; then
    set_pkg_var "${pkg_path}" "PKG_VERSION" "${pkg_version}"
    msg_info "UPDATED ${pkg_name} from ${old_version} to ${pkg_version}"
    changed=1
  fi

  if [ $changed -eq 1 ]; then
    download_pkg_file "${pkg_name}"
    set_pkg_sha256 "${pkg_path}"

    return 0
  else
    return 1
  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
}

# Get user Github token if available
get_gh_token() {
  if [ -z "${GITHUB_API_TOKEN}" ]; then
    GITHUB_API_TOKEN=$(get_pkg_var "" GITHUB_API_TOKEN)
  fi
}
