#!/bin/bash

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

# Khởi động VMs
echo "1. Khởi động OpenStack-Ansible cluster VMs..."
vagrant up

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

# Setup OpenStack-Ansible
echo "2. Setup OpenStack-Ansible..."
vagrant ssh deploy -c "
    # Clone OpenStack-Ansible
    git clone https://opendev.org/openstack/openstack-ansible /opt/openstack-ansible
    cd /opt/openstack-ansible
    git checkout stable/yoga

    # Bootstrap Ansible
    scripts/bootstrap-ansible.sh

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

    # Copy cấu hình mẫu
    cp -R etc/openstack_deploy/* /etc/openstack_deploy/

    # Tạo openstack_user_config.yml
    cat > /etc/openstack_deploy/openstack_user_config.yml << 'EOF'
---
cidr_networks:
  container: 172.29.236.0/22
  tunnel: 172.29.240.0/22
  storage: 172.29.244.0/22

used_ips:
  - \"172.29.236.1,172.29.236.50\"
  - \"172.29.240.1,172.29.240.50\"
  - \"172.29.244.1,172.29.244.50\"

global_overrides:
  internal_lb_vip_address: 172.29.236.100
  external_lb_vip_address: 192.168.56.100
  management_bridge: \"br-mgmt\"
  provider_networks:
    - network:
        container_bridge: \"br-mgmt\"
        container_type: \"veth\"
        container_interface: \"eth1\"
        ip_from_q: \"container\"
        type: \"raw\"
        group_binds:
          - all_containers
          - hosts
        is_container_address: true

shared-infra_hosts:
  infra1:
    ip: 172.29.236.86

repo-infra_hosts:
  infra1:
    ip: 172.29.236.86

os-infra_hosts:
  infra1:
    ip: 172.29.236.86

identity_hosts:
  infra1:
    ip: 172.29.236.86

compute_hosts:
  compute1:
    ip: 172.29.236.87

storage-infra_hosts:
  storage1:
    ip: 172.29.236.88

storage_hosts:
  storage1:
    ip: 172.29.236.88
    container_vars:
      cinder_backends:
        limit_container_types: cinder_volume
        lvm:
          volume_group: cinder-volumes
          volume_driver: cinder.volume.drivers.lvm.LVMVolumeDriver
          volume_backend_name: LVM_iSCSI
EOF

    # Generate passwords
    cd /opt/openstack-ansible
    python3 scripts/pw-token-gen.py --file /etc/openstack_deploy/user_secrets.yml

    # Setup target hosts
    openstack-ansible setup-hosts.yml

    # Setup infrastructure
    openstack-ansible setup-infrastructure.yml

    # Setup OpenStack
    openstack-ansible setup-openstack.yml
"

if [ $? -eq 0 ]; then
    echo ""
    echo "✓ OpenStack-Ansible đã được triển khai thành công!"
    echo ""
    echo "Dashboard: http://192.168.56.100"
    echo "SSH Deploy: vagrant ssh deploy"
    echo ""
    echo "Nodes:"
    echo "  Infrastructure: vagrant ssh infra1"
    echo "  Compute: vagrant ssh compute1"
    echo "  Storage: vagrant ssh storage1"
else
    echo "✗ Lỗi triển khai OpenStack-Ansible"
    exit 1
fi