aboutsummarylogtreecommitdiffstats
path: root/fpm
blob: c21fb7cf202acc4864854696cce28e1f4742d664 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
#!/usr/bin/env bash
# fpm - fuzzy pacman wrapper using skim (sk)
set -euo pipefail

cache_dir="/var/cache/pacman/pkg"

_sk() {
  local header="$1"; shift
  local query="${1:-}"
  # If first arg after header looks like a query (not starting with --), use it
  if [ -n "$query" ] && [[ ! "$query" =~ ^-- ]]; then
    shift
  else
    query=""
  fi
  
  sk \
    --ansi \
    --no-clear \
    --height 40% \
    --reverse \
    --prompt "fpm> " \
    --bind "tab:toggle+down,ctrl-u:half-page-up,ctrl-d:half-page-down,ctrl-r:toggle-preview" \
    --header "$header" \
    --tiebreak=begin,length \
    --preview-window=right:50%:wrap \
    ${query:+--query "$query"} \
    "$@"
}

_require_sk() { command -v sk >/dev/null || { echo "skim (sk) missing"; exit 1; }; }
_require_pacman() { command -v pacman >/dev/null || { echo "pacman missing"; exit 1; }; }

# Get AUR packages list (cached for performance)
_get_aur_packages() {
  local cache_file="/tmp/fpm_aur_cache_$$"
  local cache_age=3600 # 1 hour
  
  # Check if cache exists and is recent
  if [ -f "$cache_file" ] && [ $(($(date +%s) - $(stat -c %Y "$cache_file" 2>/dev/null || echo 0))) -lt $cache_age ]; then
    cat "$cache_file"
    return
  fi
  
  # Fetch AUR package list
  curl -s 'https://aur.archlinux.org/packages.gz' | gunzip | tail -n +2 | \
    awk '{printf "aur/%-40s %s\n", $1, $1}' | tee "$cache_file"
}

