#!/bin/bash

# Update system and install necessary packages
apt-get update && apt-get dist-upgrade -y
apt-get install openstack-keystone python3-module-openstackclient mariadb-server memcached rabbitmq-server -y

# Start necessary services
systemctl enable --now mariadb
systemctl enable --now memcached
systemctl enable --now rabbitmq

# Adding a delay to ensure MariaDB service is fully up and running
echo "Waiting for MariaDB to fully start..."
sleep 10

# Configure MySQL database for Keystone
mysql -u root -e "CREATE DATABASE keystone;"
mysql -u root -e "GRANT ALL PRIVILEGES ON keystone.* TO 'keystone'@'localhost' IDENTIFIED BY '1';"
mysql -u root -e "GRANT ALL PRIVILEGES ON keystone.* TO 'keystone'@'%' IDENTIFIED BY '1';"

# Configure Keystone
awk '/^\[database\]/{p=1} p && /^$/ && !a {print "connection = mysql+pymysql://keystone:1@127.0.0.1/keystone"; a=1} 1' /etc/keystone/keystone.conf > /etc/keystone/keystone.conf.tmp && mv /etc/keystone/keystone.conf.tmp /etc/keystone/keystone.conf

# Assuming cache is enabled and backend configuration is needed once
awk '/^\[cache\]/{p=1} p && /^$/ && !a {print "enabled = true\nbackend = dogpile.cache.memcached"; a=1} 1' /etc/keystone/keystone.conf > /etc/keystone/keystone.conf.tmp && mv /etc/keystone/keystone.conf.tmp /etc/keystone/keystone.conf

# Configure MySQL for OpenStack
cat > /etc/my.cnf.d/openstack.cnf <<OEOF
[mysqld]
bind-address = 127.0.0.1
default-storage-engine = innodb
innodb_file_per_table
max_connections = 4096
collation-server = utf8_general_ci
character-set-server = utf8
OEOF

sed -i "/skip-networking/d" /etc/my.cnf.d/server.cnf
systemctl restart mariadb

# Keystone initial setup
keystone-manage db_sync
keystone-manage fernet_setup --keystone-user keystone --keystone-group keystone
keystone-manage credential_setup --keystone-user keystone --keystone-group keystone
keystone-manage bootstrap --bootstrap-password 1 --bootstrap-admin-url http://$(hostname -i):5000/v3/ --bootstrap-internal-url http://$(hostname -i):5000/v3/ --bootstrap-public-url http://$(hostname -i):5000/v3/ --bootstrap-region-id RegionOne

chown -R keystone:keystone /etc/keystone

# Assuming Apache2 is used for Keystone
systemctl enable --now httpd2.service

# Set environment variables for OpenStack commands
cat > auth_data <<AEOF
export OS_AUTH_URL=http://$(hostname -i):5000/v3
export OS_IDENTITY_API_VERSION=3
export OS_USERNAME=admin
export OS_PASSWORD=1
export OS_PROJECT_NAME=admin
export OS_USER_DOMAIN_NAME=Default
export OS_PROJECT_DOMAIN_NAME=Default
export OS_REGION_NAME=RegionOne
AEOF

source auth_data

# Create domain, project, and service entities
openstack domain create --description "An Example Domain" example
openstack project create --domain default --description "Service Project" service

# rabbitmq setup
rabbitmqctl add_user openstack 1
rabbitmqctl set_permissions openstack ".*" ".*" ".*"
