// cmdScriptParse serviced script parse filename
494792
func (c *ServicedCli) cmdScriptParse(ctx *cli.Context) {
	args := ctx.Args()
	if len(args) != 1 {
		fmt.Fprintf(os.Stderr, "Incorrect Usage.\n\n")
		return
	}
	fileName := args[0]
	config := script.Config{}
	err := c.driver.ScriptParse(fileName, &config)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
	}
	return
}
123886
func Parse() string {
	selected := MustParse(CommandLine.Parse(os.Args[1:]))
	if selected == "" && CommandLine.cmdGroup.have() {
		Usage()
		CommandLine.terminate(0)
	}
	return selected
}
639646
func (c *ServicedCli) serviceCommands(id string) (data []string) {
	svc, err := c.driver.GetService(id)
	if err != nil || svc == nil {
		c.exit(1)
		return
	}

	data = make([]string, len(svc.Commands))
	i := 0
	for r := range svc.Commands {
		data[i] = r
		i++
	}

	return
}
564564
func extractScript(p *Provisioner) (string, error) {
	temp, err := tmp.File("powershell-provisioner")
	if err != nil {
		return "", err
	}
	defer temp.Close()
	writer := bufio.NewWriter(temp)
	for _, command := range p.config.Inline {
		log.Printf("Found command: %s", command)
		if _, err := writer.WriteString(command + "\n"); err != nil {
			return "", fmt.Errorf("Error preparing powershell script: %s", err)
		}
	}

	if err := writer.Flush(); err != nil {
		return "", fmt.Errorf("Error preparing powershell script: %s", err)
	}

	return temp.Name(), nil
}
685475
func (c *ServicedCli) cmdServiceVariableGet(ctx *cli.Context) {
	args := ctx.Args()
	if len(args) < 2 {
		fmt.Printf("Incorrect Usage.\n\n")
		cli.ShowCommandHelp(ctx, "get")
		return
	}

	svcDetails, _, err := c.searchForService(args[0], ctx.Bool("no-prefix-match"))
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		return
	}

	service, err := c.driver.GetService(svcDetails.ID)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		return
	}

	key := args[1]
	if service.Context == nil {
		message := fmt.Sprintf("Variable %v not found.", key)
		fmt.Fprintln(os.Stderr, message)
		return
	}

	if value, found := service.Context[key]; found {
		switch value.(type) {
		case string:
			if vstr, ok := value.(string); ok {
				fmt.Printf("%v\n", vstr)
			}
		case int64:
			if vstr, ok := value.(string); ok {
				fmt.Printf("%v\n", vstr)
			}
		case uint64:
			if vstr, ok := value.(string); ok {
				fmt.Printf("%v\n", vstr)
			}
		}
	} else {
		message := fmt.Sprintf("Variable %v not found.", key)
		fmt.Fprintln(os.Stderr, message)
		return
	}
}
428258
func (c *ServicedCli) cmdServiceAttach(ctx *cli.Context) error {
	// verify args
	args := ctx.Args()
	if len(args) < 1 {
		if !ctx.Bool("help") {
			fmt.Fprintf(os.Stderr, "Incorrect Usage.\n\n")
		}
		cli.ShowSubcommandHelp(ctx)
		c.exit(1)
		return nil
	}

	// Bash completion
	if args[len(args)-1] == "--generate-bash-completion" {
		// CC-892: The attach command does not require an additional argument after
		// SERVICE_ID. Disable bash completion after SERVICE_ID.
		return c.exit(1)
	}

	svc, instanceID, err := c.searchForService(ctx.Args().First(), ctx.Bool("no-prefix-match"))
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		c.exit(1)
		return err
	}

	if instanceID < 0 {
		instanceID = 0
	}
	command := ""
	argv := []string{}
	if len(args) > 1 {
		command = args[1]
		argv = args[2:]
	}

	if err := c.driver.AttachServiceInstance(svc.ID, instanceID, command, argv); err != nil {
		fmt.Fprintln(os.Stderr, err)
		c.exit(1)
		return err
	}
	return nil
}
1317112
func ParseFile(filename string) (string, error) {
	bs, err := ioutil.ReadFile(filename)
	if err != nil {
		return "", err
	}
	return Parse(filepath.Base(filename), bs)
}
139153
func (c *ServicedCli) cmdServiceSnapshot(ctx *cli.Context) {
	nArgs := len(ctx.Args())
	if nArgs < 1 {
		fmt.Printf("Incorrect Usage.\n\n")
		cli.ShowCommandHelp(ctx, "snapshot")
		c.exit(1)
		return
	}

	description := ""
	if nArgs <= 3 {
		description = ctx.String("description")
	}

	svc, _, err := c.searchForService(ctx.Args().First(), ctx.Bool("no-prefix-match"))
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		c.exit(1)
		return
	}

	//get the tags (if any)
	tag := ctx.String("tag")

	cfg := api.SnapshotConfig{
		ServiceID: svc.ID,
		Message:   description,
		Tag:       tag,
	}
	if snapshot, err := c.driver.AddSnapshot(cfg); err != nil {
		fmt.Fprintln(os.Stderr, err)
		c.exit(1)
	} else if snapshot == "" {
		fmt.Fprintln(os.Stderr, "received nil snapshot")
		c.exit(1)
	} else {
		fmt.Println(snapshot)
	}
	return
}
1045533
func (c *ServicedCli) cmdSnapshotList(ctx *cli.Context) {
	showTags := ctx.Bool("show-tags")
	var (
		snapshots []dao.SnapshotInfo
		err       error
	)
	if len(ctx.Args()) > 0 {
		serviceID := ctx.Args().First()
		if snapshots, err = c.driver.GetSnapshotsByServiceID(serviceID); err != nil {
			fmt.Fprintln(os.Stderr, err)
			return
		}
	} else {
		if snapshots, err = c.driver.GetSnapshots(); err != nil {
			fmt.Fprintln(os.Stderr, err)
			return
		}
	}

	if snapshots == nil || len(snapshots) == 0 {
		fmt.Fprintln(os.Stderr, "no snapshots found")
	} else {
		if showTags { //print a table of snapshot, description, tag list
			t := NewTable("Snapshot,Description,Tags")
			for _, s := range snapshots {
				//build a comma-delimited list of the tags
				tags := strings.Join(s.Tags, ",")
				snapshotID := s.SnapshotID
				if s.Invalid {
					snapshotID += " [DEPRECATED]"
				}

				//make the row and add it to the table
				row := make(map[string]interface{})
				row["Snapshot"] = snapshotID
				row["Description"] = s.Description
				row["Tags"] = tags
				t.Padding = 6
				t.AddRow(row)
			}
			//print the table
			t.Print()
		} else { //just print a list of snapshots
			for _, s := range snapshots {
				fmt.Println(s)
			}
		}
	}
	return
}
300049
func (c *ServicedCli) cmdServiceSetIP(ctx *cli.Context) {
	args := ctx.Args()
	if len(args) < 3 {
		fmt.Printf("Incorrect Usage.\n\n")
		cli.ShowCommandHelp(ctx, "set-ip")
		c.exit(1)
		return
	}

	if args[len(args)-1] == "--generate-bash-completion" {
		// CC-892: Disable bash completion after SERVICE_ID because possible matches
		// are unavailable outside the container.
		return
	}

	svc, _, err := c.searchForService(ctx.Args().First(), ctx.Bool("no-prefix-match"))
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		c.exit(1)
		return
	}

	var endpointName string
	if len(args) > 1 {
		endpointName = args[1]
	}

	var ipAddress string
	if len(args) > 2 {
		ipAddress = args[2]
	}

	if ctx.Int("port") < 1 {
		fmt.Printf("Please specify the valid port number.\n\n")
		cli.ShowCommandHelp(ctx, "set-ip")
		c.exit(1)
		return
	}

	if ctx.String("proto") == "" {
		fmt.Printf("Please specify port protocol.\n\n")
		cli.ShowCommandHelp(ctx, "set-ip")
		c.exit(1)
		return
	}

	cfg := api.IPConfig{
		ServiceID:    svc.ID,
		IPAddress:    ipAddress,
		Port:         uint16(ctx.Int("port")),
		Proto:        ctx.String("proto"),
		EndpointName: endpointName,
	}

	if err := c.driver.SetIP(cfg); err != nil {
		fmt.Fprintln(os.Stderr, err)
		c.exit(1)
	}
	return
}
544492
func (service *Service) ServeFiles(path, filename string) error {
	ctrl := service.NewController("FileServer")
	return ctrl.ServeFiles(path, filename)
}
1049928
func (po *Po) ParseFile(f string) {
	// Check if file exists
	info, err := os.Stat(f)
	if err != nil {
		return
	}

	// Check that isn't a directory
	if info.IsDir() {
		return
	}

	// Parse file content
	data, err := ioutil.ReadFile(f)
	if err != nil {
		return
	}

	po.Parse(data)
}
1323623
func (b *UpdateService) ScriptFile(scriptFile string) *UpdateService {
	b.scriptFile = scriptFile
	return b
}
358059
func (c *Command) Parse(params []CommandInfoParam) ([]internal.ReflectManagedMethodExecuterSoapArgument, error) {
	flags := flag.NewFlagSet(strings.Join(c.name, " "), flag.ExitOnError)
	vals := make([]string, len(params))

	for i, p := range params {
		v := &vals[i]
		for _, a := range p.Aliases {
			a = strings.TrimPrefix(a[1:], "-")
			flags.StringVar(v, a, "", p.Help)
		}
	}

	err := flags.Parse(c.args)
	if err != nil {
		return nil, err
	}

	args := []internal.ReflectManagedMethodExecuterSoapArgument{}

	for i, p := range params {
		if vals[i] == "" {
			continue
		}
		args = append(args, c.Argument(p.Name, vals[i]))
	}

	return args, nil
}
145508
func (c *ServicedCli) cmdTemplateAdd(ctx *cli.Context) {
	var input *os.File

	if filepath := ctx.Args().First(); filepath != "" {
		var err error
		if input, err = os.Open(filepath); err != nil {
			fmt.Fprintln(os.Stderr, err)
			return
		}
		defer input.Close()
	} else {
		input = os.Stdin
	}

	if template, err := c.driver.AddServiceTemplate(input); err != nil {
		fmt.Fprintln(os.Stderr, err)
	} else if template == nil {
		fmt.Fprintln(os.Stderr, "received nil template")
	} else {
		fmt.Println(template.ID)
	}
}
1278344
func (c *ServicedCli) cmdTemplateCompile(ctx *cli.Context) {
	args := ctx.Args()
	if len(args) < 1 {
		fmt.Printf("Incorrect Usage.\n\n")
		cli.ShowCommandHelp(ctx, "compile")
		return
	}

	cfg := api.CompileTemplateConfig{
		Dir: args[0],
		Map: *ctx.Generic("map").(*api.ImageMap),
	}

	if template, err := c.driver.CompileServiceTemplate(cfg); err != nil {
		fmt.Fprintln(os.Stderr, err)
	} else if template == nil {
		fmt.Fprintln(os.Stderr, "received nil template")
	} else {
		cmd := fmt.Sprintf("cd %s && git rev-parse HEAD", args[0])
		commit, err := exec.Command("sh", "-c", cmd).Output()
		if err != nil {
			commit = []byte("unknown")
		}
		cmd = fmt.Sprintf("cd %s && git config --get remote.origin.url", args[0])
		repo, err := exec.Command("sh", "-c", cmd).Output()
		if err != nil {
			repo = []byte("unknown")
		}
		cmd = fmt.Sprintf("cd %s && git rev-parse --abbrev-ref HEAD", args[0])
		branch, err := exec.Command("sh", "-c", cmd).Output()
		if err != nil {
			branch = []byte("unknown")
		}
		cmd = fmt.Sprintf("cd %s && git describe --always", args[0])
		tag, err := exec.Command("sh", "-c", cmd).Output()
		if err != nil {
			tag = []byte("unknown")
		}
		templateVersion := map[string]string{
			"repo":   strings.Trim(string(repo), "\n"),
			"branch": strings.Trim(string(branch), "\n"),
			"tag":    strings.Trim(string(tag), "\n"),
			"commit": strings.Trim(string(commit), "\n"),
		}
		mTemplate := metaTemplate{*template, servicedversion.GetVersion(), templateVersion}
		jsonTemplate, err := json.MarshalIndent(mTemplate, " ", "  ")
		if err != nil {
			fmt.Fprintf(os.Stderr, "failed to marshal template: %s\n", err)
		} else {
			fmt.Println(string(jsonTemplate))
		}
	}
}
174933
func (c *ServicedCli) cmdTemplateDeploy(ctx *cli.Context) {
	args := ctx.Args()
	if len(args) < 3 {
		fmt.Printf("Incorrect Usage.\n\n")
		cli.ShowCommandHelp(ctx, "deploy")
		return
	}

	cfg := api.DeployTemplateConfig{
		ID:              args[0],
		PoolID:          args[1],
		DeploymentID:    args[2],
		ManualAssignIPs: ctx.Bool("manual-assign-ips"),
	}

	fmt.Fprintln(os.Stderr, "Deploying template - please wait...")
	if svcs, err := c.driver.DeployServiceTemplate(cfg); err != nil {
		fmt.Fprintln(os.Stderr, err)
	} else if svcs == nil {
		fmt.Fprintln(os.Stderr, "received nil service definition")
	} else {
		for _, svc := range svcs {
			fmt.Println(svc.ID)
		}
	}
}