#!/bin/bash
# we only remove specific file extensions generated during the run. We do not remove the dir itself or other file types to prevent potential severe damages if the paths are set incorrectly.

function cleanup {
    if [ "$ENABLE_CLEANUP" = "true" ]; then
        echo
        echo "Cleaning up..."
        if [ "$IS_LOCAL" = "true" ]; then
            if ! "$VEHICLE_RM" -rf "$BIRTH_GEN_DIR/$BIRTH_GEN_EXTENSIONS"; then
                echo "Error removing ${BIRTH_GEN_EXTENSIONS[*]} from $BIRTH_GEN_DIR from this vehicle. Check permissions and/or remove manually."
                exit 1
            fi
        else
            if [ "$IS_LOCAL" = "false" ]; then
                if ! "$OP_SSH" -q "$VEHICLE_USER@$VEHICLE_ADDR" "$VEHICLE_RM -rf $BIRTH_GEN_DIR/$BIRTH_GEN_EXTENSIONS"; then
                    echo "Error removing ${BIRTH_GEN_EXTENSIONS[*]} from $BIRTH_GEN_DIR on the remote vehicle. Check permissions and/or remove manually."
                    exit 1
                fi
            else
                echo "Invalid value for '-l' or '--local' option. Legitimate values are: 'true' or 'false'; case-sensitive and without single-quotes."
                exit 1
            fi
        fi
        echo "Done Cleaning up the intermediate provisioning artifacts. If exited abnormally (e.g. using CTRL+C), you still need to manually clean-up TPM state or certificate storage dir $BIRTH_STORE_DIR."
    else
        echo "Not cleaning up the intermediate provisioning artifacts. Do it manually."
        exit 1
    fi
}