# Preview package info (official or AUR)
_preview_pkg() {
  local pkg="$1"
  local cache_dir="/tmp/fpm_preview_cache"
  local cache_file="$cache_dir/${pkg}.cache"
  local lock_file="$cache_dir/${pkg}.lock"
  local error_file="$cache_dir/${pkg}.error"
  local fetching_file="$cache_dir/${pkg}.fetching"
  
  # Validate input
  if [ -z "$pkg" ]; then
    echo "⚠️  No package selected"
    return
  fi
  
  # Create cache directory if it doesn't exist
  mkdir -p "$cache_dir"
  
  # Try official repos first (fast, no cache needed)
  if pacman -Si "$pkg" 2>/dev/null; then
    return
  fi
  
  # Check if we have a cached error (valid for 5 minutes)
  if [ -f "$error_file" ]; then
    local error_age=$(($(date +%s) - $(stat -c %Y "$error_file" 2>/dev/null || echo 0)))
    if [ $error_age -lt 300 ]; then
      cat "$error_file"
      return
    else
      rm -f "$error_file"
    fi
  fi
  
  # Check if we have a cached result (valid for 1 hour)
  if [ -f "$cache_file" ]; then
    local cache_age=$(($(date +%s) - $(stat -c %Y "$cache_file" 2>/dev/null || echo 0)))
    if [ $cache_age -lt 3600 ]; then
      cat "$cache_file"
      return
    fi
  fi
  
  # Check if currently being fetched by another process
  if [ -f "$fetching_file" ]; then
    local fetch_age=$(($(date +%s) - $(stat -c %Y "$fetching_file" 2>/dev/null || echo 0)))
    
    # If fetching file is older than 10 seconds, assume it's stale
    if [ $fetch_age -gt 10 ]; then
      rm -f "$fetching_file" "$lock_file"
    else
      echo "⏳ Loading package information..."
      return
    fi
  fi
  
  # Check if there's an active lock (another preview process)
  if [ -f "$lock_file" ]; then
    local lock_age=$(($(date +%s) - $(stat -c %Y "$lock_file" 2>/dev/null || echo 0)))
    
    # If lock is older than 10 seconds, assume it's stale
    if [ $lock_age -gt 10 ]; then
      rm -f "$lock_file"
    else
      # Another preview is being called, don't show anything (debounce)
      echo "🔍 Fetching AUR package information..."
      return
    fi
  fi
  
  # Create lock file to prevent multiple simultaneous fetches
  touch "$lock_file"
  
  # Small debounce delay - if lock disappears, another process took over
  sleep 0.05
  if [ ! -f "$lock_file" ]; then
    return
  fi
  
  # Mark as fetching
  touch "$fetching_file"
  
  # Show loading indicator
  echo "🔍 Fetching AUR package information..."
  
  # Fetch from AUR synchronously but with timeout
  local json=$(timeout 8 curl -s --max-time 8 "https://aur.archlinux.org/rpc/?v=5&type=info&arg=${pkg}" 2>/dev/null)
  local curl_exit=$?
  
  # Check if curl failed or timed out
  if [ $curl_exit -ne 0 ] || [ -z "$json" ]; then
    echo "❌ Network error: Failed to fetch package information" | tee "$error_file"
    rm -f "$lock_file" "$fetching_file"
    return
  fi
  
  # Check if we got valid JSON
  if ! echo "$json" | grep -q '"resultcount"'; then
    echo "❌ Invalid response from AUR API" | tee "$error_file"
    rm -f "$lock_file" "$fetching_file"
    return
  fi
  
  # Check if we got valid JSON with results
  local result_count=$(echo "$json" | grep -o '"resultcount":[0-9]*' | cut -d: -f2)
  
  if [ -z "$result_count" ] || [ "$result_count" -eq 0 ]; then
    echo "📦 Package not found in AUR" | tee "$cache_file"
    rm -f "$lock_file" "$fetching_file"
    return
  fi
  
  # Extract package data
  local name=$(echo "$json" | grep -o '"Name":"[^"]*"' | head -1 | cut -d'"' -f4)
  local version=$(echo "$json" | grep -o '"Version":"[^"]*"' | head -1 | cut -d'"' -f4)
  local description=$(echo "$json" | grep -o '"Description":"[^"]*"' | head -1 | cut -d'"' -f4)
  local url=$(echo "$json" | grep -o '"URL":"[^"]*"' | head -1 | cut -d'"' -f4)
  local maintainer=$(echo "$json" | grep -o '"Maintainer":"[^"]*"' | head -1 | cut -d'"' -f4)
  local votes=$(echo "$json" | grep -o '"NumVotes":[0-9]*' | head -1 | cut -d: -f2)
  local popularity=$(echo "$json" | grep -o '"Popularity":[0-9.]*' | head -1 | cut -d: -f2)
  local depends=$(echo "$json" | grep -o '"Depends":\[[^]]*\]' | sed 's/"Depends":\[//;s/\]//;s/"//g')
  local makedepends=$(echo "$json" | grep -o '"MakeDepends":\[[^]]*\]' | sed 's/"MakeDepends":\[//;s/\]//;s/"//g')
  
  # Validate we got at least the essential data
  if [ -z "$name" ]; then
    echo "⚠️  Incomplete package data received" | tee "$error_file"
    rm -f "$lock_file" "$fetching_file"
    return
  fi
  
  # Parse and format, then save to cache
  {
    echo "Repository      : aur"
    echo "Name            : ${name}"
    echo "Version         : ${version:-N/A}"
    
    if [ -z "$description" ]; then
      echo "Description     : (No description available)"
    else
      echo "Description     : ${description}"
    fi
    
    if [ -n "$url" ] && [ "$url" != "null" ]; then
      echo "URL             : ${url}"
    fi
    
    echo "Maintainer      : ${maintainer:-Orphaned}"
    echo "Votes           : ${votes:-0}"
    echo "Popularity      : ${popularity:-0}"
    
    # Extract dependencies if present
    if [ -n "$depends" ]; then
      echo "Depends On      : $depends"
    fi
    
    if [ -n "$makedepends" ]; then
      echo "Make Depends    : $makedepends"
    fi
  } | tee "$cache_file"
  
  # Remove lock and fetching files
  rm -f "$lock_file" "$fetching_file"
}

