#!/usr/bin/env bash

# This script verifies the build produced by the buildserver. It helps the user verify the staging
# repository versions and triggers a e2e run with a small subset of the tests to verify the build.
# This should be be run after `2-push-release-tag` and after the build server has finished building.

set -eu

SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
cd "$SCRIPT_DIR"

REPO_ROOT=../../../
PRODUCT_VERSION_PATH=$REPO_ROOT/dist-assets/desktop-product-version.txt
PRODUCT_VERSION=$(cat $PRODUCT_VERSION_PATH)

$REPO_ROOT/scripts/utils/gh-ready-check
$REPO_ROOT/scripts/utils/commit-verification
"$SCRIPT_DIR/verify-version-is-release"

source $REPO_ROOT/scripts/utils/log

WAIT="false"

for argument in "$@"; do
    case "$argument" in
        --wait)
          WAIT="true"
          ;;
        *)
            log_error "Unknown option \"$argument\""
            exit 1
            ;;
    esac
done

function verify_repository_versions {
  print_versions_args=( --staging )

  if [[ "$PRODUCT_VERSION" == *-beta* ]]; then
    print_versions_args+=( --beta )
  fi

  deb_product_version=${PRODUCT_VERSION/-/\~}
  deb_version_output=$(./print-package-versions --deb "${print_versions_args[@]}")
  for arch in amd64 arm64; do
    if ! echo "$deb_version_output" | grep -q "^mullvad-vpn/.* $deb_product_version $arch\$"; then
      log_error "Missing or incorrect deb $arch version in repository (expected $deb_product_version)"
      echo "$deb_version_output"
      exit 1
    fi
  done

  rpm_product_version=${PRODUCT_VERSION/-/\~}-1
  rpm_version_output=$(./print-package-versions --rpm "${print_versions_args[@]}")
  for arch in x86_64 aarch64; do
    if ! echo "$rpm_version_output" | grep -q "^mullvad-vpn\.$arch .* $rpm_product_version "; then
      log_error "Missing or incorrect rpm $arch version in repository (expected $rpm_product_version)"
      echo "$rpm_version_output"
      exit 1
    fi
  done
}

function wait_for_workflow_result {
  log_header "Waiting workflow result..."
  sleep 30 # Sleep to allow the workflow run to start

  while true; do
    run=$(gh run list --workflow desktop-e2e.yml --branch "$PRODUCT_VERSION" --limit 1 --json conclusion,status,updatedAt,url | jq --exit-status '.[0]')

    status=$(echo "$run" | jq --exit-status --raw-output '.status')
    echo "Status: $status"
    if [[ "$status" != "in_progress" ]] && [[ "$status" != "queued" ]]; then
      if echo "$run" | jq --exit-status '.conclusion == "success"' > /dev/null; then
        log_success "Workflow run successfull"
        break
      else
        log_error "Workflow failed"
        exit 1
      fi
    fi

    sleep 60
  done
}

verify_repository_versions
gh workflow run desktop-e2e.yml --ref "$PRODUCT_VERSION" \
    -f oses="fedora42 ubuntu2504 windows11 macos15" \
    -f tests="test_quantum_resistant_tunnel test_ui_tunnel_settings"

if [[ "$WAIT" == "true" ]]; then
  wait_for_workflow_result
fi
