//go:build pivkey && cgo
// +build pivkey,cgo

// Copyright 2021 The Sigstore Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package pivkey

import (
	"github.com/go-piv/piv-go/v2/piv"
)

func SlotForName(slotName string) *piv.Slot {
	switch slotName {
	case "":
		return &piv.SlotSignature
	case "authentication":
		return &piv.SlotAuthentication
	case "signature":
		return &piv.SlotSignature
	case "card-authentication":
		return &piv.SlotCardAuthentication
	case "key-management":
		return &piv.SlotKeyManagement
	default:
		return nil
	}
}

func PINPolicyForName(policyName string, slot piv.Slot) piv.PINPolicy {
	switch policyName {
	case "":
		return defaultPINPolicyForSlot(slot)
	case "never":
		return piv.PINPolicyNever
	case "once":
		return piv.PINPolicyOnce
	case "always":
		return piv.PINPolicyAlways
	default:
		return -1
	}
}

func TouchPolicyForName(policyName string, slot piv.Slot) piv.TouchPolicy {
	switch policyName {
	case "":
		return defaultTouchPolicyForSlot(slot)
	case "never":
		return piv.TouchPolicyNever
	case "cached":
		return piv.TouchPolicyCached
	case "always":
		return piv.TouchPolicyAlways
	default:
		return -1
	}
}

func defaultPINPolicyForSlot(slot piv.Slot) piv.PINPolicy {
	//
	// Defaults from https://developers.yubico.com/PIV/Introduction/Certificate_slots.html
	//

	switch slot {
	case piv.SlotAuthentication:
		return piv.PINPolicyOnce
	case piv.SlotSignature:
		return piv.PINPolicyAlways
	case piv.SlotKeyManagement:
		return piv.PINPolicyOnce
	case piv.SlotCardAuthentication:
		return piv.PINPolicyNever
	default:
		// This should never happen
		panic("invalid value for slot")
	}
}

func defaultTouchPolicyForSlot(slot piv.Slot) piv.TouchPolicy {
	//
	// Defaults from https://developers.yubico.com/PIV/Introduction/Certificate_slots.html
	//

	switch slot {
	case piv.SlotAuthentication:
		return piv.TouchPolicyCached
	case piv.SlotSignature:
		return piv.TouchPolicyAlways
	case piv.SlotKeyManagement:
		return piv.TouchPolicyCached
	case piv.SlotCardAuthentication:
		return piv.TouchPolicyNever
	default:
		// This should never happen
		panic("invalid value for slot")
	}
}
