#!/bin/bash
## HELPER SCRIPT TO RESTART BUNDLE THROUGH JOLOKIA

IP=$1
PORT=$2
BUNDLENAME=$3
USERNAME=$4
PASSWORD=$5

## helper python script to extract json data. an alternative could be using jq
PYTHON_GET_OSGI_OBJECT_NAME='
import json

temp = []
data = None
with open("output.json") as json_data:
    data = json.load(json_data)
print data["value"][0]
'

PYTHON_GET_SSHD_BUNDLE_ID='
import json

temp = []
data = None
with open("output.json") as json_data:
    data = json.load(json_data)

temp = [ [ it,data["value"][it]["SymbolicName"] ] for it in data["value"] ]
temp = [ it for it in temp if "'$BUNDLENAME'" in it[1] ]

print temp[0][0]
'

## Getting the correct Osgi bundleState jmx object name
curl -u $USERNAME:$PASSWORD  http://$IP:$PORT/jolokia/search/osgi.core:type=bundleState,version=1.7,framework=org.apache.felix.framework,uuid=* > output.json
OSGI_OBJECT_NAME=$(python -c "$PYTHON_GET_OSGI_OBJECT_NAME")
echo $OSGI_OBJECT_NAME

## Using that jmx object name to list all bundles and get the bundle ID of the first one that contains $BUNDLENAME (usually $BUNDLENAME=sshd)
curl -u $USERNAME:$PASSWORD http://$IP:$PORT/jolokia/exec/$OSGI_OBJECT_NAME/listBundles\(\) > output.json
SSHD_BUNDLE_ID=$(python -c "$PYTHON_GET_SSHD_BUNDLE_ID")
echo $SSHD_BUNDLE_ID

## Getting the correct Osgi framework jmx object name
curl -u $USERNAME:$PASSWORD  http://$IP:$PORT/jolokia/search/osgi.core:type=framework,version=1.7,framework=org.apache.felix.framework,uuid=* > output.json
OSGI_OBJECT_NAME=$(python -c "$PYTHON_GET_OSGI_OBJECT_NAME")

## Clean-up output file 
rm ./output.json

## Call refreshBundle using the retrieved SSHD_BUNDLE_ID
curl -u $USERNAME:$PASSWORD http://$IP:$PORT/jolokia/exec/$OSGI_OBJECT_NAME/refreshBundle\(long\)/$SSHD_BUNDLE_ID/
