#!/bin/bash

set -e

BIN_NAME=$(basename "$0")

function stdout() {
  echo -e "[$BIN_NAME] $1"
}

function stderr() {
  echo -e "[$BIN_NAME] $1" 1>&2
}

function usage() {
  stderr "usage:"
  stderr "\t# $BIN_NAME create"
}

if [[ $EUID -ne 0 ]]; then
  stderr "fail: this script must be run as root"
  exit 1
fi

if [ -z "$1" ]; then
  stderr "fail: invalid args"
  usage "$0"
  exit 1
fi

function handle_create() {
  mkdir -p ./hasp
  /opt/edge/bin/hasp_update lf > ./hasp/keys.xml
  /opt/edge/bin/hasp_update f ./hasp/host.c2v

  /opt/edge/bin/hasp_update l | jq -rc 'keys|.[]' | while read -r keyRef; do
    /opt/edge/bin/hasp_update i "$keyRef" "./hasp/$keyRef.c2v"
  done
}

case $1 in
  create)
    stdout "exec: create"
    handle_create
    stdout "done: create"
    ;;

  restore)
    ;;

  *)
    stderr "fail: unsupported (action:$1)"
    usage "$0"
    exit 1
    ;;
esac
