package main

import (
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"
	"text/template"
)

var recoveryConfTemplate = template.Must(template.New("recovery.conf").Parse(
	`recovery_target_timeline = 'latest'
standby_mode = 'on'
primary_conninfo = 'host={{ .Master }} port=5432 user=replication application_name={{ .Localhost }}'

{{ if .Restore -}}
	restore_command = '/var/lib/postgresql/bin/restore-wal-e "%f" "%p"'
{{ end -}}
`))

func writeRecoveryConf(dataDir string, masterHost string, localHost string) error {
	recoveryConfPath := filepath.Join(dataDir, "recovery.conf")
	addRestoreCmd := false

	//If recovery.conf exists, see if it has a wal restore method in it
	if _, err := os.Stat(recoveryConfPath); err == nil {
		data, err := ioutil.ReadFile(recoveryConfPath)
		if err != nil {
			return err
		}

		dataStr := string(data)
		addRestoreCmd = strings.Contains(dataStr, "restore_command")
	}

	firstReplicaDot := strings.Index(localHost, ".")
	if firstReplicaDot >= 0 {
		localHost = localHost[0:firstReplicaDot]
	}

	file, err := os.Create(recoveryConfPath)
	defer file.Close()
	if err != nil {
		return err
	}

	err = recoveryConfTemplate.Execute(file, struct {
		Master    string
		Localhost string
		Restore   bool
	}{
		masterHost,
		localHost,
		addRestoreCmd,
	})
	if err != nil {
		return err
	}
	file.Close()

	err = os.Chmod(recoveryConfPath, 0600)
	return err
}
