// https://developer.fastly.com/solutions/examples/set-google-analytics-_ga-cookie

package main

import (
	"context"
	"fmt"
	"io"
  "strings"
  "math/rand"
  "time"

	"github.com/fastly/compute-sdk-go/fsthttp"
)

// BackendName is the name of our service backend.
const BackendName = "origin_0"

func main() {
	fsthttp.ServeFunc(func(ctx context.Context, w fsthttp.ResponseWriter, r *fsthttp.Request) {
		// This requires your service to be configured with a backend
		// named "origin_0" and pointing to "https://http-me.glitch.me".
		
    resp, err := r.Send(ctx, BackendName)
		if err != nil {
			w.WriteHeader(fsthttp.StatusBadGateway)
			fmt.Fprintln(w, err.Error())
			return
		}

    if !strings.Contains(r.Header.Get("cookie"), "_ga") {
      // Calculate the number of domain segments.
      domainsegs := len(strings.Split(r.Header.Get("host"), "."))
      // Generate a random number between [1000000000, 2147483647]
      rnd := rand.New(rand.NewSource(time.Now().UnixNano()))
      rnum := rnd.Intn(2147483647 - 1000000000 + 1) + 1000000000

      // Assemble the Google analytics value
      ga := fmt.Sprintf("_ga=GA1.%d.%d.%d;Domain=.fiddle.fastly.dev;Max-Age=63072000;", domainsegs, rnum, time.Now().Unix())

      // Add the Google Analytics cookie.
      resp.Header.Add("set-cookie", ga)

      // Prevent browser from caching a set cookie.
      resp.Header.Set("cache-control", "no-store")
    }
    

		w.Header().Reset(resp.Header)
		w.WriteHeader(resp.StatusCode)
		io.Copy(w, resp.Body)
	})
}