#!/bin/bash

OSM_PACKAGE_DIR=$HOME/osm-packages
WIKI_VNFD_PACKAGE_NAME=wiki_webserver_autoscale_vnfd
WIKI_NSD_PACKAGE_NAME=wiki_webserver_autoscale_nsd
WIKI_VNF_PACKAGE_DIR=$OSM_PACKAGE_DIR/$WIKI_VNFD_PACKAGE_NAME
WIKI_NS_PACKAGE_DIR=$OSM_PACKAGE_DIR/$WIKI_NSD_PACKAGE_NAME
WIKI_VNFD_NAME=wiki_webserver_autoscale_vnf
WIKI_NSD_NAME=wiki_webserver_autoscale_ns
USER_ID=$OSM_USER

echo "========================================================================"
echo "Downloading and modifying the wiki package"
echo "========================================================================"
# clone from git
rm -rf $OSM_PACKAGE_DIR
git clone https://osm.etsi.org/gitlab/vnf-onboarding/osm-packages.git
# Append user id to NSD and VNFD names
sed -i "s/${WIKI_VNFD_NAME}.*/${WIKI_VNFD_NAME}_${USER_ID}/" $WIKI_VNF_PACKAGE_DIR/wiki_webserver_autoscale_vnfd.yaml
sed -i "s/${WIKI_VNFD_NAME}.*/${WIKI_VNFD_NAME}_${USER_ID}/" $WIKI_NS_PACKAGE_DIR/wiki_webserver_autoscale_nsd.yaml
sed -i "s/${WIKI_NSD_NAME}.*/${WIKI_NSD_NAME}_${USER_ID}/" $WIKI_NS_PACKAGE_DIR/wiki_webserver_autoscale_nsd.yaml
# Add 'runcmd' in cloud-init to modify configuration and restart haproxy service
echo 'runcmd:' >> $WIKI_VNF_PACKAGE_DIR/cloud_init/cloud_init_haproxy
echo ' - ip=$(ifconfig | grep -A 1 "ens4" | tail -1 | cut -d ":" -f 2 | cut -d " " -f 1)' >> $WIKI_VNF_PACKAGE_DIR/cloud_init/cloud_init_haproxy
echo ' - sudo -S sed -i "s/ipv4@\(.*:9999\)/ipv4@${ip}\:9999/" /etc/haproxy/haproxy.cfg' >> $WIKI_VNF_PACKAGE_DIR/cloud_init/cloud_init_haproxy
echo ' - sleep 60' >> $WIKI_VNF_PACKAGE_DIR/cloud_init/cloud_init_haproxy
echo ' - echo "osm2021" | sudo service haproxy restart' >> $WIKI_VNF_PACKAGE_DIR/cloud_init/cloud_init_haproxy

echo "========================================================================"
echo "Cleaning out any prior versions of the descriptors from OSM"
echo "========================================================================"
osm nsd-delete $WIKI_NSD_NAME"_"$USER_ID
osm vnfd-delete $WIKI_VNFD_NAME"_"$USER_ID

echo "========================================================================"
echo "Building packages"
echo "========================================================================"
cd $OSM_PACKAGE_DIR
osm package-build $WIKI_VNFD_PACKAGE_NAME 
osm package-build $WIKI_NSD_PACKAGE_NAME 

echo "========================================================================"
echo "Uploading packages"
echo "========================================================================"
osm upload-package $WIKI_VNFD_PACKAGE_NAME.tar.gz
osm upload-package $WIKI_NSD_PACKAGE_NAME.tar.gz

echo "========================================================================"
echo "Done"
echo "========================================================================"