# new sync command
fpm_sync() {
  _require_pacman
  sudo -v || exit 1
  echo "🔄 Syncing pacman databases..."
  sudo pacman -Sy
}

_auto_sync() {
  fpm_sync
}

fpm_add() {
  local initial_query="$1"
  _auto_sync
  _require_sk; _require_pacman
  sudo -v || exit 1
  
  # Create a fast preview script
  local preview_script="/tmp/fpm_preview_$$"
  cat > "$preview_script" << 'PREVIEW_EOF'
#!/usr/bin/env bash
pkg="$1"
cache_dir="/tmp/fpm_preview_cache"
cache_file="$cache_dir/${pkg}.cache"
error_file="$cache_dir/${pkg}.error"
fetching_file="$cache_dir/${pkg}.fetching"
lock_file="$cache_dir/${pkg}.lock"

[ -z "$pkg" ] && { echo "⚠️  No package selected"; exit 0; }
mkdir -p "$cache_dir"

# Try official repos first (fast path)
if pacman -Si "$pkg" 2>/dev/null; then exit 0; fi

# Check cache first (fastest path)
if [ -f "$cache_file" ]; then
  cache_age=$(($(date +%s) - $(stat -c %Y "$cache_file" 2>/dev/null || echo 0)))
  if [ $cache_age -lt 3600 ]; then
    cat "$cache_file"
    exit 0
  fi
fi

# Check for cached error
if [ -f "$error_file" ]; then
  error_age=$(($(date +%s) - $(stat -c %Y "$error_file" 2>/dev/null || echo 0)))
  if [ $error_age -lt 300 ]; then
    cat "$error_file"
    exit 0
  fi
fi

# Check if fetching
if [ -f "$fetching_file" ]; then
  fetch_age=$(($(date +%s) - $(stat -c %Y "$fetching_file" 2>/dev/null || echo 0)))
  if [ $fetch_age -le 10 ]; then
    echo "⏳ Loading package information..."
    exit 0
  fi
  rm -f "$fetching_file" "$lock_file"
fi

# Check for active lock
if [ -f "$lock_file" ]; then
  lock_age=$(($(date +%s) - $(stat -c %Y "$lock_file" 2>/dev/null || echo 0)))
  if [ $lock_age -le 10 ]; then
    echo "🔍 Fetching AUR package information..."
    exit 0
  fi
  rm -f "$lock_file"
fi

# Acquire lock
touch "$lock_file"
sleep 0.05
[ ! -f "$lock_file" ] && exit 0

touch "$fetching_file"

# Fetch in background to not block
(
  json=$(timeout 8 curl -s --max-time 8 "https://aur.archlinux.org/rpc/?v=5&type=info&arg=${pkg}" 2>/dev/null)
  
  if [ $? -ne 0 ] || [ -z "$json" ]; then
    echo "❌ Network error: Failed to fetch package information" > "$error_file"
    rm -f "$lock_file" "$fetching_file"
    exit 0
  fi
  
  if ! echo "$json" | grep -q '"resultcount"'; then
    echo "❌ Invalid response from AUR API" > "$error_file"
    rm -f "$lock_file" "$fetching_file"
    exit 0
  fi
  
  result_count=$(echo "$json" | grep -o '"resultcount":[0-9]*' | cut -d: -f2)
  
  if [ -z "$result_count" ] || [ "$result_count" -eq 0 ]; then
    echo "📦 Package not found in AUR" > "$cache_file"
    rm -f "$lock_file" "$fetching_file"
    exit 0
  fi
  
  name=$(echo "$json" | grep -o '"Name":"[^"]*"' | head -1 | cut -d'"' -f4)
  [ -z "$name" ] && { echo "⚠️  Incomplete package data" > "$error_file"; rm -f "$lock_file" "$fetching_file"; exit 0; }
  
  version=$(echo "$json" | grep -o '"Version":"[^"]*"' | head -1 | cut -d'"' -f4)
  description=$(echo "$json" | grep -o '"Description":"[^"]*"' | head -1 | cut -d'"' -f4)
  url=$(echo "$json" | grep -o '"URL":"[^"]*"' | head -1 | cut -d'"' -f4)
  maintainer=$(echo "$json" | grep -o '"Maintainer":"[^"]*"' | head -1 | cut -d'"' -f4)
  votes=$(echo "$json" | grep -o '"NumVotes":[0-9]*' | head -1 | cut -d: -f2)
  popularity=$(echo "$json" | grep -o '"Popularity":[0-9.]*' | head -1 | cut -d: -f2)
  depends=$(echo "$json" | grep -o '"Depends":\[[^]]*\]' | sed 's/"Depends":\[//;s/\]//;s/"//g')
  makedepends=$(echo "$json" | grep -o '"MakeDepends":\[[^]]*\]' | sed 's/"MakeDepends":\[//;s/\]//;s/"//g')
  
  {
    echo "Repository      : aur"
    echo "Name            : ${name}"
    echo "Version         : ${version:-N/A}"
    echo "Description     : ${description:-(No description available)}"
    [ -n "$url" ] && [ "$url" != "null" ] && echo "URL             : ${url}"
    echo "Maintainer      : ${maintainer:-Orphaned}"
    echo "Votes           : ${votes:-0}"
    echo "Popularity      : ${popularity:-0}"
    [ -n "$depends" ] && echo "Depends On      : $depends"
    [ -n "$makedepends" ] && echo "Make Depends    : $makedepends"
  } > "$cache_file"
  
  rm -f "$lock_file" "$fetching_file"
) >/dev/null 2>&1 &
PREVIEW_EOF

# Wait for result with polling (max 8 seconds)
for i in {1..8}; do
  if [ -f "$cache_file" ] || [ -f "$error_file" ]; then
    # Result ready, display it
    [ -f "$cache_file" ] && cat "$cache_file" && exit 0
    [ -f "$error_file" ] && cat "$error_file" && exit 0
  fi
  
  # Still waiting, show progress
  if [ $i -eq 1 ]; then
    echo "🔍 Fetching AUR package information..."
  elif [ $i -le 3 ]; then
    echo "🔍 Fetching AUR package information."
  elif [ $i -le 5 ]; then
    echo "🔍 Fetching AUR package information.."
  else
    echo "🔍 Fetching AUR package information..."
  fi
  
  sleep 1
done

# Timeout - check one last time
if [ -f "$cache_file" ]; then
  cat "$cache_file"
elif [ -f "$error_file" ]; then
  cat "$error_file"
else
  echo "⏱️  Fetch timeout - please try again"
fi
  
  chmod +x "$preview_script"
  
  # Get list of installed packages for marking
  local installed_pkgs=$(pacman -Qq)
  
  # Combine official repos and AUR
  {
    pacman -Sl | awk -v installed="$installed_pkgs" '
      BEGIN { split(installed, inst_arr, "\n"); for (i in inst_arr) inst[inst_arr[i]] = 1 }
      { status = ($2 in inst) ? "[installed]" : ""; printf "%-20s %-40s %s\n", $1"/"$2, $2, status }'
    _get_aur_packages | awk -v installed="$installed_pkgs" '
      BEGIN { split(installed, inst_arr, "\n"); for (i in inst_arr) inst[inst_arr[i]] = 1 }
      { split($0, parts, " "); pkg = parts[2]; status = (pkg in inst) ? "[installed]" : ""; printf "%-20s %-40s %s\n", parts[1], pkg, status }'
  } | \
    _sk "TAB=select • ENTER=install (official + AUR)" "$initial_query" --multi \
      --preview "$preview_script {2}" | \
    awk '{print $2}' | \
    while read -r pkg; do
      # Check if package is in AUR or official repos
      if pacman -Si "$pkg" &>/dev/null; then
        sudo pacman -S "$pkg"
      else
        # Install from AUR using makepkg
        echo "Installing AUR package: $pkg"
        tmpdir=$(mktemp -d)
        cd "$tmpdir"
        curl -s "https://aur.archlinux.org/cgit/aur.git/snapshot/${pkg}.tar.gz" | tar xz
        cd "$pkg"
        makepkg -si
        cd -
        rm -rf "$tmpdir"
      fi
    done
  
  # Cleanup
  rm -f "$preview_script"
}

