#!/bin/bash
set -e

PROD_HOST='https://shamraindex:9200'
PROD_USER='elastic'
PROD_PASS='<ES_PASSWORD>'
PROD_AUTH="$PROD_USER:$PROD_PASS"
LOCAL='http://localhost:9200'

reindex_from_prod() {
    local INDEX=$1
    echo "=== Processing $INDEX ==="
    
    # Delete local index
    echo "Deleting local index..."
    curl -s -X DELETE "$LOCAL/$INDEX" || true
    echo ''

    # Get mapping from prod
    echo "Getting mapping from prod..."
    MAPPING=$(curl -s -u $PROD_AUTH "$PROD_HOST/$INDEX/_mappings" | python3 -c "import sys,json; d=json.load(sys.stdin); print(json.dumps(list(d.values())[0]['mappings']))")
    
    # Create local index
    echo "Creating local index..."
    curl -s -X PUT "$LOCAL/$INDEX" -H 'Content-Type: application/json' -d '{
        "settings": {"number_of_shards": 1, "number_of_replicas": 0},
        "mappings": '"$MAPPING"'
    }'
    echo ''

    # Reindex from prod
    echo "Reindexing from prod (this may take a while)..."
    curl -s -X POST "$LOCAL/_reindex?wait_for_completion=true&timeout=60m" -H 'Content-Type: application/json' -d '{
        "source": {
            "remote": {"host": "'"$PROD_HOST"'", "username": "'"$PROD_USER"'", "password": "'"$PROD_PASS"'"},
            "index": "'"$INDEX"'"
        },
        "dest": {"index": "'"$INDEX"'"}
    }'
    echo ''
    
    # Verify count
    echo "Verifying doc count..."
    curl -s "$LOCAL/_cat/indices/$INDEX?v&h=index,docs.count"
    echo "=== Done with $INDEX ==="
    echo ''
}

reindex_from_prod arabic_research_v1.0
reindex_from_prod english_research
reindex_from_prod arabic_research_lmd

echo 'All indices complete!'
