// Copyright 2022, 2023 Chainguard, Inc.
//
// 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 s6

import (
	"context"
	"fmt"
	"path/filepath"

	"github.com/chainguard-dev/clog"
)

func (sc *Context) WriteSupervisionTree(ctx context.Context, services Services) error {
	log := clog.FromContext(ctx)
	log.Debug("generating supervision tree")

	// generate the leaves
	for service, svccmd := range services {
		svcdir := filepath.Join("sv", service)
		if err := sc.fs.MkdirAll(svcdir, 0777); err != nil {
			return fmt.Errorf("could not make supervision directory: %w", err)
		}

		if err := sc.fs.WriteFile(filepath.Join(svcdir, "run"), []byte(fmt.Sprintf("#!/bin/execlineb\n%s\n", svccmd)), 0755); err != nil {
			return fmt.Errorf("could not write runfile: %w", err)
		}
	}

	return nil
}
