--liquibase formatted sql
-- This code generated was by RbacViewPostgresGenerator, do not amend manually.


-- ============================================================================
--changeset hs-hosting-asset-rbac-OBJECT:1 endDelimiter:--//
-- ----------------------------------------------------------------------------
call generateRelatedRbacObject('hs_hosting_asset');
--//


-- ============================================================================
--changeset hs-hosting-asset-rbac-ROLE-DESCRIPTORS:1 endDelimiter:--//
-- ----------------------------------------------------------------------------
call generateRbacRoleDescriptors('hsHostingAsset', 'hs_hosting_asset');
--//


-- ============================================================================
--changeset hs-hosting-asset-rbac-insert-trigger:1 endDelimiter:--//
-- ----------------------------------------------------------------------------

/*
    Creates the roles, grants and permission for the AFTER INSERT TRIGGER.
 */

create or replace procedure buildRbacSystemForHsHostingAsset(
    NEW hs_hosting_asset
)
    language plpgsql as $$

declare
    newParentServer hs_hosting_asset;
    newBookingItem hs_booking_item;

begin
    call enterTriggerForObjectUuid(NEW.uuid);

    SELECT * FROM hs_hosting_asset WHERE uuid = NEW.parentAssetUuid    INTO newParentServer;

    SELECT * FROM hs_booking_item WHERE uuid = NEW.bookingItemUuid    INTO newBookingItem;

    perform createRoleWithGrants(
        hsHostingAssetOWNER(NEW),
            permissions => array['DELETE'],
            incomingSuperRoles => array[hsBookingItemADMIN(newBookingItem)]
    );

    perform createRoleWithGrants(
        hsHostingAssetADMIN(NEW),
            permissions => array['UPDATE'],
            incomingSuperRoles => array[hsHostingAssetOWNER(NEW)]
    );

    perform createRoleWithGrants(
        hsHostingAssetTENANT(NEW),
            permissions => array['SELECT'],
            incomingSuperRoles => array[hsHostingAssetADMIN(NEW)],
            outgoingSubRoles => array[hsBookingItemTENANT(newBookingItem)]
    );

    IF NEW.type = 'CLOUD_SERVER' THEN
    ELSIF NEW.type = 'MANAGED_SERVER' THEN
    ELSIF NEW.type = 'MANAGED_WEBSPACE' THEN
    ELSE
    END IF;

    call leaveTriggerForObjectUuid(NEW.uuid);
end; $$;

/*
    AFTER INSERT TRIGGER to create the role+grant structure for a new hs_hosting_asset row.
 */

create or replace function insertTriggerForHsHostingAsset_tf()
    returns trigger
    language plpgsql
    strict as $$
begin
    call buildRbacSystemForHsHostingAsset(NEW);
    return NEW;
end; $$;

create trigger insertTriggerForHsHostingAsset_tg
    after insert on hs_hosting_asset
    for each row
execute procedure insertTriggerForHsHostingAsset_tf();
--//


-- ============================================================================
--changeset hs-hosting-asset-rbac-GRANTING-INSERT-PERMISSION:1 endDelimiter:--//
-- ----------------------------------------------------------------------------

-- granting INSERT permission to hs_booking_item ----------------------------

/*
    Grants INSERT INTO hs_hosting_asset permissions to specified role of pre-existing hs_booking_item rows.
 */
do language plpgsql $$
    declare
        row hs_booking_item;
    begin
        call defineContext('create INSERT INTO hs_hosting_asset permissions for pre-exising hs_booking_item rows');

        FOR row IN SELECT * FROM hs_booking_item
            -- unconditional for all rows in that table
            LOOP
                call grantPermissionToRole(
                        createPermission(row.uuid, 'INSERT', 'hs_hosting_asset'),
                        hsBookingItemAGENT(row));
            END LOOP;
    end;
$$;

/**
    Grants hs_hosting_asset INSERT permission to specified role of new hs_booking_item rows.
*/
create or replace function new_hs_hosting_asset_grants_insert_to_hs_booking_item_tf()
    returns trigger
    language plpgsql
    strict as $$