fpm_rm() {
  _require_sk
  sudo -v || exit 1
  pacman -Q | \
    _sk "TAB=select • ENTER=remove" --multi --preview "pacman -Qi {1}" | \
    awk '{print $1}' | \
    xargs -r sudo pacman -Rns --
}

fpm_search() {
  local initial_query="$1"
  _auto_sync
  _require_sk
  
  # Create a fast preview script
  local preview_script="/tmp/fpm_preview_$$"
  cat > "$preview_script" << 'PREVIEW_EOF'
#!/usr/bin/env bash
pkg="$1"
cache_dir="/tmp/fpm_preview_cache"
cache_file="$cache_dir/${pkg}.cache"
error_file="$cache_dir/${pkg}.error"
fetching_file="$cache_dir/${pkg}.fetching"
lock_file="$cache_dir/${pkg}.lock"

[ -z "$pkg" ] && { echo "⚠️  No package selected"; exit 0; }
mkdir -p "$cache_dir"

# Try official repos first (fast path)
if pacman -Si "$pkg" 2>/dev/null; then exit 0; fi

# Check cache first (fastest path)
if [ -f "$cache_file" ]; then
  cache_age=$(($(date +%s) - $(stat -c %Y "$cache_file" 2>/dev/null || echo 0)))
  if [ $cache_age -lt 3600 ]; then
    cat "$cache_file"
    exit 0
  fi
fi

# Check for cached error
if [ -f "$error_file" ]; then
  error_age=$(($(date +%s) - $(stat -c %Y "$error_file" 2>/dev/null || echo 0)))
  if [ $error_age -lt 300 ]; then
    cat "$error_file"
    exit 0
  fi
fi

# Check if fetching
if [ -f "$fetching_file" ]; then
  fetch_age=$(($(date +%s) - $(stat -c %Y "$fetching_file" 2>/dev/null || echo 0)))
  if [ $fetch_age -le 10 ]; then
    echo "⏳ Loading package information..."
    exit 0
  fi
  rm -f "$fetching_file" "$lock_file"
fi

# Check for active lock
if [ -f "$lock_file" ]; then
  lock_age=$(($(date +%s) - $(stat -c %Y "$lock_file" 2>/dev/null || echo 0)))
  if [ $lock_age -le 10 ]; then
    echo "🔍 Fetching AUR package information..."
    exit 0
  fi
  rm -f "$lock_file"
fi

# Acquire lock
touch "$lock_file"
sleep 0.05
[ ! -f "$lock_file" ] && exit 0

echo "🔍 Fetching AUR package information..."

# Fetch in background to not block
(
  json=$(timeout 8 curl -s --max-time 8 "https://aur.archlinux.org/rpc/?v=5&type=info&arg=${pkg}" 2>/dev/null)
  
  if [ $? -ne 0 ] || [ -z "$json" ]; then
    echo "❌ Network error: Failed to fetch package information" > "$error_file"
    rm -f "$lock_file" "$fetching_file"
    exit 0
  fi
  
  if ! echo "$json" | grep -q '"resultcount"'; then
    echo "❌ Invalid response from AUR API" > "$error_file"
    rm -f "$lock_file" "$fetching_file"
    exit 0
  fi
  
  result_count=$(echo "$json" | grep -o '"resultcount":[0-9]*' | cut -d: -f2)
  
  if [ -z "$result_count" ] || [ "$result_count" -eq 0 ]; then
    echo "📦 Package not found in AUR" > "$cache_file"
    rm -f "$lock_file" "$fetching_file"
    exit 0
  fi
  
  name=$(echo "$json" | grep -o '"Name":"[^"]*"' | head -1 | cut -d'"' -f4)
  [ -z "$name" ] && { echo "⚠️  Incomplete package data" > "$error_file"; rm -f "$lock_file" "$fetching_file"; exit 0; }
  
  version=$(echo "$json" | grep -o '"Version":"[^"]*"' | head -1 | cut -d'"' -f4)
  description=$(echo "$json" | grep -o '"Description":"[^"]*"' | head -1 | cut -d'"' -f4)
  url=$(echo "$json" | grep -o '"URL":"[^"]*"' | head -1 | cut -d'"' -f4)
  maintainer=$(echo "$json" | grep -o '"Maintainer":"[^"]*"' | head -1 | cut -d'"' -f4)
  votes=$(echo "$json" | grep -o '"NumVotes":[0-9]*' | head -1 | cut -d: -f2)
  popularity=$(echo "$json" | grep -o '"Popularity":[0-9.]*' | head -1 | cut -d: -f2)
  depends=$(echo "$json" | grep -o '"Depends":\[[^]]*\]' | sed 's/"Depends":\[//;s/\]//;s/"//g')
  makedepends=$(echo "$json" | grep -o '"MakeDepends":\[[^]]*\]' | sed 's/"MakeDepends":\[//;s/\]//;s/"//g')
  
  {
    echo "Repository      : aur"
    echo "Name            : ${name}"
    echo "Version         : ${version:-N/A}"
    echo "Description     : ${description:-(No description available)}"
    [ -n "$url" ] && [ "$url" != "null" ] && echo "URL             : ${url}"
    echo "Maintainer      : ${maintainer:-Orphaned}"
    echo "Votes           : ${votes:-0}"
    echo "Popularity      : ${popularity:-0}"
    [ -n "$depends" ] && echo "Depends On      : $depends"
    [ -n "$makedepends" ] && echo "Make Depends    : $makedepends"
  } > "$cache_file"
  
  rm -f "$lock_file" "$fetching_file"
) >/dev/null 2>&1 &

# Wait for result with polling (max 8 seconds)
for i in {1..8}; do
  if [ -f "$cache_file" ] || [ -f "$error_file" ]; then
    # Result ready, display it
    [ -f "$cache_file" ] && cat "$cache_file" && exit 0
    [ -f "$error_file" ] && cat "$error_file" && exit 0
  fi
  
  # Still waiting, show progress
  if [ $i -eq 1 ]; then
    echo "🔍 Fetching AUR package information..."
  elif [ $i -le 3 ]; then
    echo "🔍 Fetching AUR package information."
  elif [ $i -le 5 ]; then
    echo "🔍 Fetching AUR package information.."
  else
    echo "🔍 Fetching AUR package information..."
  fi
  
  sleep 1
done

# Timeout - check one last time
if [ -f "$cache_file" ]; then
  cat "$cache_file"
elif [ -f "$error_file" ]; then
  cat "$error_file"
else
  echo "⏱️  Fetch timeout - please try again"
fi
PREVIEW_EOF
  
  chmod +x "$preview_script"
  
  # Get list of installed packages for marking
  local installed_pkgs=$(pacman -Qq)
  
  # Combine official repos and AUR
  {
    pacman -Sl | awk -v installed="$installed_pkgs" '
      BEGIN { split(installed, inst_arr, "\n"); for (i in inst_arr) inst[inst_arr[i]] = 1 }
      { status = ($2 in inst) ? "[installed]" : ""; printf "%-20s %-40s %s\n", $1"/"$2, $2, status }'
    _get_aur_packages | awk -v installed="$installed_pkgs" '
      BEGIN { split(installed, inst_arr, "\n"); for (i in inst_arr) inst[inst_arr[i]] = 1 }
      { split($0, parts, " "); pkg = parts[2]; status = (pkg in inst) ? "[installed]" : ""; printf "%-20s %-40s %s\n", parts[1], pkg, status }'
  } | \
    _sk "Search packages (official + AUR)" "$initial_query" \
      --preview "$preview_script {2}"
  
  # Cleanup
  rm -f "$preview_script"
}

