#!/bin/sh
set -eu

# Add HostnameCloak field to config.Server struct
sed -i '/^\tHostname string$/a\\tHostnameCloak string' config/config.go

# Add HostnameCloak to raw config parsing struct
sed -i '/Hostname.*scfg:"hostname"/a\\tHostnameCloak       string     `scfg:"hostname-cloak"`' config/config.go

# Add HostnameCloak parsing in Load()
sed -i '/srv\.Hostname = raw\.Hostname/,/^	}$/{
/^	}$/a\\tif raw.HostnameCloak != "" {\n\t\tsrv.HostnameCloak = raw.HostnameCloak\n\t}
}' config/config.go

# Add HostnameCloak field to runtime Config struct in server.go
sed -i '/^\tHostname .*string$/a\\tHostnameCloak             string' server.go

# Add HostnameCloak to config mapping in cmd/soju/main.go
sed -i '/Hostname:.*raw\.Hostname,$/a\\t\tHostnameCloak:             raw.HostnameCloak,' cmd/soju/main.go

# Override hostname with cloak in downstream.go
sed -i 's/if host, _, err := net.SplitHostPort(remoteAddr); err == nil {/if cloak := dc.srv.Config().HostnameCloak; cloak != "" {\n\t\tdc.hostname = cloak\n\t} else if host, _, err := net.SplitHostPort(remoteAddr); err == nil {/' downstream.go
