apiVersion: batch/v1
kind: Job
metadata:
  name: nominatim-init
  namespace: bakery-ia
  labels:
    app.kubernetes.io/name: nominatim-init
    app.kubernetes.io/component: data-init
    app.kubernetes.io/part-of: bakery-ia
spec:
  ttlSecondsAfterFinished: 86400
  template:
    metadata:
      labels:
        app.kubernetes.io/name: nominatim-init
        app.kubernetes.io/component: data-init
    spec:
      imagePullSecrets:
      - name: dockerhub-creds
      restartPolicy: OnFailure
      containers:
      - name: nominatim-import
        image: mediagis/nominatim:4.4
        command:
        - sh
        - -c
        - |
          set -e
          echo "Checking if Nominatim database is already initialized..."

          if psql -lqt | cut -d \| -f 1 | grep -qw nominatim; then
            echo "Nominatim database already exists. Skipping import."
            exit 0
          fi

          echo "Downloading Spain OSM data..."
          wget -O /tmp/spain-latest.osm.pbf "${NOMINATIM_PBF_URL}"

          echo "Importing OSM data into Nominatim (this may take 30-60 minutes)..."
          nominatim import --osm-file /tmp/spain-latest.osm.pbf

          echo "Building search indices..."
          nominatim refresh --website --importance

          echo "Nominatim initialization complete!"
        volumeMounts:
        - name: nominatim-data
          mountPath: /var/lib/postgresql
        - name: nominatim-flatnode
          mountPath: /nominatim-flatnode
        env:
        - name: NOMINATIM_PBF_URL
          valueFrom:
            configMapKeyRef:
              name: nominatim-config
              key: NOMINATIM_PBF_URL
        - name: NOMINATIM_IMPORT_STYLE
          valueFrom:
            configMapKeyRef:
              name: nominatim-config
              key: NOMINATIM_IMPORT_STYLE
        - name: NOMINATIM_THREADS
          valueFrom:
            configMapKeyRef:
              name: nominatim-config
              key: NOMINATIM_THREADS
        - name: NOMINATIM_FLATNODE_FILE
          valueFrom:
            configMapKeyRef:
              name: nominatim-config
              key: NOMINATIM_FLATNODE_FILE
        resources:
          requests:
            memory: "8Gi"
            cpu: "4"
          limits:
            memory: "16Gi"
            cpu: "8"
      volumes:
      - name: nominatim-data
        persistentVolumeClaim:
          claimName: nominatim-data
      - name: nominatim-flatnode
        persistentVolumeClaim:
          claimName: nominatim-flatnode
