package main

import (
  "bytes"
  "context"
  "fmt"
  "net/http"
  "os"
  "path"
  "path/filepath"
  "strings"
  "github.com/aws/aws-lambda-go/lambda"
  "github.com/aws/aws-lambda-go/events"
  php "github.com/deuill/go-php"
)

var phpScript = ""

func handler(ctx context.Context, req events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
  engine, _ := php.New()
  context, _ := engine.NewContext()

  var bodyReader = strings.NewReader(req.Body)
  var httpReq, _ = http.NewRequest(req.HTTPMethod, req.Path, bodyReader)

  for k, v := range req.Headers {
    httpReq.Header.Add(k, v)
  }

  httpReq.ParseForm()

  postMap := make(map[string]string)
  for k, v := range httpReq.PostForm {
    for _, s := range v {
      postMap[k] = s
    }
  }

  context.Bind("_POST", postMap)
  var stdout bytes.Buffer
  context.Output = &stdout
  context.Exec(phpScript)

  fmt.Printf("request!\n") // TODO remove

  headers := make(map[string]string)
  for k, v := range context.Header {
    for _, s := range v {
      headers[k] = s
    }
  }

  engine.Destroy()
  return events.APIGatewayProxyResponse { StatusCode: 200, Headers: headers, Body: stdout.String() }, nil
}

func main() {
  ex, _ := os.Executable()
  phpScript = path.Join(filepath.Dir(ex), os.Getenv("NOW_PHP_SCRIPT"))
  fmt.Printf("phpScript %s\n", phpScript)
  lambda.Start(handler)
}
