#!/usr/bin/env bash

# Copyright (C) 2016 Paul Kocialkowski <contact@paulk.fr>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

usage() {
	tool_usage_actions "$tool" "generate" "sign" "verify"
}

generate() {
	local type=$(boot_keys_type "$@")

	if [[ -z "$type" ]]
	then
		printf 1>&2 '%s\n' 'Unable to determine keys type'
		return 1
	fi

	case $type in
		"cros"*)
			boot_keys_cros "cros-boot-keys" "generate"
			;;
	esac
}

sign() {
	local project=$1

	local prepare_files=$(boot_keys_files "$@")
	local type=$(boot_keys_type "$@")
	local install_path
	local firmware_path
	local kernel_path
	local media

	if [[ -z "$type" ]]
	then
		printf 1>&2 '%s\n' 'Unable to determine keys type'
		return 1
	fi

	printf '%s\n' "$prepare_files" | while read install_path
	do
		case $type in
			"cros-firmware")
				firmware_path="$install_path/$project.$ROM"

				boot_keys_cros "$type-prepare" "sign" "$firmware_path"
				;;
			"cros-kernel")
				media=$(project_action "media" "$@")

				for medium in $media
				do
					kernel_path="$install_path/$KERNEL-$medium.$IMG"

					if [[ -f "$kernel_path" ]]
					then
						boot_keys_cros "$type-prepare" "sign" "$kernel_path"
					else
						boot_keys_cros "$type-prepare" "pack" "$install_path" "$medium"
					fi
				done
				;;
		esac
	done
}

verify() {
	local project=$1

	local prepare_files=$(boot_keys_files "$@")
	local type=$(boot_keys_type "$@")
	local install_path
	local firmware_path
	local kernel_path
	local media

	if [[ -z "$type" ]]
	then
		printf 1>&2 '%s\n' 'Unable to determine keys type'
		return 1
	fi

	printf '%s\n' "$prepare_files" | while read install_path
	do
		case $type in
			"cros-firmware")
				firmware_path="$install_path/$project.$ROM"

				boot_keys_cros "$type-prepare" "verify" "$firmware_path"
				;;
			"cros-kernel")
				media=$(project_action "media" "$@")

				for medium in $media
				do
					kernel_path="$install_path/$KERNEL-$medium.$IMG"

					boot_keys_cros "$type-prepare" "verify" "$kernel_path"
				done
				;;
		esac
	done
}
