#!/bin/bash
set -e

# Restore the original password
ORIGINAL_PASSWORD=$(echo "${SERVERLESS_CLUSTER_PASSWORD}" | sed 's/\\\$/\$/g' | sed 's/\\\!/\!/g' | sed 's/\\\^/\^/g')

echo "Creating the database if it doesn't exist..."
cat > ~/.my.cnf <<EOF
[client]
host=${SERVERLESS_CLUSTER_HOST}
port=${SERVERLESS_CLUSTER_PORT}
user='${SERVERLESS_CLUSTER_USERNAME}'
password='${ORIGINAL_PASSWORD}'
EOF

chmod 600 ~/.my.cnf

mysql -e "CREATE DATABASE IF NOT EXISTS \`${SERVERLESS_CLUSTER_DATABASE_NAME}\`;"

# Clone the repository
echo "Cloning repository..."
git clone https://github.com/tidb-samples/tidb-lab-ai

# Run Docker container
echo "Starting Docker container..."
sudo docker run -d \
  -p 3000:8080 \
  -p 8501:8501 \
  -p 8502:8502 \
  -v ./tidb-lab-ai:/root/tidb-lab-ai \
  cheesewang/tidb-lab-python-vscode:1.0
