#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "$0")/.." && pwd)"
UPSTREAM_DIR="$ROOT_DIR/../linuxcnc"
VENDOR_DIR="$ROOT_DIR/vendor/linuxcnc"
MANIFEST_FILE="$ROOT_DIR/tools/source-manifest.txt"

copy_file() {
  local src_rel="$1"
  local src="$UPSTREAM_DIR/$src_rel"
  local dst="$VENDOR_DIR/$src_rel"

  if [[ ! -f "$src" ]]; then
    echo "missing upstream file: $src" >&2
    exit 1
  fi

  mkdir -p "$(dirname "$dst")"
  if [[ -f "$dst" ]] && cmp -s "$src" "$dst"; then
    touch -r "$src" "$dst"
    echo "unchanged $src_rel"
    return
  fi

  cp -p "$src" "$dst"
  echo "copied $src_rel"
}

if [[ ! -f "$MANIFEST_FILE" ]]; then
  echo "missing manifest: $MANIFEST_FILE" >&2
  exit 1
fi

validate_manifest_path() {
  local src_rel="$1"
  if [[ "$src_rel" = /* || "$src_rel" == */ || "$src_rel" == *"//"* ]]; then
    return 1
  fi

  local component
  local -a path_components
  IFS=/ read -r -a path_components <<< "$src_rel"
  for component in "${path_components[@]}"; do
    if [[ -z "$component" || "$component" == "." || "$component" == ".." ]]; then
      return 1
    fi
  done
}

while IFS= read -r src_rel; do
  [[ -z "$src_rel" ]] && continue
  [[ "${src_rel:0:1}" == "#" ]] && continue
  if ! validate_manifest_path "$src_rel"; then
    echo "invalid manifest path: $src_rel" >&2
    exit 1
  fi
  copy_file "$src_rel"
done < "$MANIFEST_FILE"

echo "extraction complete"
