package cmd

import (
	"fmt"
	"os"
	"text/tabwriter"

	"git.wntrmute.dev/kyle/arca/internal/config"
	"git.wntrmute.dev/kyle/arca/internal/udisks"
	"github.com/spf13/cobra"
)

var statusCmd = &cobra.Command{
	Use:   "status",
	Short: "Show LUKS volume status",
	RunE:  runStatus,
}

func init() {
	rootCmd.AddCommand(statusCmd)
}

func runStatus(cmd *cobra.Command, args []string) error {
	cfg := config.Load()

	client, err := udisks.NewClient()
	if err != nil {
		return fmt.Errorf("connecting to udisks2: %w", err)
	}
	defer client.Close()

	devices, err := client.ListEncryptedDevices()
	if err != nil {
		return err
	}

	w := tabwriter.NewWriter(os.Stdout, 0, 4, 2, ' ', 0)
	fmt.Fprintln(w, "DEVICE\tUUID\tALIAS\tSTATE\tMOUNTPOINT")

	for _, dev := range devices {
		alias := cfg.AliasFor(dev.UUID)
		state := "locked"
		mountpoint := ""

		if ct, err := client.CleartextDevice(&dev); err == nil {
			state = "unlocked"
			if mp, err := client.MountPoint(ct); err == nil && mp != "" {
				mountpoint = mp
				state = "mounted"
			}
		}

		fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\n",
			dev.DevicePath, dev.UUID, alias, state, mountpoint)
	}

	w.Flush()
	return nil
}