fpm_info() {
  _auto_sync
  _require_sk
  pacman -Q | _sk "Inspect package" --preview "pacman -Qi {1}"
}

fpm_update() {
  _auto_sync
  _require_sk
  pacman -Qu | _sk "Updates available" --preview "pacman -Si {1}"
}

fpm_files() {
  _require_sk
  pacman -Q | _sk "List package files" --preview "pacman -Ql {1}"
}

fpm_orphans() {
  _require_sk
  sudo -v || exit 1
  pacman -Qdt | \
    _sk "TAB=select • ENTER=remove orphans" --multi --preview "pacman -Qi {1}" | \
    awk '{print $1}' | \
    xargs -r sudo pacman -Rns --
}

fpm_file() {
  _require_sk
  pacman -Fl | _sk "File provider" --preview "pacman -Fl {1}"
}

fpm_own() {
  _require_sk
  find /usr -type f 2>/dev/null | \
    _sk "File owner" --preview "pacman -Qo {}"
}

fpm_repo() {
  _require_sk
  REPO=$(printf "core\nextra\ncommunity\nmultilib" | _sk "Select repo")
  [ -z "${REPO:-}" ] && return
  pacman -Sl "$REPO" | _sk "Browsing $REPO" --preview "pacman -Si {2}"
}

