#!/bin/bash

# Required: ontologies must be RDF/XML or Turtle and include rdfs:label and owl:versionInfo.
# schema:image is optional — if absent, Widoco runs with webVOWL enabled.

#SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
WIDOCO="$1"
REMOTE_USER="$2"
REMOTE_HOST="$3"
BASE_PATH="$4"
ONTOLOGIES_DIR="$5"
FILE_CONFIG=$ONTOLOGIES_DIR/ontodoc_files
OUTFOLDER="/var/www/ontology-documentation/"


process_ontology() {
  ONTOLOGY_FILE="$1"

  echo "🚀 Processing: $ONTOLOGY_FILE"

  # Use Python to extract rdfs:label, owl:versionInfo, and schema:image
  read -r LABEL VERSION IMAGE <<<$(python3 - "$ONTOLOGY_FILE" <<EOF
from rdflib import Graph, Namespace, OWL, RDFS, URIRef
from rdflib.namespace import RDF
import sys

SCHEMA = Namespace("http://schema.org/")
g = Graph()
g.parse(sys.argv[1])

label = version = image = "unknown"

for s in g.subjects(RDF.type, OWL.Ontology):
    label_value = g.value(subject=s, predicate=RDFS.label)
    if label_value and str(label_value).strip():
        label = str(label_value).strip().replace(" ", "-").lower()
    version_value = g.value(subject=s, predicate=OWL.versionInfo)
    if version_value:
        version = str(version_value).strip().replace(" ", "_")
    image_value = g.value(subject=s, predicate=SCHEMA.image)
    if image_value:
        image = str(image_value).strip()
    break

print(label, version, image)
EOF
)

  # Skip processing if label is missing
  if [ "$LABEL" = "unknown" ]; then
    echo "⛔ Skipping: missing rdfs:label in $ONTOLOGY_FILE"
    return
  fi

  # Use 'current' if version is missing
  if [ "$VERSION" = "unknown" ]; then
    VERSION="current"
    echo "⚠️  Missing owl:versionInfo — using fallback: $VERSION"
  fi

  # Construct the output path
  OUTFOLDER+="$LABEL/$VERSION"
  mkdir -p "$OUTFOLDER"

  echo "🏷 Label: $LABEL"
  echo "🔢 Version: $VERSION"
  echo "🖼 Image: $IMAGE"
  echo "📁 Output folder: $OUTFOLDER"

  # Build base Widoco command
  CMD=(java -jar "$WIDOCO" \
    -ontFile "$ONTOLOGY_FILE" \
    -outFolder "$OUTFOLDER" \
    -getOntologyMetadata \
    -lang cs \
    -rewriteAll)

  # Add webVOWL flag if no image is present
  if [ "$IMAGE" = "unknown" ]; then
    echo "🔍 No schema:image found — enabling webVOWL visualization."
    CMD+=( -webVowl )
  fi

  # Run Widoco with assembled command
  "${CMD[@]}" > /dev/null 2>&1

  # Strict access, no references and image goes with docs
  sed -i '/<div id="references">/,/<\/div>/d' $OUTFOLDER/index-cs.html
  mv $OUTFOLDER/index-cs.html $OUTFOLDER/index.html
  cp $IMAGE $OUTFOLDER
  chmod -R 755 $OUTFOLDER

  echo "✅ Documentation generated at: $OUTFOLDER"

  #TODO: Move docs to the server where it belongs

  # Create remote path according to the ontology and version
  DOC_PATH=$BASE_PATH/ontologies/$LABEL
  REMOTE_PATH=$DOC_PATH/$VERSION

  # Check if target dir exists on remote server; if not, create it
  ssh -o StrictHostKeyChecking=no "${REMOTE_USER}@${REMOTE_HOST}" "mkdir -p '${DOC_PATH}'"
  echo "Documentation path: $DOC_PATH"

  # Resolve symlink
  ssh $REMOTE_USER@$REMOTE_HOST "cd '$DOC_PATH' && \
    if [ ! -L current ]; then
      echo '📌 Symlink current does not exist — creating it...'; \
      ln -s '$VERSION' current; \
    else
      CURRENT_TARGET=\$(readlink current); \
      if [ \"\$CURRENT_TARGET\" != \"$VERSION\" ]; then \
        echo '🔄 Updating symlink: current → $VERSION'; \
        ln -sfn '$VERSION' current; \
      else
        echo '✅ current already points to the latest version'; \
      fi; \
    fi"

    # Copy data to symlink path
    scp -r $OUTFOLDER $REMOTE_USER@$REMOTE_HOST:$DOC_PATH
    echo "✅ data copied to $DOC_PATH"; 

    # Restart apache - maybe once after all ontologies are processed
    ssh -o StrictHostKeyChecking=no "$REMOTE_USER@$REMOTE_HOST" "sudo systemctl reload apache2" 
    echo "🚀 Apache restarted."

}


# Collect all files from file_config
EXT_REGEX='\.ttl$|\.rdf$|\.owl$'
FILES_TO_PROCESS=()


# If file_config is missing or empty, exit quietly
if [[ ! -f "$FILE_CONFIG" || ! -s "$FILE_CONFIG" ]]; then
  echo "⛔ file_config on location '$FILE_CONFIG' is missing or empty — skipping ontology processing."
  exit 0
fi

# Parse file_config
while IFS= read -r line || [ -n "$line" ]; do
  [[ "$line" =~ ^#.*$ || -z "$line" ]] && continue

  case "$line" in
    "*")
      while IFS= read -r f; do
        FILES_TO_PROCESS+=("$f")
      done < <(find "$ONTOLOGIES_DIR" -type f \( -iname "*.ttl" -o -iname "*.rdf" -o -iname "*.owl" \))
      ;;
    ".")
      for f in "$ONTOLOGIES_DIR"/*.{ttl,rdf,owl}; do
        [ -e "$f" ] && FILES_TO_PROCESS+=("$f")
      done
      ;;
    *)
      FULL_PATH="$ONTOLOGIES_DIR/$line"
      if [ -d "$FULL_PATH" ]; then
        for f in "$FULL_PATH"/*.{ttl,rdf,owl}; do
          [ -e "$f" ] && FILES_TO_PROCESS+=("$f")
        done
      elif [ -f "$FULL_PATH" ]; then
        if [[ "$FULL_PATH" =~ $EXT_REGEX ]]; then
          FILES_TO_PROCESS+=("$FULL_PATH")
        else
          echo "⛔ Skipping unsupported file type: $FULL_PATH"
        fi
      else
        echo "⚠️ Warning: '$line' not found in repository."
      fi
      ;;
  esac
done < "$FILE_CONFIG"

# Loop over RDF/Turtle/Ontology files in the script's directory
for file in "${FILES_TO_PROCESS[@]}"; do
	process_ontology "$file"
  echo "====================================================================="
done

