#cd ../docker
#docker buildx rm c3nav-local 2>/dev/null || true
#docker buildx create  --name c3nav-local --driver=docker-container --bootstrap --use
#cd ../local_run
docker compose down --remove-orphans
rm -rf data || true
cp -r data-copy data 
chmod 777 data
docker volume rm c3nav-postgres c3nav-redis || true
docker volume create c3nav-postgres
docker volume create c3nav-redis

# Start only postgres and redis first (no build since we pre-built)
docker compose up  -d postgres redis
sleep 10


cat ./db/auth_user.sql | docker exec -i local_run-postgres-1 su - postgres -c 'psql c3nav'

# Create Django superuser

sleep 1

# Load database dump before starting the main app
cat ./db/dump.sql |  docker exec -i local_run-postgres-1 su - postgres -c 'psql c3nav'

# Fix geometry access permissions for anonymous users
 docker exec -i local_run-postgres-1 psql -U postgres -d c3nav -c "UPDATE mapdata_space SET base_mapdata_accessible = true;"

# Now start the main services (no build since we pre-built)
docker compose up --build -d
echo "Creating Django superuser"
# docker exec -i local_run-c3nav-core-1 sh -c "echo \"from django.contrib.auth.models import User; [0].set_password('admin'); User.objects.get(username='admin').save()\" | /app/env/bin/python manage.py shell"
 docker exec -i local_run-c3nav-core-1 sh -c "echo \"
from django.contrib.auth.models import User
user = User.objects.get_or_create(username='admin', defaults={'email': 'admin@example.com', 'is_superuser': True, 'is_staff': True})[0]
user.set_password('admin')
user.save()
print('Password set successfully for user:', user.username)
\" | /app/env/bin/python manage.py shell"
sleep 30


# Fake apply all migrations since we loaded from dump
 docker exec -i local_run-c3nav-core-1 sh -c '/app/env/bin/python manage.py migrate --fake'

 docker compose ps -a
 docker exec -i local_run-c3nav-core-1 sh -c '/app/env/bin/python manage.py clearmapcache --include-history --include-geometries && /app/env/bin/python manage.py collectstatic -l --no-input'

# Fix NumPy compatibility issue
echo "Applying NumPy compatibility fix..."
 docker exec -i local_run-c3nav-core-1 sed -i 's/np\.fromstring(/np.frombuffer(/g' /app/c3nav/mapdata/utils/cache/indexed.py

# Process map updates to rebuild cache with NumPy fix
echo "Processing map updates to rebuild cache..."
 docker exec -i local_run-c3nav-core-1 sh -c '/app/env/bin/python manage.py processupdates'

