#!/bin/bash -

. /etc/os-release

VERSION_ID=`sed -E 's/([0-9]).*/\1/g' <<< "$VERSION_ID"`

if grep "Red Hat" /etc/redhat-release &>/dev/null
then
    if [[ "$VERSION_ID" -ge 8 ]]
    then
        subscription-manager repos --enable ansible-2.9-for-rhel-8-x86_64-rpms
    else
	      subscription-manager repos --enable rhel-7-server-ansible-2.9-rpms
    fi
elif [[ "$VERSION_ID" -eq 7 ]]
then
    yum -y install epel-release
fi

if [[ "$VERSION_ID" -eq 7 ]]
then
    yum -y install ansible
else
    dnf -y install ansible-core || yum -y install ansible
fi

ANSIBLE_VERSION=`ansible --version | head -1 | sed -E 's/.*[^0-9.]([0-9.]+).*/\1/g'`
ANSIBLE_VERSION_MIN=`printf "2.10\n${ANSIBLE_VERSION}\n" | sort -V | head -1`

ansible-galaxy install --force xe0nic.ansible_isp_server
ansible-galaxy install --force xe0nic.ansible_kodo_endpoints_server
if [[ "$ANSIBLE_VERSION_MIN" == "2.10" ]]
then
    ansible-galaxy install -r  ~/.ansible/roles/xe0nic.ansible_isp_server/meta/collections.yml
    ansible-galaxy install -r  ~/.ansible/roles/xe0nic.ansible_kodo_endpoints_server/meta/collections.yml
fi

pip3 install -r  ~/.ansible/roles/xe0nic.ansible_kodo_endpoints_server/meta/python_requirements.txt

mkdir -p kodo

if [ ! -z "$KODO_VARS_FILE" ]
then
    echo "Using extra vars file: $KODO_VARS_FILE"
    cp "$KODO_VARS_FILE" kodo/vars.yml
    extra_vars_arg="--extra-vars @vars.yml"
fi

cd kodo

repo=${KODO_REPO:-"http://repo.storware.eu/storware/current/el${VERSION_ID}"}

cat << EOF > hosts
[all:vars] 
ansible_user=root
ansible_connection=local
kodo_repo=$repo

[server]
localhost
EOF

cat << EOF > site.yml
---

- hosts: server
  roles:
    - xe0nic.ansible_isp_server
    - xe0nic.ansible_kodo_endpoints_server
EOF

ansible-playbook -i hosts site.yml $extra_vars_arg

echo DONE! Try to log into your Kodo Endpoints Server console now.
