package main

import (
	"context"
	"encoding/base64"
	"fmt"
	"io"

	"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) {
		// Get user and pw from URL
		q := r.URL.Query()
		userValue := q.Get("user")
		pwValue := q.Get("pw")

		// Check if the user and pw are present
		if userValue != "" && pwValue != "" {
			// base64 encode
			basic_auth := base64.StdEncoding.EncodeToString([]byte(userValue + ":" + pwValue))
			// Set to Authorization header
			r.Header.Add("Authorization", "Basic "+basic_auth)
			// Remove user and pw from the querystring
			q.Del("user")
			q.Del("pw")
			r.URL.RawQuery = q.Encode()
		}

		// Send the request to the origin server
		resp, err := r.Send(ctx, BackendName)
		if err != nil {
			w.WriteHeader(fsthttp.StatusBadGateway)
			fmt.Fprintln(w, err.Error())
			return
		}

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