#!/bin/sh

. "${GITHUB_ACTION_PATH}/scripts/utils.sh"

repo_info() {
  curl -X GET \
    -H "Authorization: token $GITHUB_TOKEN" \
    -H 'Accept: application/json' \
    "$GITHUB_API_URL/repos/$GITHUB_REPOSITORY"
}

in_private_repo() {
  test "$(repo_info | jq --raw-output '.private')" = 'true'
}

default_branch() {
  repo_info | jq --raw-output '.default_branch'
}

# USAGE: base_report_url <BASE_BRANCH>
base_report_url() {
  curl -X 'GET' \
    "$GITHUB_API_URL/repos/$GITHUB_REPOSITORY/actions/tasks" \
    -H "Authorization: token $GITHUB_TOKEN" \
    -H 'Accept: application/json' |
    jq --raw-output \
      --arg name "$JOB_NAME" \
      --arg head_branch "$1" \
      '[.workflow_runs[] | select(.name == $name and .head_branch == $head_branch)] | first | .url'
}

# USAGE: has_report <REPORT_URL>
has_report() {
  http_code=$(curl -X 'GET' -o /dev/null --silent -Iw '%{http_code}' \
    "$1" -H "Authorization: token $GITHUB_TOKEN")
  log "Got code $http_code for $1"
  test "$http_code" = '200'
}

# If a base branch is not provided, use the default branch
base_branch=${BASE_BRANCH:-$(default_branch)}

if [ "$(in_private_repo)" != 'true' ] && [ "$JOB_NAME" ]; then
  url=$(base_report_url "$base_branch")

  log "Found previous run at: $url"
  report_url="$url/artifacts/$ARTIFACT_NAME"

  if has_report "$report_url"; then
    log 'Found previous report, downloading...'
    curl -X 'GET' \
      "$report_url" \
      -H "Authorization: token $GITHUB_TOKEN" |
      gunzip >old-report.json
    log "Reporting on sizes and comparing to sizes in $base_branch"
    exit 0
  fi
  error "Failed to find previous report, expected at: $report_url"
fi

warn "Couldn't retrieve old report:"
warn '    This usuially happens when running on private repos'
warn '    or when job-name is not set.'
warn
warn '    See the README for more details'

error "Falling back to slow method (checkout $base_branch and generate the report)"

old=$(mktemp -d)
group "Download files from $base_branch"
curl -X 'GET' \
  "$GITHUB_API_URL/repos/$GITHUB_REPOSITORY/archive/$base_branch.tar.gz" \
  -H "Authorization: token $GITHUB_TOKEN" |
  tar -zvx --strip-components=1 -C "$old"
endgroup

(cd "$old" && "$GITHUB_ACTION_PATH/scripts/create-report.sh" old-report.json)

exit 0
