/* Copyright © 2022 Lukas Bachschwell 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 cmd import ( "os" "os/exec" "path/filepath" log "github.com/s00500/env_logger" "github.com/spf13/cobra" ) var serviceTemplate string var serviceBootLevel string // serviceCmd represents the service command var serviceCmd = &cobra.Command{ Use: "service", Short: "A brief description of your command", Long: `A longer description that spans multiple lines and likely contains examples and usage of using your command. For example: Cobra is a CLI library for Go that empowers applications. This application is a tool to generate the needed files to quickly create a Cobra application.`, Run: func(cmd *cobra.Command, args []string) { log.Println("service called") if len(args) == 0 { log.Fatal("Please specify a service name") } name := args[0] prepareWorkdir() // Make changes: // Edit the servicefile if serviceBootLevel != "" { log.Info("Setting boot level to ", serviceBootLevel) if serviceBootLevel == "none" { dirs, err := os.ReadDir(workdir + "/etc/runlevels") log.MustFatal(err) for _, dir := range dirs { log.Info("Checking ", filepath.Join(dir.Name(), name)) os.RemoveAll(filepath.Join(dir.Name(), name)) } createOutput() return } err := os.Symlink("/etc/init.d/"+name, filepath.Join(workdir, "etc", "runlevels", serviceBootLevel, name)) log.MustFatal(err) createOutput() return } err := os.MkdirAll(workdir+"/etc/init.d", 0755) log.MustFatal(err) if serviceTemplate != "" { // Copy over template file from embed fs to service location err = copyEmbeddedFile("templates/service/"+serviceTemplate, workdir+"/etc/init.d/"+name) log.MustFatal(err) } editFile(workdir + "/etc/init.d/" + name) createOutput() }, } func init() { rootCmd.AddCommand(serviceCmd) serviceCmd.Flags().StringVarP(&serviceTemplate, "template", "t", "", "Create new service from a template") serviceCmd.Flags().StringVar(&serviceBootLevel, "boot", "", "Specify a boot level, use 'none' for disable") } func editFile(path string) { editor := os.Getenv("EDITOR") if editor == "" { editor = "nano" log.Info("EDITOR: nano (default)") } else { log.Info("EDITOR: ", editor) } editC := exec.Command(editor, path) log.Debug("Calling ", editC) editC.Stdout = os.Stdout editC.Stdin = os.Stdin editC.Stderr = os.Stderr log.Should(editC.Start()) log.Should(editC.Wait()) }