*** Comments ***
# Copyright 2019 Tech Mahindra Limited
#
# All Rights Reserved.
#
# 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.


*** Settings ***
Documentation   Library providing keywords for CRUD operations over NSD/NSpkg with OSM client.

Library   OperatingSystem
Library   String


*** Variables ***
${SUCCESS_RETURN_CODE}   0
${NSD_DELETE_MAX_WAIT_TIME}   1min
${NSD_DELETE_POL_TIME}   15sec


*** Keywords ***
Get NSDs List
    [Documentation]   Get the list of NS packages and log it.
    ${rc}   ${stdout}=   Run And Return Rc And Output   osm nspkg-list
    Log   ${stdout}
    Should Be Equal As Integers   ${rc}   ${SUCCESS_RETURN_CODE}

Create NSD
    [Documentation]   Upload a NS package to OSM and return the id.
    [Arguments]   ${nsd_pkg}
    ${rc}   ${stdout}=   Run And Return Rc And Output   osm nspkg-create ${nsd_pkg}
    Log   ${stdout}
    Should Be Equal As Integers   ${rc}   ${SUCCESS_RETURN_CODE}
    ${lines}=   Get Line Count   ${stdout}
    ${last}=   Evaluate   ${lines} - 1
    ${id}=   Get Line   ${stdout}   ${last}
    RETURN   ${id}

Delete NSD
    [Documentation]   Delete a NS package from OSM.
    [Arguments]   ${nsd_id}
    ${rc}   ${stdout}=   Run Keyword And Continue On Failure   Run And Return Rc And Output   osm nspkg-delete ${nsd_id}
    Should Be Equal As Integers   ${rc}   ${SUCCESS_RETURN_CODE}
    Log   ${stdout}
    Wait Until Keyword Succeeds   ${NSD_DELETE_MAX_WAIT_TIME}   ${NSD_DELETE_POL_TIME}   Check For NSD   ${nsd_id}

Check For NSD
    [Documentation]   Check that a NS package exists in OSM.
    [Arguments]   ${nsd_id}
    ${rc}   ${stdout}=   Run And Return Rc And Output   osm nspkg-list | awk '{print $2}' | grep ${nsd_id}
    Log   ${rc},${stdout}
    Should Not Be Equal As Strings   ${stdout}   ${nsd_id}

Get NSD Ip
    [Documentation]   To get the Ip from the Nsd
    [Arguments]   ${nsd_id}
    ${stdout}=   Run   osm nsd-show ${nsd_id} --literal | grep -A2 ip-address | grep -v "ip-address:" | awk '{print $2}' | tr -d ',-'
    Log   ${stdout}
    RETURN   ${stdout}
