#!/bin/bash

# -------------------------------------------------------------------------- #
# Copyright 2002-2025, OpenNebula Project, OpenNebula Systems                #
#                                                                            #
# 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.                                             #
#--------------------------------------------------------------------------- #

ACTION="$1"
DOM_UUID="$2"
VMDIR="$3"

LIBVIRT_VTPM_DIR="/var/lib/libvirt/swtpm/$DOM_UUID"
LIBVIRT_VTPM_FILE="$LIBVIRT_VTPM_DIR/tpm2/tpm2-00.permall"

case "$ACTION" in
    recover)
        # Return unless there's a saved TPM (i.e., skip process on first instantiation)
        [ -d "$VMDIR/tpm" ] || exit

        # Replicate exactly the structure expected by swtpm, otherwise it will recreate it
        mkdir -p "$LIBVIRT_VTPM_DIR/tpm2"
        chmod 711 "$LIBVIRT_VTPM_DIR"
        chmod 700 "$LIBVIRT_VTPM_DIR/tpm2"
        touch "$LIBVIRT_VTPM_DIR/tpm2/.lock"
        chmod 640 "$LIBVIRT_VTPM_DIR/tpm2/.lock"
        cp "$VMDIR/tpm/tpm2-00.permall" "$LIBVIRT_VTPM_FILE"
        chmod 600 "$LIBVIRT_VTPM_FILE"
        chown -R oneadmin:oneadmin "$LIBVIRT_VTPM_DIR/tpm2"
        ;;
    backup)
        mkdir -p "$VMDIR/tpm"
        cp "$LIBVIRT_VTPM_FILE" "$VMDIR/tpm/tpm2-00.permall"
        chown -R oneadmin:oneadmin "$VMDIR/tpm" # Must be accessible by swtpm's user
        ;;
esac
