#!/bin/bash

echo "=== Deploy Kolla-Ansible OpenStack ==="

# Khởi động VMs
echo "1. Khởi động Kolla cluster VMs..."
vagrant up

if [ $? -ne 0 ]; then
    echo "✗ Lỗi khởi động VMs"
    exit 1
fi

# Setup Kolla-Ansible
echo "2. Setup Kolla-Ansible..."
vagrant ssh controller -c "
    # Cài đặt Kolla-Ansible
    pip3 install 'ansible>=4,<6'
    pip3 install kolla-ansible

    # Tạo thư mục cấu hình
    sudo mkdir -p /etc/kolla
    sudo chown vagrant:vagrant /etc/kolla

    # Copy cấu hình mẫu
    cp -r /usr/local/share/kolla-ansible/etc_examples/kolla/* /etc/kolla/
    cp /usr/local/share/kolla-ansible/ansible/inventory/* .

    # Tạo inventory
    cat > multinode << 'EOF'
[control]
controller ansible_host=192.168.56.81 ansible_user=vagrant

[network:children]
control

[compute]
compute ansible_host=192.168.56.82 ansible_user=vagrant

[monitoring:children]
control

[storage:children]
control

[deployment]
localhost ansible_connection=local
EOF

    # Cấu hình globals.yml
    cat >> /etc/kolla/globals.yml << 'EOF'
kolla_base_distro: \"ubuntu\"
kolla_install_type: \"source\"
openstack_release: \"yoga\"
kolla_internal_vip_address: \"192.168.56.83\"
network_interface: \"eth1\"
neutron_external_interface: \"eth2\"
nova_compute_virt_type: \"qemu\"
enable_haproxy: \"no\"
EOF

    # Generate passwords
    kolla-genpwd

    # Bootstrap servers
    kolla-ansible -i multinode bootstrap-servers

    # Prechecks
    kolla-ansible -i multinode prechecks

    # Deploy OpenStack
    kolla-ansible -i multinode deploy

    # Post-deploy
    kolla-ansible -i multinode post-deploy

    # Install OpenStack CLI
    pip3 install python-openstackclient
"

if [ $? -eq 0 ]; then
    echo ""
    echo "✓ Kolla-Ansible OpenStack đã được triển khai thành công!"
    echo ""
    echo "Dashboard: http://192.168.56.83"
    echo "Admin credentials: /etc/kolla/admin-openrc.sh"
    echo ""
    echo "SSH Controller: vagrant ssh controller"
    echo "SSH Compute: vagrant ssh compute"
else
    echo "✗ Lỗi triển khai Kolla-Ansible"
    exit 1
fi