#!/bin/bash

# Exit immediately if a command exits with a non-zero status
set -e

echo "🛋️ Starting CouchDB Installation & Configuration..."

# 1. Define the Absolute Paths
BASE_DIR="/home/user/containerdata/couchdb"
ETC_DIR="$BASE_DIR/etc"
DATA_DIR="$BASE_DIR/data"
COMPOSE_FILE="$BASE_DIR/couchdb.yml"
ENV_FILE="$BASE_DIR/couchdb.env"

# 2. Ensure Host Directories Exist & Set Permissions
echo "📁 Ensuring volume directories exist and setting permissions..."
mkdir -p "$ETC_DIR"
mkdir -p "$DATA_DIR"

# Grant ownership to CouchDB's internal user (UID 5984) to prevent permission denied errors
chown -R 5984:5984 "$ETC_DIR" "$DATA_DIR"

# 3. Clean up existing configuration files
echo "🧹 Cleaning up existing configuration files..."
rm -f "$ENV_FILE"
rm -f "$COMPOSE_FILE"

# 4. Create the new couchdb.env File
echo "🔒 Generating secure couchdb.env file..."
GENERATED_PASSWORD=$(tr -dc A-Za-z0-9 </dev/urandom | head -c 16)
GENERATED_SECRET=$(tr -dc A-Za-z0-9 </dev/urandom | head -c 32)

cat <<EOF > "$ENV_FILE"
COUCHDB_USER=admin
COUCHDB_PASSWORD=$GENERATED_PASSWORD
COUCHDB_SECRET=$GENERATED_SECRET
EOF
echo "✅ couchdb.env file created. Save these credentials securely!"

# 5. Write the new couchdb.yml Configuration
echo "✍️ Writing Docker Compose configuration to couchdb.yml..."
cat <<EOF > "$COMPOSE_FILE"
services:
  mine-couchdb:
    container_name: mine-couchdb
    image: couchdb:3.3.3
    restart: unless-stopped
    ports:
      - "5984:5984"
    volumes:
      - $ETC_DIR:/opt/couchdb/etc/local.d 
      - $DATA_DIR:/opt/couchdb/data
    environment:
      - TZ=America/New_York
      - COUCHDB_USER=\${COUCHDB_USER}
      - COUCHDB_PASSWORD=\${COUCHDB_PASSWORD}
      - COUCHDB_SECRET=\${COUCHDB_SECRET}
    logging:
      driver: "json-file"
      options:
        max-size: "10m"   
        max-file: "3"     
    networks:
      user_default:
        ipv4_address: 172.18.0.4

networks:
  user_default:
    external: true
EOF
echo "✅ couchdb.yml created successfully."

# 6. Resolve Conflicts
echo "🛑 Cleaning up old containers to prevent conflicts..."
docker rm -f mine-couchdb 2>/dev/null || true

# 7. Start or Update the Container
echo "🚀 Starting CouchDB container via Docker Compose..."
cd "$BASE_DIR"

# Export the variables into the shell directly
set -a
# 🔑 THE FIX: Replaced 'source' with the POSIX-compliant '.' (dot)
. couchdb.env
set +a

# Start Docker Compose with --remove-orphans
docker compose -f couchdb.yml up -d --remove-orphans

echo "🎉 CouchDB is successfully configured and running on port 5984!"
echo "📂 Your data is safely stored in $BASE_DIR/data."
