#!/usr/bin/env bash

if [[ $EUID -eq 0 ]]; then
  echo "dev cannot be run as root or with sudo"
  exit 1
fi

set -euo pipefail

# Bump this counter to force rebuilding `dev` on all machines.
DEV_VERSION=106

THIS_DIR=$(cd "$(dirname "$0")" && pwd)
BINARY_DIR=$THIS_DIR/bin/dev-versions
BINARY_PATH=$BINARY_DIR/dev.$DEV_VERSION

if [[ -f "$BINARY_PATH" && ! -z "${DEV_FORCE_REBUILD-}" ]]; then
    rm "$BINARY_PATH"
fi

if [[ ! -f "$BINARY_PATH" ]]; then
    echo "$BINARY_PATH not found, building..."
    mkdir -p $BINARY_DIR
    bazel build //pkg/cmd/dev --norun_validations --remote_cache=
    cp $(bazel info bazel-bin --norun_validations)/pkg/cmd/dev/dev_/dev $BINARY_PATH
    # The Bazel-built binary won't have write permissions.
    chmod a+w $BINARY_PATH
fi

source "$(dirname "${0}")/tools/claim_output_base.sh" || true

cd $THIS_DIR
$BINARY_PATH "$@"
