package main

import (
	"bytes"
	"fmt"
	"os/exec"
	"regexp"
	"strings"
)

type SSHkey struct {
	Size        int
	Fingerprint string
	Comment     string
	Algo        string
}

func SSHkeyAnalyse(key string) (s SSHkey, err error) {
	cmd := exec.Command("ssh-keygen", "-l", "-f", "-")
	cmd.Stdin = strings.NewReader(key)

	var out bytes.Buffer
	cmd.Stdout = &out

	if err = cmd.Run(); err != nil {
		return
	}

	var validLine = regexp.MustCompile(`^([0-9]+)`)

	for _, line := range strings.Split(out.String(), "\n") {
		if validLine.MatchString(line) {
			s.Size, err = fmt.Sscanf("%d", validLine.SubexpNames()[1])
			s.Fingerprint = validLine.SubexpNames()[2]
			s.Comment = validLine.SubexpNames()[3]
			s.Algo = validLine.SubexpNames()[4]
		}
	}

	return
}
