#!/usr/bin/env bash

# This script fetches the glfw sources from upstream and verifies that the files
# committed are the same.

# Files we don't want in the downstream go-gl/glfw repository.
# Users can get these from upstream if needed.
excludes=(
  --exclude=glfw-*/.appveyor.yml
  --exclude=glfw-*/.github
  --exclude=glfw-*/.gitignore
  --exclude=glfw-*/.mailmap
  --exclude=glfw-*/.travis.yml
  --exclude=glfw-*/*.in
  --exclude=glfw-*/CMake
  --exclude=glfw-*/CMakeLists.txt
  --exclude=glfw-*/docs
  --exclude=glfw-*/examples
  --exclude=glfw-*/README.md
  --exclude=glfw-*/CONTRIBUTORS.md
  --exclude=glfw-*/src/*.in
  --exclude=glfw-*/src/CMakeLists.txt
  --exclude=glfw-*/tests
)

set -e

grab-upstream() {
  local godir=$1
  if [[ ! -d "$godir" ]]; then
    echo "Run with top-level directory as working directory." 1>&2
    exit 1
  fi
  local rev="$(cat "$godir"/GLFW_C_REVISION.txt)"
  local target=$godir/glfw

  rm -r "$target"
  mkdir "$target"

  curl -s -L "https://github.com/glfw/glfw/archive/${rev}.tar.gz" |
    tar xz \
      --strip-components=1 \
      --directory="$target" \
      "${excludes[@]}"

  # Place a dummy go file in each directory.
  find "$target/deps" "$target/include" "$target/src" -type d -print0 |
    while IFS= read -r -d $'\0' D
  do
    cat > "$D"/dummy.go <<EOF
//go:build required
// +build required

// Package dummy prevents go tooling from stripping the c dependencies.
package dummy
EOF
  done
}

# v3.3
{
  grab-upstream v3.3/glfw

  cat > v3.3/glfw/glfw/deps/dummy.go <<EOF
//go:build required
// +build required

// Package dummy prevents go tooling from stripping the c dependencies.
package dummy

import (
	// Prevent go tooling from stripping out the c source files.
	_ "github.com/go-gl/glfw/v3.3/glfw/glfw/deps/glad"
	_ "github.com/go-gl/glfw/v3.3/glfw/glfw/deps/mingw"
	_ "github.com/go-gl/glfw/v3.3/glfw/glfw/deps/vs2008"
)
EOF

  scripts/generate-wayland-protocols.sh ./v3.3/glfw/glfw/src
  sed -i 's|/\* Generated by wayland-scanner .* \*/|/* Generated by wayland-scanner */|' \
    ./*/glfw/glfw/src/wayland-*
  
  go generate ./v3.3/glfw/glfw_tree_rebuild.go
}

if test -n "$(git status --porcelain ./*/glfw)"; then

  git status ./*/glfw

  {
    echo
    echo "Tree is dirty after fetching GLFW_C_REVISION from upstream."
    echo
    echo "To fix this:"
    echo "  1. Update GLFW_C_REVISION.txt, then:"
    echo "  2. Run scripts/grab-upstream.sh from the top-level directory"
    echo "  3. Submit the result as a pull request"
    echo
    echo "If you must apply patches, please do it in grab-upstream.sh so that"
    echo "these patches are described programmatically."
    echo
  } 1>&2
  exit 1
fi
