#!/bin/bash
set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
OUTPUT_DIR="$PROJECT_ROOT/output"
STAGING_DIR="$PROJECT_ROOT/staging"
VARIANTS_DIR="$PROJECT_ROOT/variants"
VERSION="$(tr -d '[:space:]' < "$PROJECT_ROOT/VERSION")"
ZIP_EXCLUDE=(-x "*.DS_Store" -x "*__MACOSX*" -x "._*")

# Clear output directory
clear_output_directory() {
  echo "Loesche Output-Verzeichnis..."
  rm -rf "$OUTPUT_DIR"
  mkdir -p "$OUTPUT_DIR"
  echo "Output-Verzeichnis geloescht."
}

# Update manifest.ini version in build directory
update_manifest_version() {
  local build_dir="$1"
  local variant_dir="$2"
  local manifest_path="$build_dir/$variant_dir/config/omninx/manifest.ini"
  if [[ -f "$manifest_path" ]]; then
    if [[ "$(uname)" == "Darwin" ]]; then
      sed -i '' "s/^version=.*/version=$VERSION/" "$manifest_path"
    else
      sed -i "s/^version=.*/version=$VERSION/" "$manifest_path"
    fi
  fi
}

# Light: Staging (Root) + Ordner "OmniNX Light" = variants/light
build_light() {
  local build_dir
  build_dir="$(mktemp -d)"
  echo "Baue OmniNX Light..."
  cp -R "$STAGING_DIR/." "$build_dir/"
  mkdir -p "$build_dir/OmniNX Light"
  cp -R "$VARIANTS_DIR/light/." "$build_dir/OmniNX Light/"
  update_manifest_version "$build_dir" "OmniNX Light"
  mkdir -p "$OUTPUT_DIR"
  cd "$build_dir" && zip -q -r "$OUTPUT_DIR/OmniNX-Light-$VERSION.zip" . "${ZIP_EXCLUDE[@]}" && cd "$PROJECT_ROOT"
  rm -rf "$build_dir"
}

# Standard: Staging (Root) + Ordner "OmniNX Standard" = light, dann standard drueber
build_standard() {
  local build_dir
  build_dir="$(mktemp -d)"
  echo "Baue OmniNX Standard..."
  cp -R "$STAGING_DIR/." "$build_dir/"
  mkdir -p "$build_dir/OmniNX Standard"
  cp -R "$VARIANTS_DIR/light/." "$build_dir/OmniNX Standard/"
  cp -R "$VARIANTS_DIR/standard/." "$build_dir/OmniNX Standard/"
  update_manifest_version "$build_dir" "OmniNX Standard"
  mkdir -p "$OUTPUT_DIR"
  cd "$build_dir" && zip -q -r "$OUTPUT_DIR/OmniNX-Standard-$VERSION.zip" . "${ZIP_EXCLUDE[@]}" && cd "$PROJECT_ROOT"
  rm -rf "$build_dir"
}

# OC: Staging (Root) + Ordner "OmniNX OC" = light, dann standard, dann oc drueber
build_oc() {
  local build_dir
  build_dir="$(mktemp -d)"
  echo "Baue OmniNX OC..."
  cp -R "$STAGING_DIR/." "$build_dir/"
  mkdir -p "$build_dir/OmniNX OC"
  cp -R "$VARIANTS_DIR/light/." "$build_dir/OmniNX OC/"
  cp -R "$VARIANTS_DIR/standard/." "$build_dir/OmniNX OC/"
  cp -R "$VARIANTS_DIR/oc/." "$build_dir/OmniNX OC/"
  update_manifest_version "$build_dir" "OmniNX OC"
  mkdir -p "$OUTPUT_DIR"
  cd "$build_dir" && zip -q -r "$OUTPUT_DIR/OmniNX-OC-$VERSION.zip" . "${ZIP_EXCLUDE[@]}" && cd "$PROJECT_ROOT"
  rm -rf "$build_dir"
}

mkdir -p "$OUTPUT_DIR"
clear_output_directory
build_light
build_standard
build_oc
echo "Alle Varianten gebaut."
