// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package cgi

import (
	
	
	
	
	
	
	
	
)

func cgiMain() {
	switch path.Join(os.Getenv("SCRIPT_NAME"), os.Getenv("PATH_INFO")) {
	case "/bar", "/test.cgi", "/myscript/bar", "/test.cgi/extrapath":
		testCGI()
		return
	}
	childCGIProcess()
}

// testCGI is a CGI program translated from a Perl program to complete host_test.
// test cases in host_test should be provided by testCGI.
func testCGI() {
	,  := Request()
	if  != nil {
		panic()
	}

	 = .ParseForm()
	if  != nil {
		panic()
	}

	 := .Form
	if .Get("loc") != "" {
		fmt.Printf("Location: %s\r\n\r\n", .Get("loc"))
		return
	}

	fmt.Printf("Content-Type: text/html\r\n")
	fmt.Printf("X-CGI-Pid: %d\r\n", os.Getpid())
	fmt.Printf("X-Test-Header: X-Test-Value\r\n")
	fmt.Printf("\r\n")

	if .Get("writestderr") != "" {
		fmt.Fprintf(os.Stderr, "Hello, stderr!\n")
	}

	if .Get("bigresponse") != "" {
		// 17 MB, for OS X: golang.org/issue/4958
		 := strings.Repeat("A", 1024)
		for  := 0;  < 17*1024; ++ {
			fmt.Printf("%s\r\n", )
		}
		return
	}

	fmt.Printf("test=Hello CGI\r\n")

	 := make([]string, 0, len())
	for  := range  {
		 = append(, )
	}
	sort.Strings()
	for ,  := range  {
		fmt.Printf("param-%s=%s\r\n", , .Get())
	}

	 := envMap(os.Environ())
	 = make([]string, 0, len())
	for  := range  {
		 = append(, )
	}
	sort.Strings()
	for ,  := range  {
		fmt.Printf("env-%s=%s\r\n", , [])
	}

	,  := os.Getwd()
	fmt.Printf("cwd=%s\r\n", )
}

type neverEnding byte

func ( neverEnding) ( []byte) ( int,  error) {
	for  := range  {
		[] = byte()
	}
	return len(), nil
}

// childCGIProcess is used by integration_test to complete unit tests.
func childCGIProcess() {
	if os.Getenv("REQUEST_METHOD") == "" {
		// Not in a CGI environment; skipping test.
		return
	}
	switch os.Getenv("REQUEST_URI") {
	case "/immediate-disconnect":
		os.Exit(0)
	case "/no-content-type":
		fmt.Printf("Content-Length: 6\n\nHello\n")
		os.Exit(0)
	case "/empty-headers":
		fmt.Printf("\nHello")
		os.Exit(0)
	}
	Serve(http.HandlerFunc(func( http.ResponseWriter,  *http.Request) {
		if .FormValue("nil-request-body") == "1" {
			fmt.Fprintf(, "nil-request-body=%v\n", .Body == nil)
			return
		}
		.Header().Set("X-Test-Header", "X-Test-Value")
		.ParseForm()
		if .FormValue("no-body") == "1" {
			return
		}
		if ,  := .Form["exact-body"];  {
			io.WriteString(, [0])
			return
		}
		if .FormValue("write-forever") == "1" {
			io.Copy(, neverEnding('a'))
			for {
				time.Sleep(5 * time.Second) // hang forever, until killed
			}
		}
		fmt.Fprintf(, "test=Hello CGI-in-CGI\n")
		for ,  := range .Form {
			for ,  := range  {
				fmt.Fprintf(, "param-%s=%s\n", , )
			}
		}
		for ,  := range os.Environ() {
			fmt.Fprintf(, "env-%s\n", )
		}
	}))
	os.Exit(0)
}