#!/bin/bash
CONFIG="/opt/scripts_local/mount_delayed_table.conf"
BACKUP="$CONFIG.bak.$(date +%Y%m%d_%H%M%S)"
TMP_FILE="$(mktemp)"
EXPECTED_FIELDS=10

DRY_RUN=0
SHOW_DIFF=0

while [[ $# -gt 0 ]]; do
  case "$1" in
    --dry-run) DRY_RUN=1 ;;
    --diff) SHOW_DIFF=1 ;;
    -h|--help)
      echo "Usage: $0 [--dry-run] [--diff]"
      echo "  --dry-run   Show what would be changed, but don’t write"
      echo "  --diff      Show unified diff between original and corrected version"
      exit 0
      ;;
    *) echo "❌ Unknown option: $1"; exit 1 ;;
  esac
  shift
done

echo "=============================="
echo "✅ Valid Mount Entry Examples:"
echo "=============================="
cat <<'EOF'
# CIFS
server.example.com | share1      | /mnt/share1        | cifs   | user1    | group1   | 0770 | -           | -         | -

# NFS
nfs.example.com    | /export     | /mnt/nfsdata       | nfs    | root     | root     | -    | -           | -         | -

# BINDFS (with creation user and permissions)
-                  | /data       | /mnt/data_bindfs   | bindfs | user2    | group2   | -    | u=rwX:g=rwX | user2     | 0755

# BINDFS (view only)
-                  | /data       | /mnt/data_bindfs   | bindfs | user2    | group2   | -    | u=rwX       | -         | -
EOF
echo "------------------------------"
echo

echo "📂 Validating config: $CONFIG"
[[ $DRY_RUN -eq 0 ]] && echo "📦 Backup saved as: $BACKUP"

cp "$CONFIG" "$BACKUP"

line_number=0
corrections=0

while IFS= read -r line || [[ -n "$line" ]]; do
  ((line_number++))

  if [[ "$line" =~ ^[[:space:]]*# ]] || [[ -z "${line//|/}" ]]; then
    echo "$line" >> "$TMP_FILE"
    continue
  fi

  field_count=$(awk -F'|' '{print NF}' <<< "$line")

  if [[ "$field_count" -lt $EXPECTED_FIELDS ]]; then
    echo "⚠️  Line $line_number has $field_count fields — will be corrected"
    fixed_line="$line"
    while [[ $(awk -F'|' '{print NF}' <<< "$fixed_line") -lt $EXPECTED_FIELDS ]]; do
      fixed_line="${fixed_line} | -"
    done
    echo "# [autofix] original line had $field_count fields:" >> "$TMP_FILE"
    echo "# $line" >> "$TMP_FILE"
    echo "$fixed_line" >> "$TMP_FILE"
    ((corrections++))
    continue
  fi

  # Parse and check type
  IFS='|' read -r server share dest type uid gid mode view_perms create_user file_perms <<< "$line"
  read -r server share dest type uid gid mode view_perms create_user file_perms <<< \
    "$(echo "$server $share $dest $type $uid $gid $mode $view_perms $create_user $file_perms" | xargs -n10)"

  if [[ ! "$type" =~ ^(cifs|nfs|bindfs)$ ]]; then
    echo "⚠️  Line $line_number has unknown mount type: '$type'"
    echo "# [invalid-type] $line" >> "$TMP_FILE"
    continue
  fi

  echo "$line" >> "$TMP_FILE"
done < "$CONFIG"

echo
if [[ $corrections -gt 0 ]]; then
  echo "✅ $corrections correction(s) made."
else
  echo "✅ No corrections needed."
fi

if [[ $SHOW_DIFF -eq 1 ]]; then
  echo
  echo "📄 Diff between current and corrected version:"
  diff -u "$BACKUP" "$TMP_FILE" || true
  echo
fi

if [[ $DRY_RUN -eq 1 ]]; then
  echo "🧪 Dry run: no changes written to $CONFIG"
  rm "$TMP_FILE"
else
  echo "💾 Writing corrected config to: $CONFIG"
  mv "$TMP_FILE" "$CONFIG"
fi