Select Git revision
vmCreds2pdf.go
vmCreds2pdf.go 3.30 KiB
package cmdVM
import (
u "nexus-client/utils"
"github.com/go-pdf/fpdf"
)
import _ "embed"
//go:embed resources/cmuntb.ttf
var embeddedCMUTypewriterBold string
type Creds2pdf struct {
Name string
}
func (cmd *Creds2pdf)GetName() string {
return cmd.Name
}
func (cmd *Creds2pdf)GetDesc() []string {
return []string{
"Creates a PDF with the credentials required to attach to running VMs.",
"If not the VM's owner: requires VM_ATTACH VM access capability or VM_ATTACH_ANY user capability."}
}
func (cmd *Creds2pdf)PrintUsage() {
for _, desc := range cmd.GetDesc() {
u.PrintlnErr(desc)
}
u.PrintlnErr("―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――")
u.PrintlnErr("USAGE: ",cmd.GetName()," [ID ...] [regex ...] pdfile")
u.PrintlnErr("―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――")
printRegexUsageDetails()
}
func (cmd *Creds2pdf)Run(args []string) int {
argc := len(args)
if argc < 2 {
cmd.PrintUsage()
return 1
}
pdfFile := args[argc-1]
credsList, err := getFilteredVMCredentials("/vms/attach", args[:argc-1])
if err != nil {
u.PrintlnErr("Error: "+err.Error())
return 1
}
if len(credsList) == 0 {
u.PrintlnErr("Error: VM(s) not found (possible causes: no VM by that ID/regex, VM(s) not started, missing capabilities).")
return 1
}
const leftMargin = 8.
const topMargin = 5.
const rightMargin = 0.
// Max number of chars allowed in the VM's name given the used font and size.
const maxChar = 70
columnWidth := [...]float64 {156.,30.}
const rowHeight = 15.
const fontSize = 12.
const cellBorder = "1" // full cell border; use "" for no border
const nextPos = 0 // 0 means to move right
const align = "L"
const bkgd = false // transparent background; use true for filled
const link = 0 // no link
const url = "" // no url
pdf := fpdf.New("p", "mm", "A4", "") // "p" means portrait orienation
pdf.SetMargins(leftMargin, topMargin, rightMargin)
pdf.AddPage()
// Read a specific monospace bold font known to support UTF8 encoding
pdf.AddUTF8FontFromBytes("cmuntb", "b", []byte(embeddedCMUTypewriterBold))
for _, creds := range credsList {
if len(creds.Name) > maxChar {
creds.Name = creds.Name[0:maxChar-1]
creds.Name = creds.Name+"…"
}
pdf.SetX(leftMargin)
pdf.SetFont("cmuntb", "b", fontSize) // "b" means bold; use "" for normal
pdf.CellFormat(columnWidth[0], rowHeight, creds.Name, cellBorder, nextPos, align, bkgd, link, url)
pdf.CellFormat(columnWidth[1], rowHeight, creds.Pwd, cellBorder, nextPos, "C", bkgd, link, url)
pdf.Ln(-1) // line break; -1 means move by the height of the last printed cell
}
if err = pdf.OutputFileAndClose(pdfFile); err != nil {
u.PrintlnErr("Error: "+err.Error())
return 1
}
u.Println(pdfFile+" written successfully.")
return 0
}