#!/bin/bash
set -e
echo "Stopping all containers..."
cd /opt/fzx/deploy
podman-compose -f podman-compose.aliyun-dev.yml stop

echo "Removing all containers..."
podman rm -f fzx-aliyun-gateway fzx-aliyun-user fzx-aliyun-auth fzx-aliyun-merchant fzx-aliyun-order fzx-aliyun-rider fzx-aliyun-product fzx-aliyun-map fzx-aliyun-marketing fzx-aliyun-upload fzx-aliyun-platform fzx-aliyun-nacos fzx-aliyun-redis fzx-aliyun-mariadb fzx-aliyun-registry fzx-aliyun-nginx fzx-aliyun-webhook-handler fzx-aliyun-jenkins

echo "Removing mariadb volume..."
podman volume rm fzx-aliyun-mariadb-data

echo "Creating init scripts..."
mkdir -p /opt/fzx/infrastructure/database/mariadb/init
cat > /opt/fzx/infrastructure/database/mariadb/init/00_init.sql << 'EOF'
CREATE DATABASE IF NOT EXISTS fzx_local_life DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE DATABASE IF NOT EXISTS nacos_config DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER IF NOT EXISTS 'fzx_app'@'%' IDENTIFIED BY 'Fzx@2024!app';
GRANT ALL ON fzx_local_life.* TO 'fzx_app'@'%';
GRANT ALL ON nacos_config.* TO 'fzx_app'@'%';
FLUSH PRIVILEGES;
EOF

echo "Starting mariadb..."
podman-compose -f podman-compose.aliyun-dev.yml up -d mariadb

echo "Waiting for mariadb..."
sleep 30

echo "Verifying connection..."
podman exec fzx-aliyun-mariadb mysql -u fzx_app -pFzx@2024!app -e "SELECT 1;"

echo "Starting all containers..."
podman-compose -f podman-compose.aliyun-dev.yml up -d

echo "Done!"