fpm_svc() {
  _require_sk
  systemctl list-units --type=service --all --no-pager | \
    awk '{print $1}' | \
    _sk "systemd services" --preview "systemctl status {1} --no-pager"
}


fpm_cache() {
  _require_sk
  sudo -v || exit 1
  while true; do
    sel=$(ls -1 "$cache_dir" | _sk "TAB=select • ENTER=delete • ESC=quit" --multi --preview "ls -lh $cache_dir/{1}")
    [ -z "${sel:-}" ] && break
    printf '%s\n' "$sel" | while read -r f; do sudo rm -v "$cache_dir/$f"; done
  done
}

fpm_bulk() {
  _require_sk
  ACTION=$(printf "%s\n" \
    "Sync pacman databases" \
    "Install packages" \
    "Remove packages" \
    "Search repository packages" \
    "Inspect installed packages" \
    "List files of installed packages" \
    "Remove orphan dependencies" \
    "Show available updates" \
    "Package providing a file (repo)" \
    "Package owning a file (system)" \
    "Browse repository" \
    "Systemd services browser" \
    "Clean cache (simple)" \
    "Clean cache (interactive)" \
    | _sk "Select action")
  case "$ACTION" in
    "Sync pacman databases") fpm_sync ;;
    "Install packages") fpm_add ;;
    "Remove packages") fpm_rm ;;
    "Search repository packages") fpm_search ;;
    "Inspect installed packages") fpm_info ;;
    "List files of installed packages") fpm_files ;;
    "Remove orphan dependencies") fpm_orphans ;;
    "Show available updates") fpm_update ;;
    "Package providing a file (repo)") fpm_file ;;
    "Package owning a file (system)") fpm_own ;;
    "Browse repository") fpm_repo ;;
    "Systemd services browser") fpm_svc ;;
    "Clean cache (interactive)") fpm_cache ;;
  esac
}

