#!/bin/bash

echo "=== Deploy DevStack OpenStack ==="

# Khởi động VM
echo "1. Khởi động DevStack VM..."
vagrant up

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

# Deploy DevStack
echo "2. Deploy DevStack..."
vagrant ssh -c "
    # Tạo stack user
    sudo useradd -s /bin/bash -d /opt/stack -m stack
    echo 'stack ALL=(ALL) NOPASSWD: ALL' | sudo tee /etc/sudoers.d/stack

    # Clone DevStack
    sudo -u stack git clone https://opendev.org/openstack/devstack /opt/stack/devstack

    # Tạo local.conf
    sudo -u stack tee /opt/stack/devstack/local.conf << 'EOF'
[[local|localrc]]
ADMIN_PASSWORD=admin123
DATABASE_PASSWORD=db123
RABBIT_PASSWORD=rabbit123
SERVICE_PASSWORD=service123

HOST_IP=192.168.56.80
LOGFILE=/opt/stack/logs/stack.sh.log

# Services
enable_service rabbit mysql key
enable_service n-api n-crt n-obj n-cpu n-cond n-sch n-novnc n-cauth
enable_service placement-api placement-client
enable_service g-api g-reg
enable_service c-sch c-api c-vol
enable_service horizon
enable_service neutron q-svc q-agt q-dhcp q-l3 q-meta

# Disable some services for faster deployment
disable_service tempest
disable_service c-bak
EOF

    # Chạy DevStack
    cd /opt/stack/devstack
    sudo -u stack ./stack.sh
"

if [ $? -eq 0 ]; then
    echo ""
    echo "✓ DevStack OpenStack đã được triển khai thành công!"
    echo ""
    echo "Dashboard: http://192.168.56.80"
    echo "Username: admin"
    echo "Password: admin123"
    echo ""
    echo "SSH: vagrant ssh"
else
    echo "✗ Lỗi triển khai DevStack"
    exit 1
fi