begin
    -- unconditional for all rows in that table
        call grantPermissionToRole(
            createPermission(NEW.uuid, 'INSERT', 'hs_hosting_asset'),
            hsBookingItemAGENT(NEW));
    -- end.
    return NEW;
end; $$;

-- z_... is to put it at the end of after insert triggers, to make sure the roles exist
create trigger z_new_hs_hosting_asset_grants_insert_to_hs_booking_item_tg
    after insert on hs_booking_item
    for each row
execute procedure new_hs_hosting_asset_grants_insert_to_hs_booking_item_tf();

-- granting INSERT permission to hs_hosting_asset ----------------------------

-- Granting INSERT INTO hs_hosting_asset permissions to specified role of pre-existing hs_hosting_asset rows slipped,
-- because there cannot yet be any pre-existing rows in the same table yet.

/**
    Grants hs_hosting_asset INSERT permission to specified role of new hs_hosting_asset rows.
*/
create or replace function new_hs_hosting_asset_grants_insert_to_hs_hosting_asset_tf()
    returns trigger
    language plpgsql
    strict as $$
begin
    if NEW.type = 'MANAGED_SERVER' then
        call grantPermissionToRole(
            createPermission(NEW.uuid, 'INSERT', 'hs_hosting_asset'),
            hsHostingAssetADMIN(NEW));
    end if;
    return NEW;
end; $$;

-- z_... is to put it at the end of after insert triggers, to make sure the roles exist
create trigger z_new_hs_hosting_asset_grants_insert_to_hs_hosting_asset_tg
    after insert on hs_hosting_asset
    for each row
execute procedure new_hs_hosting_asset_grants_insert_to_hs_hosting_asset_tf();


-- ============================================================================
--changeset hs_hosting_asset-rbac-CHECKING-INSERT-PERMISSION:1 endDelimiter:--//
-- ----------------------------------------------------------------------------

/**
    Checks if the user respectively the assumed roles are allowed to insert a row to hs_hosting_asset.
*/
create or replace function hs_hosting_asset_insert_permission_check_tf()
    returns trigger
    language plpgsql as $$
declare
    superObjectUuid uuid;
begin
    -- check INSERT permission via direct foreign key: NEW.bookingItemUuid
    if NEW.type in ('MANAGED_SERVER', 'CLOUD_SERVER', 'MANAGED_WEBSPACE') and hasInsertPermission(NEW.bookingItemUuid, 'hs_hosting_asset') then
        return NEW;
    end if;
    -- check INSERT permission via direct foreign key: NEW.parentAssetUuid
    if NEW.type in ('MANAGED_WEBSPACE') and hasInsertPermission(NEW.parentAssetUuid, 'hs_hosting_asset') then
        return NEW;
    end if;

    raise exception '[403] insert into hs_hosting_asset not allowed for current subjects % (%)',
            currentSubjects(), currentSubjectsUuids();
end; $$;

create trigger hs_hosting_asset_insert_permission_check_tg
    before insert on hs_hosting_asset
    for each row
        execute procedure hs_hosting_asset_insert_permission_check_tf();
--//


-- ============================================================================
--changeset hs-hosting-asset-rbac-IDENTITY-VIEW:1 endDelimiter:--//
-- ----------------------------------------------------------------------------

call generateRbacIdentityViewFromQuery('hs_hosting_asset',
    $idName$
        SELECT asset.uuid as uuid, bookingItemIV.idName || '-' || cleanIdentifier(asset.identifier) as idName
            FROM hs_hosting_asset asset
            JOIN hs_booking_item_iv bookingItemIV ON bookingItemIV.uuid = asset.bookingItemUuid
    $idName$);
--//


-- ============================================================================
--changeset hs-hosting-asset-rbac-RESTRICTED-VIEW:1 endDelimiter:--//
-- ----------------------------------------------------------------------------
call generateRbacRestrictedView('hs_hosting_asset',
    $orderBy$
        identifier
    $orderBy$,
    $updates$
        version = new.version,
        caption = new.caption,
        config = new.config
    $updates$);
--//