fpm_help() {
cat <<EOF
fpm - fuzzy pacman wrapper

Note: Searches official Arch repositories (core, extra, multilib) and AUR.

Commands:
  sync      Sync pacman databases (pacman -Sy)
  add       Install packages
  rm        Remove packages
  search    Search repository
  info      Inspect installed packages
  update    Show updates
  files     List package files
  orphans   Remove orphan dependencies
  file      Repo file provider lookup
  own       Installed file owner lookup
  repo      Browse repositories
  svc       Browse systemd services
  cache     Clean pacman cache
  bulk      Bulk menu
  help      Show help
EOF
}

_main() {
  if [ $# -eq 0 ]; then fpm_help; return; fi
  cmd="$1"; shift
  case "$cmd" in
    sync) fpm_sync ;;
    add) fpm_add "$@" ;;
    rm) fpm_rm ;;
    search) fpm_search "$@" ;;
    info) fpm_info ;;
    update) fpm_update ;;
    files) fpm_files ;;
    orphans) fpm_orphans ;;
    file) fpm_file ;;
    own) fpm_own ;;
    repo) fpm_repo ;;
    svc) fpm_svc ;;
    cache) fpm_cache ;;
    bulk) fpm_bulk ;;
    help|-h|--help) fpm_help ;;
    *) 
      # If not a known command, treat as search query
      fpm_search "$cmd" "$@"
      ;;
  esac
}

_main "$@"