#!/bin/bash

set -eu

install-packages git-core wget make gcc python-pip python-dev python-setuptools puppet

if test -f /etc/redhat-release
then
    rpm -Uvh https://packages.chef.io/stable/el/7/chef-12.9.41-1.el7.x86_64.rpm
else
    install-packages chef
fi

name=murano-agent
svc_root=${DIB_MURANO_AGENT_SVC_ROOT:-/opt/stack/$name}
repo=${DIB_MURANO_AGENT_REPO:-https://git.openstack.org/openstack/murano-agent.git}
branch=${DIB_MURANO_AGENT_BRANCH:-master}
ref=${DIB_MURANO_AGENT_REF:-''}

# clone murano-agent source code into /opt/stack/murano-agent
mkdir -p $svc_root
git clone --depth=1 -b $branch $repo $svc_root
if [ -n "$ref" ]; then
    pushd $svc_root
    git fetch $repo $ref && git checkout FETCH_HEAD
    popd
fi

# install murano-agent to default location using pip
# FIXME(starodubcevna): probably pip is not the best case for this. I suggest to
# switch to package when they will be available to all supported distros.

pip install $svc_root

# setup config file at /etc/murano/agent.conf
mkdir -p /etc/murano

PATH="/usr/local/bin:/usr/bin:$PATH"

pushd ${svc_root}
oslo-config-generator --config-file ${svc_root}/etc/oslo-config-generator/muranoagent.conf
popd

cp ${svc_root}/etc/muranoagent/muranoagent.conf.sample /etc/murano/agent.conf.sample

# install upstart script for murano-agent
if [ -d "/etc/init/" ]; then
    install -D -g root -o root -m 0755 $(dirname $0)/murano-agent.conf /etc/init/
fi
if [ -d "/etc/systemd/system/" ]; then
    install -D -g root -o root -m 0755 $(dirname $0)/murano-agent.service /etc/systemd/system/
fi
