#!/bin/bash

# This script does not check available ressources on nectar! 


function usage {
    echo $"Usage: $0 {create|update|show|create_or_update,delete_if_exists} STACKNAME"
    exit 1
}

if [ "$#" -ne 2 ]; then
    echo "Illegal number of parameters expecting 2"
    usage
fi

STACKNAME=$2


if [[ "$STACKNAME" == "CICD"* ]]; then
  echo "CICD found in stackname. doing nothing"
else
  STACKNAME="CICD"$STACKNAME
fi



echo "[heatcicdwrapper] Prefixing Stackname with CICD. This is a safety feature because this script can also delete stacks" $STACKNAME

function check_stack_exists {
    if openstack stack list | grep -w $STACKNAME;
        then 
            echo "stack found";
        else 
            echo "stack not found";
            return 1
    fi
}


function func_delete_if_exists {
  if ! check_stack_exists
  then
    exit 0
  fi
  openstack stack delete -y --wait $STACKNAME
  ret=$?
  if [ $ret -ne "0" ]
  then
    sleep 15
    openstack stack delete -y --wait $STACKNAME
    ret=$?
  fi
  exit $ret
}

function create_stack {
    
 if check_stack_exists
 then
    echo "I will NOT create existing stack maybe use update"
    exit -44
 fi
 openstack stack create --wait --template ./CICD/heat/gc_HOT.yaml --parameter "project_name=$STACKNAME" -e ./CICD/heat/resource_registry.yaml $STACKNAME
 createreturn=$?
 if [ $createreturn -ne "0" ]
 then
    openstack stack delete -y --wait $STACKNAME
    echo "creation failed. trying to delete"
    exit -47
 fi
 exit $createreturn
}


case "$1" in
        create)
            create_stack
            ;;
         
        update)
            if ! check_stack_exists
               then
                   echo "I cannot update a stack which does not exist"
                   exit -45
            fi
            openstack stack update --wait --template ./CICD/heat/gc_HOT.yaml --parameter "project_name=$STACKNAME" -e ./CICD/heat/resource_registry.yaml $STACKNAME
            ret=$?
            exit $ret
            ;;
        create_or_update)
            if  check_stack_exists
               then
               openstack stack update --wait --template ./CICD/heat/gc_HOT.yaml --parameter "project_name=$STACKNAME" -e ./CICD/heat/resource_registry.yaml $STACKNAME
               ret=$?
               exit $ret
            fi
            create_stack
                  
            ;;
        delete_if_exists)
            func_delete_if_exists

            ;;
         

        show)
            check_stack_exists
            echo $?
            OUTPUT=$(openstack stack show $STACKNAME| grep -w stack_status)
            echo $OUTPUT
            ;;
         
        *)
            usage
 
esac
