package main

import (
	"io"
	"net/http"
	"net/url"
	"os"
	"path"
)

func fwd_request(w http.ResponseWriter, r *http.Request, fwd string) {
	if u, err := url.Parse(fwd); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	} else {
		var user, pass string
		if u.User != nil {
			user = u.User.Username()
			pass, _ = u.User.Password()
			u.User = nil
		}
		if v, exists := os.LookupEnv("FICCLOUD_USER"); exists {
			user = v
		} else if v, exists := os.LookupEnv("FICCLOUD_PASS"); exists {
			pass = v
		}

		u.Path = path.Join(u.Path, r.URL.Path)

		if r, err := http.NewRequest(r.Method, u.String(), r.Body); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		} else {
			if len(user) != 0 || len(pass) != 0 {
				r.SetBasicAuth(user, pass)
			}

			if resp, err := http.DefaultClient.Do(r); err != nil {
				http.Error(w, err.Error(), http.StatusBadGateway)
			} else {
				defer resp.Body.Close()

				for key := range resp.Header {
					w.Header().Add(key, resp.Header.Get(key))
				}
				w.WriteHeader(resp.StatusCode)

				io.Copy(w, resp.Body)
			}
		}
	}
}
