package main

import (
	"fmt"
	"log"
	"os"

	"s.mcquay.me/dm/school/cs465/aes"

	"github.com/spf13/cobra"
)

var key128 = aes.Block{
	0x2b, 0x28, 0xab, 0x09,
	0x7e, 0xae, 0xf7, 0xcf,
	0x15, 0xd2, 0x15, 0x4f,
	0x16, 0xa6, 0x88, 0x3c,
}
var key192 = aes.Block{
	0x00, 0x04, 0x08, 0x0c, 0x10, 0x14,
	0x01, 0x05, 0x09, 0x0d, 0x11, 0x15,
	0x02, 0x06, 0x0a, 0x0e, 0x12, 0x16,
	0x03, 0x07, 0x0b, 0x0f, 0x13, 0x17,
}
var key256 = aes.Block{
	0x00, 0x04, 0x08, 0x0c, 0x10, 0x14, 0x18, 0x1c,
	0x01, 0x05, 0x09, 0x0d, 0x11, 0x15, 0x19, 0x1d,
	0x02, 0x06, 0x0a, 0x0e, 0x12, 0x16, 0x1a, 0x1e,
	0x03, 0x07, 0x0b, 0x0f, 0x13, 0x17, 0x1b, 0x1f,
}

func main() {
	var keysize int
	var decrypt bool
	var ascii bool

	var aes = &cobra.Command{
		Use:   "aes",
		Short: "aes cipher",
		Long:  `perform aes cipher`,
		Run: func(cmd *cobra.Command, args []string) {
			if len(args) < 1 {
				fmt.Println("missing input, see -h (--help) for more info")
				os.Exit(1)
			}
			for _, arg := range args {
				all := aes.BlockGen(arg)
				if ascii {
					switch keysize {
					case 128:
						fmt.Println(aes.ToString(all, 128, key128, decrypt))
					case 192:
						fmt.Println(aes.ToString(all, 192, key192, decrypt))
					case 256:
						fmt.Println(aes.ToString(all, 256, key256, decrypt))
					default:
						log.Fatal("keysize not valid")
					}
				} else {
					switch keysize {
					case 128:
						fmt.Println(aes.ToHex(all, 128, key128, decrypt))
					case 192:
						fmt.Println(aes.ToHex(all, 192, key192, decrypt))
					case 256:
						fmt.Println(aes.ToHex(all, 256, key256, decrypt))
					default:
						log.Fatal("keysize not valid")
					}
				}
			}
		},
	}
	aes.Flags().IntVarP(
		&keysize,
		"keysize",
		"k",
		0,
		"keysize",
	)
	aes.Flags().BoolVarP(
		&ascii,
		"ascii",
		"a",
		false,
		"display in ascii (may mess up terminal :) )",
	)
	aes.Flags().BoolVarP(
		&decrypt,
		"decrypt",
		"d",
		false,
		"decrypt",
	)
	var rootCmd = &cobra.Command{Use: "app"}
	rootCmd.AddCommand(aes)
	rootCmd.Execute()
}
