package main

import (
	"fmt"
	"os"
	"strings"

	"gensokyo.uk/nix"
)

func formatInstallable(name string, installable *string, flagNixOS bool, args []string) error {
	if len(args) != 1 {
		return commandHandlerError(name + " requires exactly 1 argument")
	}

	*installable = args[0]
	if !flagNixOS {
		return nil
	}

	fields := strings.SplitN(*installable, "#", 2)
	switch len(fields) {
	case 2:
		*installable = nix.InstallableNixOS(fields[0], fields[1])
		return nil
	case 1:
		hostname, err := os.Hostname()
		if err != nil {
			return commandHandlerError(fmt.Sprintf("cannot get hostname: %v", err))
		}
		*installable = nix.InstallableNixOS(fields[0], hostname)
		return nil
	default:
		return commandHandlerError("unexpected installable")
	}
}

func replaceFromEnviron(v map[string]*string) error {
	for key, p := range v {
		if *p != "env" {
			continue
		}

		if s, ok := os.LookupEnv(key); !ok {
			return commandHandlerError(key + " not set")
		} else {
			*p = s
		}
	}

	return nil
}
