package common

import (
	"fmt"
	"os"
	"os/exec"
	"strings"
)

const tempPath = "/tmp/cron_rule.temp"

func AddCronCommand(cronStr, cmd string) error {
	e := exec.Command("crontab", "-l")
	out, err := e.CombinedOutput()
	if err != nil &&
		!strings.Contains(string(out), "no crontab") {
		return err
	}
	f, err := os.OpenFile(tempPath, os.O_TRUNC|os.O_CREATE|os.O_RDWR, 0744)
	if err != nil {
		return err
	}
	defer f.Close()
	if !strings.Contains(string(out), "no crontab") {
		_, err := f.WriteString(string(out))
		if err != nil {
			return err
		}
	}
	cmd = fmt.Sprintf("%s %s", cronStr, cmd)
	_, err = f.WriteString(cmd)
	if err != nil {
		return err
	}
	return RunCommandStd("crontab", tempPath)
}
