#!/usr/bin/env bash
set -eo pipefail

. scripts/grafana-server/variables

PORT=${PORT:-$DEFAULT_PORT}
ARCH=${ARCH:-$DEFAULT_ARCH}

if [ "$ARCH" ]; then
    ARCH+="/"
fi

./scripts/grafana-server/kill-server

docker ps -q --filter "name=grafana-image-renderer" | xargs docker stop || true

mkdir $RUNDIR

echo -e "Copying grafana backend files to temp dir..."

if [[ ! -f bin/"$ARCH"grafana-server ]]; then
  echo "bin/linux-amd64/grafana-server missing, trying local grafana-server binary"
fi

echo starting server

# air now deletes the binary, so we check if we need to build it before trying to start the server
# see https://github.com/air-verse/air/issues/525
# if this gets resolved, we could remove the go build and rely on the binary being present as before
if [[ ! -f ./bin/"$ARCH"grafana ]]; then
  make GO_BUILD_DEV=1 build-go
fi

cp -r ./bin $RUNDIR
cp -r ./tools $RUNDIR
ln -s $(realpath ./public) $RUNDIR


mkdir $RUNDIR/conf
mkdir $PROV_DIR
mkdir $PROV_DIR/datasources
mkdir $PROV_DIR/dashboards
mkdir $PROV_DIR/alerting
mkdir $PROV_DIR/plugins

cp ./scripts/grafana-server/custom.ini $RUNDIR/conf/custom.ini
cp ./conf/defaults.ini $RUNDIR/conf/defaults.ini

echo -e "Copying custom plugins from e2e tests"

mkdir -p "$RUNDIR/data/plugins"

if [ -d "./e2e-playwright/test-plugins" ]; then
  ln -s $(realpath ./e2e-playwright/test-plugins/*) "$RUNDIR/data/plugins"
# when running in CI
elif [ -d "../e2e-playwright/test-plugins" ]; then
  cp -r "../e2e-playwright/test-plugins" "$RUNDIR/data/plugins"
fi

if [ "$START_IMAGE_RENDERER" ]; then
  echo -e "Starting image renderer container"
  docker run -d --rm --name=grafana-image-renderer -p ${IR_DEFAULT_PORT}:${IR_DEFAULT_PORT} grafana/grafana-image-renderer:${IMAGE_RENDERER_VERSION:-latest}

  if [[ "$(uname)" == "Darwin" ]]; then
    DOCKER_HOST="host.docker.internal"
    echo "Detected Mac host, using $DOCKER_HOST as the Docker host"
  else
    DOCKER_HOST="172.17.0.1"
    echo "Detected Linux host, using $DOCKER_HOST as the Docker host"
  fi
fi

echo -e "Copy provisioning setup from devenv"

cp devenv/datasources.yaml $PROV_DIR/datasources
cp devenv/dashboards.yaml $PROV_DIR/dashboards
cp devenv/alert_rules.yaml $PROV_DIR/alerting
cp devenv/plugins.yaml $PROV_DIR/plugins

cp -r devenv $RUNDIR

echo -e "Starting Grafana server port $PORT"

# We get a lot of "context canceled" errors from navigating away from pages,
# so filter them out because they're not useful
{
  CMD=(
    "$RUNDIR/bin/${ARCH}grafana" server
    --homepath="$HOME_PATH"
    --pidfile="$RUNDIR/pid"
    cfg:server.http_port="$PORT"
    cfg:enterprise.license_path="$1"
  )

  if [ "$START_IMAGE_RENDERER" ]; then
    CMD+=(
      cfg:rendering.callback_url="http://$DOCKER_HOST:$PORT"
      cfg:rendering.server_url="http://localhost:$IR_DEFAULT_PORT/render"
    )
  fi

  exec "${CMD[@]}" 2>&1
} | grep -v -i "context canceled"
