/*
 * Copyright 2024 CloudWeGo Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package job

const jobTemplate = `package job

// Run is an example function job
func Run() {
	// TODO: fill with your own logic

}
`

const jobMainTemplate = `// Code generated by cwgo ({{.Version}}). DO NOT EDIT.
package main

import (
    "log"
    schedule "{{.PackagePrefix}}"
)

func main() {
    err := schedule.Run()
    if err != nil {
        log.Fatalf("job failed: %v", err)
    }
}

`

const jobScheduleTemplate = `package schedule

import (
	"sync"
    {{- range .JobInfos }}
	{{.JobName}} "{{.PackagePrefix}}/{{.JobName}}/job"
	{{- end }}
)

func Run() error {
	var wg sync.WaitGroup

	{{- range .JobInfos }}
	wg.Add(1)
	go func() {
		defer wg.Done()
		{{.JobName}}.Run()
	}()
	{{- end }}

	wg.Wait()
	return nil
}

`

const scriptTemplate = `#!/bin/bash

echo "Building job binary..."
go build -o job ../cmd/main.go

if [ $? -ne 0 ]; then
    echo "Error: Failed to build job."
    exit 1
fi

echo "Running job..."
./job

if [ $? -ne 0 ]; then
    echo "Error: job execution failed."
    exit 1
fi

echo "job Done."

rm job

if [ $? -ne 0 ]; then
    echo "Error: Failed to remove job binary."
    exit 1
fi

`
