-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcursor-setup-ubuntu.sh
More file actions
executable file
·1491 lines (1305 loc) · 52.3 KB
/
cursor-setup-ubuntu.sh
File metadata and controls
executable file
·1491 lines (1305 loc) · 52.3 KB
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
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bash
# -------------------------------------------------------------------
# Cursor Setup Ubuntu Script - Enhanced Version
# -------------------------------------------------------------------
# This script provides an intelligent, automated way to download,
# install, and manage Cursor AI AppImage on Ubuntu-based systems.
#
# FEATURES:
# - Enhanced security with file validation
# - Robust error handling and process management
# - Internationalization support (EN/ES)
# - Configurable timeouts and retry logic
# - Smart process detection and backup management
# - Colored logging with timestamps
# - System requirements validation
#
# Author: Daniel Ignacio Fernández
# Version: 2.1.2 - Cursor 2.x Compatibility & Detection Fixes
#
# IMPROVEMENTS IN v2.1.2:
# - Full support for Cursor 2.x versions (tested with 2.0.11)
# - Fixed automatic version detection from cursor-ai-downloads repository
# - Fixed installation detection (glob pattern expansion bug)
# - Improved network resilience (flexible ping checks with Google DNS fallback)
# - Increased curl timeout from 5s to 10s for better reliability
# - Enhanced content validation (minimum 1KB size check)
# - Extensive debug mode logging for troubleshooting
# - Fixed glob pattern quoting in check_cursor_installation() and remove_old_versions()
# -------------------------------------------------------------------
set -euo pipefail
# -------------------------------------------------------------------
# Standard Exit Codes
# -------------------------------------------------------------------
readonly EXIT_SUCCESS=0
readonly EXIT_ERROR=1
readonly EXIT_NO_ACTION=2
readonly EXIT_USER_CANCEL=3
# -------------------------------------------------------------------
# Configuration Constants
# -------------------------------------------------------------------
readonly MIN_APPIMAGE_SIZE=104857600 # 100MB minimum size for AppImage validation
readonly MAX_WAIT_ATTEMPTS=12 # Maximum wait attempts for process termination (2 minutes with 10s intervals)
readonly WAIT_INTERVAL=10 # Wait interval in seconds between process checks
readonly MENU_CHOICE_TIMEOUT=30 # Timeout for menu choice selection
readonly DEFAULT_CONFIRMATION_TIMEOUT=60 # Default confirmation timeout
# -------------------------------------------------------------------
# Use the real user's home directory even when running with sudo
# -------------------------------------------------------------------
if [ -n "${SUDO_USER:-}" ]; then
readonly REAL_HOME=$(getent passwd "$SUDO_USER" | cut -d: -f6)
else
readonly REAL_HOME="$HOME"
fi
# -------------------------------------------------------------------
# Auto-detect system language
# -------------------------------------------------------------------
detect_system_language() {
local detected_lang="EN"
# Method 1: Check LANG/LANGUAGE environment variables
if [[ "${LANG,,}" == *"es"* ]] || [[ "${LANGUAGE,,}" == *"es"* ]]; then
detected_lang="ES"
fi
# Method 2: Check if Spanish desktop directories exist
if [[ -d "$REAL_HOME/Escritorio" ]] || [[ -d "$REAL_HOME/Descargas" ]]; then
detected_lang="ES"
fi
# Method 3: Check if English desktop directories exist (fallback)
if [[ -d "$REAL_HOME/Desktop" ]] && [[ ! -d "$REAL_HOME/Escritorio" ]]; then
detected_lang="EN"
fi
# Method 4: Check system locale
if command -v locale >/dev/null 2>&1; then
if locale | grep -i "LANG.*es" >/dev/null 2>&1; then
detected_lang="ES"
fi
fi
# Method 5: Check GNOME/KDE language settings
if [[ -f "$REAL_HOME/.config/user-dirs.dirs" ]]; then
if grep -q "Escritorio\|Descargas" "$REAL_HOME/.config/user-dirs.dirs" 2>/dev/null; then
detected_lang="ES"
fi
fi
echo "$detected_lang"
}
# Use auto-detected language or override with environment variable
readonly LANG_SETTING="${LANG_SETTING:-$(detect_system_language)}"
# -------------------------------------------------------------------
# User experience settings
# -------------------------------------------------------------------
readonly ENABLE_COLORS="${ENABLE_COLORS:-true}"
readonly ENABLE_DEBUG="${DEBUG_MODE:-false}"
readonly MENU_TIMEOUT="${MENU_TIMEOUT:-300}"
readonly CONFIRMATION_TIMEOUT="${CONFIRMATION_TIMEOUT:-60}"
readonly DOWNLOAD_TIMEOUT="${DOWNLOAD_TIMEOUT:-300}"
readonly MAX_RETRY_ATTEMPTS="${MAX_RETRY_ATTEMPTS:-3}"
# Set language-dependent paths using the real user's home directory
if [[ "$LANG_SETTING" == "EN" ]]; then
readonly USER_DESKTOP_DIR="$REAL_HOME/Desktop"
readonly USER_DOWNLOADS_DIR="$REAL_HOME/Downloads"
else
readonly USER_DESKTOP_DIR="$REAL_HOME/Escritorio"
readonly USER_DOWNLOADS_DIR="$REAL_HOME/Descargas"
fi
# -------------------------------------------------------------------
# Enhanced logging function with timestamps and colors
# Usage: logg <type> <message>
# Types: error, info, prompt, success, warn, debug
# -------------------------------------------------------------------
logg() {
local TYPE="$1"
local MSG="$2"
local TIMESTAMP
TIMESTAMP=$(date '+%Y-%m-%d %H:%M:%S')
# Color codes (can be disabled with LOG_COLORS=false)
local RED='\033[0;31m'
local GREEN='\033[0;32m'
local YELLOW='\033[1;33m'
local BLUE='\033[0;34m'
local NC='\033[0m' # No Color
case "$TYPE" in
error)
if [[ "${LOG_COLORS:-true}" == "true" ]]; then
echo -e "${RED}[$TIMESTAMP] ERROR: $MSG${NC}" >&2
else
echo "[$TIMESTAMP] ERROR: $MSG" >&2
fi
;;
info)
if [[ "${LOG_COLORS:-true}" == "true" ]]; then
echo -e "${BLUE}[$TIMESTAMP] INFO: $MSG${NC}"
else
echo "[$TIMESTAMP] INFO: $MSG"
fi
;;
prompt)
if [[ "${LOG_COLORS:-true}" == "true" ]]; then
echo -e "${YELLOW}[$TIMESTAMP] PROMPT: $MSG${NC}"
else
echo "[$TIMESTAMP] PROMPT: $MSG"
fi
;;
success)
if [[ "${LOG_COLORS:-true}" == "true" ]]; then
echo -e "${GREEN}[$TIMESTAMP] SUCCESS: $MSG${NC}"
else
echo "[$TIMESTAMP] SUCCESS: $MSG"
fi
;;
warn)
if [[ "${LOG_COLORS:-true}" == "true" ]]; then
echo -e "${YELLOW}[$TIMESTAMP] WARNING: $MSG${NC}"
else
echo "[$TIMESTAMP] WARNING: $MSG"
fi
;;
debug)
if [[ "${DEBUG_MODE:-false}" == "true" ]]; then
if [[ "${LOG_COLORS:-true}" == "true" ]]; then
echo -e "${BLUE}[$TIMESTAMP] DEBUG: $MSG${NC}"
else
echo "[$TIMESTAMP] DEBUG: $MSG"
fi
fi
;;
*)
echo "[$TIMESTAMP] $MSG"
;;
esac
}
# -------------------------------------------------------------------
# Internationalization function for user messages
# -------------------------------------------------------------------
i18n() {
local key="$1"
local fallback="${2:-}"
case "$LANG_SETTING" in
"ES")
case "$key" in
"menu_title") echo "=== Menú de Configuración de Cursor ===" ;;
"menu_option_1") echo "1) Buscar Actualizaciones e Instalar/Actualizar Cursor" ;;
"menu_option_2") echo "2) Actualizar Solo el Acceso Directo del Escritorio" ;;
"menu_option_3") echo "3) Mostrar Información del Sistema" ;;
"menu_option_4") echo "4) Salir" ;;
"menu_select") echo "Seleccionar opción" ;;
"update_check") echo "Buscando actualizaciones..." ;;
"download_prompt") echo "¿Desea descargar la última versión disponible?" ;;
"install_success") echo "Instalación completada exitosamente" ;;
"network_error") echo "Error de conexión. Verifique su internet." ;;
"invalid_option") echo "Opción inválida. Por favor elija 1-4." ;;
"exiting") echo "Saliendo..." ;;
"version_current") echo "Su instalación está actualizada" ;;
"version_update") echo "Actualización disponible" ;;
*) echo "$fallback" ;;
esac
;;
"EN"|*)
case "$key" in
"menu_title") echo "=== Cursor Setup Menu ===" ;;
"menu_option_1") echo "1) Check for Updates & Install/Update Cursor" ;;
"menu_option_2") echo "2) Update Desktop Shortcut Only" ;;
"menu_option_3") echo "3) Show System Information" ;;
"menu_option_4") echo "4) Exit" ;;
"menu_select") echo "Select option" ;;
"update_check") echo "Checking for updates..." ;;
"download_prompt") echo "Do you want to download the latest version?" ;;
"install_success") echo "Installation completed successfully" ;;
"network_error") echo "Network error. Check your internet connection." ;;
"invalid_option") echo "Invalid option. Please choose 1-4." ;;
"exiting") echo "Exiting..." ;;
"version_current") echo "Your installation is up to date" ;;
"version_update") echo "Update available" ;;
*) echo "$fallback" ;;
esac
;;
esac
}
# -------------------------------------------------------------------
# Simple delay with message
# -------------------------------------------------------------------
show_message() {
local message="$1"
echo "$message"
}
# -------------------------------------------------------------------
# Remove older versions, keeping only the newest one.
# -------------------------------------------------------------------
remove_old_versions() {
local newest_file
# Note: APPIMAGE_PATTERN must be unquoted to allow shell glob expansion
newest_file=$(ls -1t $APPIMAGE_PATTERN 2>/dev/null | head -n 1 || true)
if [[ -n "$newest_file" ]]; then
local older_files
older_files=$(ls -1t $APPIMAGE_PATTERN 2>/dev/null | tail -n +2 || true)
if [[ -n "$older_files" ]]; then
logg info "Removing older versions in $DOWNLOAD_DIR..."
# Note: older_files contains newline-separated paths, need to handle carefully
echo "$older_files" | while IFS= read -r file; do
[[ -n "$file" ]] && rm -f "$file"
done
fi
fi
}
# -------------------------------------------------------------------
# Confirmation function (YES/NO) using read with timeout and validation.
# Returns 0 if answer is yes, 1 if no, 2 if timeout/invalid input.
# -------------------------------------------------------------------
confirm_action() {
local question="$1"
local timeout="${2:-$DEFAULT_CONFIRMATION_TIMEOUT}"
local default="${3:-N}" # Default answer (Y/N)
local attempts=0
local max_attempts=3
while [[ $attempts -lt $max_attempts ]]; do
if ! read -t "$timeout" -rp "$question [y/N]: " response; then
logg warn "Confirmation timeout after $timeout seconds"
return 2
fi
# Remove whitespace and convert to lowercase
response=$(echo "$response" | tr -d '[:space:]' | tr '[:upper:]' '[:lower:]')
case "$response" in
y|yes|s|si|yeah|yep|sure)
return 0
;;
n|no|nope|nah|"")
return 1
;;
*)
attempts=$((attempts + 1))
if [[ $attempts -lt $max_attempts ]]; then
logg warn "Invalid response. Please enter 'y' for yes or 'n' for no."
else
logg error "Too many invalid attempts. Assuming 'no'."
return 1
fi
;;
esac
done
return 1
}
# -------------------------------------------------------------------
# Detect system architecture (x86_64 or aarch64)
# -------------------------------------------------------------------
detect_architecture() {
local arch
arch=$(uname -m)
case "$arch" in
x86_64)
echo "x64"
;;
aarch64)
echo "arm64"
;;
*)
logg error "Unsupported architecture: $arch"
return 1
;;
esac
return 0
}
# -------------------------------------------------------------------
# Get latest stable version from cursor-ai-downloads repository
# -------------------------------------------------------------------
# This function:
# 1. Fetches version information from cursor-ai-downloads repository
# 2. Extracts the latest version number from the repository content
# 3. Returns only the version info - the actual download uses official URLs
#
# Note: We get version info from GitHub repo but download from official Cursor URLs
# -------------------------------------------------------------------
get_latest_stable_version() {
# Use configurable timeouts
local ping_timeout="${CURL_PING_TIMEOUT:-2}"
local curl_timeout="${CURL_TIMEOUT:-10}"
local max_retries="${CURL_MAX_RETRIES:-3}"
# Check internet connectivity with configurable timeout (optional check - don't fail if ping fails)
local connectivity_ok=false
if ping -c 1 -W $ping_timeout github.com >/dev/null 2>&1 || \
ping -c 1 -W $ping_timeout gitlab.com >/dev/null 2>&1 || \
ping -c 1 -W $ping_timeout 8.8.8.8 >/dev/null 2>&1; then
connectivity_ok=true
[[ "${DEBUG_MODE:-false}" == "true" ]] && logg debug "Internet connectivity confirmed"
else
[[ "${DEBUG_MODE:-false}" == "true" ]] && logg debug "Ping failed, but will try curl anyway"
fi
# Try to fetch repository content with retries and fallback URLs
local repo_content=""
local attempt=0
local successful_url=""
while [[ $attempt -lt $max_retries && -z "$repo_content" ]]; do
for url in "${CURSOR_REPO_URLS[@]}"; do
[[ "${DEBUG_MODE:-false}" == "true" ]] && logg debug "Attempt $((attempt + 1))/$max_retries: Trying URL: $url"
if repo_content=$(curl -s --max-time $curl_timeout \
-H "User-Agent: Mozilla/5.0 (X11; Linux x86_64)" \
-H "Accept: text/plain, */*" \
--retry 2 --retry-delay 1 \
"$url" 2>/dev/null); then
if [[ -n "$repo_content" && ${#repo_content} -gt 1000 ]]; then
successful_url="$url"
[[ "${DEBUG_MODE:-false}" == "true" ]] && logg debug "Successfully fetched ${#repo_content} bytes from $url"
break 2
else
[[ "${DEBUG_MODE:-false}" == "true" ]] && logg debug "Content too small or empty from $url (${#repo_content} bytes)"
fi
else
[[ "${DEBUG_MODE:-false}" == "true" ]] && logg debug "Failed to fetch from $url"
fi
done
attempt=$((attempt + 1))
if [[ $attempt -lt $max_retries ]]; then
[[ "${DEBUG_MODE:-false}" == "true" ]] && logg debug "Waiting 2 seconds before retry..."
sleep 2
fi
done
if [[ -z "$repo_content" ]]; then
[[ "${DEBUG_MODE:-false}" == "true" ]] && logg debug "Failed to fetch repository content after $max_retries attempts"
return 1
fi
# Extract the latest version from the main download link
local latest_version
latest_version=$(echo "$repo_content" | grep -oE "Cursor [0-9]+\.[0-9]+\.[0-9]+" | head -1 | sed 's/Cursor //')
if [[ -z "$latest_version" ]]; then
[[ "${DEBUG_MODE:-false}" == "true" ]] && logg debug "Failed to extract version from repository content"
[[ "${DEBUG_MODE:-false}" == "true" ]] && logg debug "First 500 chars of content: $(echo "$repo_content" | head -c 500)"
return 1
fi
# Validate version format
if ! [[ "$latest_version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
[[ "${DEBUG_MODE:-false}" == "true" ]] && logg debug "Invalid version format: $latest_version"
return 1
fi
[[ "${DEBUG_MODE:-false}" == "true" ]] && logg debug "Successfully extracted version: $latest_version from $successful_url"
printf "%s" "$latest_version"
return 0
}
# -------------------------------------------------------------------
# Extract the correct download base URL from the repository content
# -------------------------------------------------------------------
get_dynamic_base_url() {
# Use configurable timeouts
local ping_timeout="${CURL_PING_TIMEOUT:-2}"
local curl_timeout="${CURL_TIMEOUT:-10}"
local max_retries="${CURL_MAX_RETRIES:-3}"
# Check internet connectivity with configurable timeout (optional check - don't fail if ping fails)
local connectivity_ok=false
if ping -c 1 -W $ping_timeout github.com >/dev/null 2>&1 || \
ping -c 1 -W $ping_timeout gitlab.com >/dev/null 2>&1 || \
ping -c 1 -W $ping_timeout 8.8.8.8 >/dev/null 2>&1; then
connectivity_ok=true
[[ "${DEBUG_MODE:-false}" == "true" ]] && logg debug "Internet connectivity confirmed for base URL fetch"
else
[[ "${DEBUG_MODE:-false}" == "true" ]] && logg debug "Ping failed for base URL fetch, but will try curl anyway"
fi
# Try to fetch repository content with retries and fallback URLs
local repo_content=""
local attempt=0
local successful_url=""
while [[ $attempt -lt $max_retries && -z "$repo_content" ]]; do
for url in "${CURSOR_REPO_URLS[@]}"; do
[[ "${DEBUG_MODE:-false}" == "true" ]] && logg debug "Base URL fetch attempt $((attempt + 1))/$max_retries: Trying $url"
if repo_content=$(curl -s --max-time $curl_timeout \
-H "User-Agent: Mozilla/5.0 (X11; Linux x86_64)" \
-H "Accept: text/plain, */*" \
--retry 2 --retry-delay 1 \
"$url" 2>/dev/null); then
if [[ -n "$repo_content" && ${#repo_content} -gt 1000 ]]; then
successful_url="$url"
[[ "${DEBUG_MODE:-false}" == "true" ]] && logg debug "Successfully fetched ${#repo_content} bytes for base URL extraction"
break 2
else
[[ "${DEBUG_MODE:-false}" == "true" ]] && logg debug "Content too small or empty (${#repo_content} bytes)"
fi
else
[[ "${DEBUG_MODE:-false}" == "true" ]] && logg debug "Failed to fetch from $url for base URL"
fi
done
attempt=$((attempt + 1))
if [[ $attempt -lt $max_retries ]]; then
[[ "${DEBUG_MODE:-false}" == "true" ]] && logg debug "Waiting 2 seconds before retry for base URL..."
sleep 2
fi
done
if [[ -z "$repo_content" ]]; then
[[ "${DEBUG_MODE:-false}" == "true" ]] && logg debug "Failed to fetch repository content for base URL after $max_retries attempts"
return 1
fi
# Get the current version first to ensure we get the right hash
local current_version
current_version=$(echo "$repo_content" | grep -oE "Cursor [0-9]+\.[0-9]+\.[0-9]+" | head -1 | sed 's/Cursor //')
if [[ -z "$current_version" ]]; then
[[ "${DEBUG_MODE:-false}" == "true" ]] && logg debug "Failed to extract version for base URL extraction"
return 1
fi
[[ "${DEBUG_MODE:-false}" == "true" ]] && logg debug "Extracting base URL for version: $current_version"
# Look for the Linux x64 download link for this specific version
local latest_download_url
latest_download_url=$(echo "$repo_content" | grep -oE "https://downloads\.cursor\.com/production/[a-f0-9]+/linux/x64/Cursor-[0-9]+\.[0-9]+\.[0-9]+-x86_64\.AppImage" | head -1)
# If Linux URL not found or doesn't match current version, try to construct it from Windows hash
if [[ -z "$latest_download_url" ]] || ! echo "$latest_download_url" | grep -q "$current_version"; then
[[ "${DEBUG_MODE:-false}" == "true" ]] && logg debug "Linux URL not found or version mismatch, trying Windows hash"
# Get hash from Windows download for the current version
local windows_url
windows_url=$(echo "$repo_content" | grep -oE "https://downloads\.cursor\.com/production/[a-f0-9]+/win32/x64/.*CursorSetup.*-${current_version}\.exe" | head -1)
if [[ -n "$windows_url" ]]; then
local hash
hash=$(echo "$windows_url" | sed -n 's|.*production/\([a-f0-9]\+\)/.*|\1|p')
latest_download_url="https://downloads.cursor.com/production/${hash}/linux/x64/Cursor-${current_version}-x86_64.AppImage"
[[ "${DEBUG_MODE:-false}" == "true" ]] && logg debug "Constructed URL from Windows hash: '$latest_download_url'"
fi
fi
if [[ -z "$latest_download_url" ]]; then
return 1
fi
# Extract the base URL (up to production/hash/linux, without x64)
local base_url
base_url=$(echo "$latest_download_url" | sed 's|/linux/.*|/linux|')
[[ "${DEBUG_MODE:-false}" == "true" ]] && logg debug "Found/constructed download URL: '$latest_download_url'"
[[ "${DEBUG_MODE:-false}" == "true" ]] && logg debug "Extracted base URL: '$base_url'"
printf "%s" "$base_url"
return 0
}
# -------------------------------------------------------------------
# Download the latest stable AppImage from official Cursor servers
# -------------------------------------------------------------------
# This function:
# 1. Gets version info from cursor-ai-downloads repository (metadata only)
# 2. Downloads the actual AppImage from official Cursor servers
# 3. Validates the downloaded file
#
# Note: Only downloads from official URLs, repository is used for version detection
# -------------------------------------------------------------------
download_latest_stable() {
logg prompt "Checking latest stable version from cursor-ai-downloads repository..."
local arch
arch=$(detect_architecture)
if [[ $? -ne 0 ]]; then
return 1
fi
local latest_version
latest_version=$(get_latest_stable_version)
if [[ $? -ne 0 ]]; then
logg error "Could not fetch repository content"
return 1
fi
local filename="Cursor-$latest_version"
if [[ "$arch" == "x64" ]]; then
filename="${filename}-x86_64.AppImage"
else
filename="${filename}-aarch64.AppImage"
fi
# Get the dynamic base URL from repository
local base_url
base_url=$(get_dynamic_base_url)
if [[ $? -ne 0 || -z "$base_url" ]]; then
logg warn "Could not get dynamic URL, falling back to hardcoded URL"
base_url="$CURSOR_DOWNLOAD_BASE_URL"
fi
local url="$base_url/$arch/$filename"
logg info "Latest stable version: $latest_version"
logg info "Downloading file: $filename"
[[ "${DEBUG_MODE:-false}" == "true" ]] && logg debug "Using base URL: '$base_url'"
logg info "Download URL: $url"
pushd "$USER_DOWNLOADS_DIR" >/dev/null
if [[ -f "$filename" ]]; then
logg info "File $filename already exists. Removing old version..."
rm -f "$filename"
fi
# Download with progress and error handling
if ! curl -L -o "$filename" -H "User-Agent: Mozilla/5.0 (X11; Linux x86_64)" \
--progress-bar --retry 3 --retry-delay 2 "$url"; then
popd >/dev/null
logg error "Failed to download the stable file after 3 attempts"
return 1
fi
if [[ ! -f "$filename" ]]; then
popd >/dev/null
logg error "Failed to download the stable file"
return 1
fi
# Validate downloaded file
if ! validate_appimage "$filename"; then
popd >/dev/null
logg error "Downloaded file validation failed"
rm -f "$filename"
return 1
fi
popd >/dev/null
# Update global variable to point to the downloaded file
LOCAL_APPIMAGE_PATH="$USER_DOWNLOADS_DIR/$filename"
logg success "Downloaded and validated file: $LOCAL_APPIMAGE_PATH"
return 0
}
# -------------------------------------------------------------------
# Configuration variables - can be overridden by environment variables
# -------------------------------------------------------------------
readonly CURSOR_REPO_URL="${CURSOR_REPO_URL:-https://raw.githubusercontent.com/oslook/cursor-ai-downloads/main/README.md}"
readonly CURSOR_DOWNLOAD_BASE_URL="${CURSOR_DOWNLOAD_BASE_URL:-https://downloads.cursor.com/production/823f58d4f60b795a6aefb9955933f3a2f0331d7b/linux}"
# Fallback URLs for repository access
readonly CURSOR_REPO_URLS=(
"https://raw.githubusercontent.com/oslook/cursor-ai-downloads/main/README.md"
"https://cdn.jsdelivr.net/gh/oslook/cursor-ai-downloads@main/README.md"
"https://raw.githubusercontent.com/oslook/cursor-ai-downloads/master/README.md"
"https://cdn.jsdelivr.net/gh/oslook/cursor-ai-downloads@master/README.md"
)
# -------------------------------------------------------------------
# Common variables and constants
# -------------------------------------------------------------------
readonly DOWNLOAD_DIR="$REAL_HOME/.AppImage"
readonly ICON_DIR="$REAL_HOME/.local/share/icons"
readonly ICON_URL="https://mintlify.s3-us-west-1.amazonaws.com/cursor/images/logo/app-logo.svg"
readonly CLI_COMMAND_NAME="cursor"
readonly USER_DESKTOP_FILE="$USER_DESKTOP_DIR/cursor.desktop"
readonly SYSTEM_DESKTOP_FILE="$REAL_HOME/.local/share/applications/cursor.desktop"
readonly DESKTOP_NAME="Cursor"
readonly APPARMOR_PROFILE="/etc/apparmor.d/cursor-appimage"
readonly SCRIPT_ALIAS_NAME="cursor-setup-ubuntu"
readonly APPIMAGE_PATTERN="$DOWNLOAD_DIR/Cursor-[0-9]*.AppImage"
SCRIPT_PATH="$(readlink -f "${BASH_SOURCE[0]}")"
# Global variable for the AppImage path (will be set by download functions)
LOCAL_APPIMAGE_PATH=""
# -------------------------------------------------------------------
# Validate URL format and accessibility
# -------------------------------------------------------------------
validate_url() {
local url="$1"
# Basic URL format validation
if ! [[ "$url" =~ ^https?:// ]]; then
logg error "Invalid URL format: $url"
return 1
fi
# Check if URL is accessible (quick timeout)
if ! curl -I --max-time 5 --silent "$url" >/dev/null 2>&1; then
logg warn "URL is not accessible: $url"
return 1
fi
return 0
}
# -------------------------------------------------------------------
# Validate AppImage file integrity
# -------------------------------------------------------------------
validate_appimage() {
local file_path="$1"
# Check if file exists and has content
if [[ ! -s "$file_path" ]]; then
logg error "AppImage file is empty or doesn't exist: $file_path"
return 1
fi
# Check file size (AppImages are typically > 100MB)
local file_size
file_size=$(stat -f%z "$file_path" 2>/dev/null || stat -c%s "$file_path" 2>/dev/null)
if [[ $file_size -lt $MIN_APPIMAGE_SIZE ]]; then
logg error "AppImage file seems too small ($file_size bytes). Download may be corrupted"
return 1
fi
# Check if file is executable
if [[ ! -x "$file_path" ]]; then
logg warn "AppImage file is not executable. Setting executable permissions."
chmod +x "$file_path"
fi
# Basic file type check
if command -v file >/dev/null 2>&1; then
if ! file "$file_path" | grep -q "AppImage"; then
logg warn "File doesn't appear to be a valid AppImage format"
# Don't fail here as file command might not recognize newer AppImages
fi
fi
logg info "AppImage validation passed for: $file_path"
return 0
}
# -------------------------------------------------------------------
# Create directory with proper error handling
# -------------------------------------------------------------------
create_directory() {
local dir_path="$1"
local dir_name="${2:-directory}"
if [[ ! -d "$dir_path" ]]; then
logg debug "Creating $dir_name: $dir_path"
if ! mkdir -p "$dir_path" 2>/dev/null; then
logg error "Failed to create $dir_name: $dir_path"
return 1
fi
fi
return 0
}
# -------------------------------------------------------------------
# Clean up old backup files
# -------------------------------------------------------------------
cleanup_backups() {
local target_dir="$1"
local max_backups="${2:-5}"
if [[ ! -d "$target_dir" ]]; then
return 0
fi
local backup_count
backup_count=$(find "$target_dir" -name "*.backup.*" -type f | wc -l)
if [[ $backup_count -gt $max_backups ]]; then
logg info "Cleaning up old backup files (keeping $max_backups most recent)"
# Remove oldest backup files
find "$target_dir" -name "*.backup.*" -type f -printf '%T@ %p\n' | \
sort -n | head -n -$max_backups | cut -d' ' -f2- | \
xargs -r rm -f
logg success "Cleanup completed"
fi
}
# -------------------------------------------------------------------
# Function to extract version from the AppImage filename
# -------------------------------------------------------------------
extract_version() {
local filename="$1"
if [[ "$filename" =~ Cursor-([0-9]+\.[0-9]+\.[0-9]+) ]]; then
printf "%s" "${BASH_REMATCH[1]}"
return
fi
printf "unknown"
}
# -------------------------------------------------------------------
# Function to update the executable symlink in /usr/local/bin.
# It creates a wrapper script that launches the AppImage with "--no-sandbox".
# -------------------------------------------------------------------
update_executable_symlink() {
local target_appimage="$DOWNLOAD_DIR/$(basename "$LOCAL_APPIMAGE_PATH")"
local wrapper="$DOWNLOAD_DIR/wrapper-${CLI_COMMAND_NAME}.sh"
local link="/usr/local/bin/${CLI_COMMAND_NAME}"
# Security: Validate target exists and is executable
if [[ ! -f "$target_appimage" ]]; then
logg error "Target AppImage not found: $target_appimage"
return $EXIT_ERROR
fi
if [[ ! -x "$target_appimage" ]]; then
logg error "Target AppImage is not executable: $target_appimage"
return $EXIT_ERROR
fi
# Security: Validate target path doesn't contain dangerous characters
local basename_target="$(basename "$LOCAL_APPIMAGE_PATH")"
if [[ "$basename_target" =~ [^a-zA-Z0-9._-] ]]; then
logg error "Invalid characters in AppImage filename: $basename_target"
return $EXIT_ERROR
fi
logg info "Creating wrapper script: $wrapper"
# Fix: Hardcode the target path in the generated script instead of using variable expansion
cat > "$wrapper" <<EOF
#!/usr/bin/env bash
# Wrapper to launch the Cursor AppImage with --no-sandbox
# Generated on $(date) by cursor-setup-ubuntu.sh
readonly TARGET_APPIMAGE="$target_appimage"
if [[ ! -f "\$TARGET_APPIMAGE" ]]; then
echo "Error: AppImage not found: \$TARGET_APPIMAGE" >&2
exit 1
fi
if [[ ! -x "\$TARGET_APPIMAGE" ]]; then
echo "Error: AppImage is not executable: \$TARGET_APPIMAGE" >&2
exit 1
fi
echo "Launching Cursor AppImage: \$TARGET_APPIMAGE"
exec "\$TARGET_APPIMAGE" --no-sandbox "\$@"
EOF
chmod +x "$wrapper"
logg info "Updating executable symlink: $link -> $wrapper"
if sudo test -L "$link" || sudo test -f "$link"; then
sudo rm -f "$link"
fi
sudo ln -s "$wrapper" "$link"
logg success "Symlink updated: $link -> $wrapper"
}
# -------------------------------------------------------------------
# Function to update the desktop shortcut and icon
# -------------------------------------------------------------------
update_desktop_shortcut() {
logg info "Updating desktop shortcut and icon..."
if ! create_directory "$ICON_DIR" "icon directory"; then
return 1
fi
curl -L -o "$ICON_DIR/cursor.svg" "$ICON_URL"
cat > "$USER_DESKTOP_FILE" <<EOF
[Desktop Entry]
Name=$DESKTOP_NAME
Exec=$DOWNLOAD_DIR/$(basename "$LOCAL_APPIMAGE_PATH") --no-sandbox
Icon=$ICON_DIR/cursor.svg
Type=Application
Categories=Utility;
EOF
if ! create_directory "$(dirname "$SYSTEM_DESKTOP_FILE")" "system desktop directory"; then
return 1
fi
cp "$USER_DESKTOP_FILE" "$SYSTEM_DESKTOP_FILE"
logg success "Desktop shortcut updated at: $USER_DESKTOP_FILE and $SYSTEM_DESKTOP_FILE"
}
# -------------------------------------------------------------------
# Function to update the AppArmor profile.
# It writes an embedded profile to the specified file and reloads it.
# -------------------------------------------------------------------
update_apparmor_profile() {
logg info "Updating AppArmor profile..."
if ! sudo -v; then
logg error "Sudo privileges are required to update the AppArmor profile"
return 1
fi
local APPARMOR_PROFILE_CONTENT="
#include <tunables/global>
profile cursor-appimage flags=(attach_disconnected,mediate_deleted) {
/home/*/.AppImage/Cursor-*.AppImage ix,
/etc/{passwd,group,shadow} r,
/usr/bin/env rix,
/usr/bin/{bash,sh} rix,
}
"
echo "$APPARMOR_PROFILE_CONTENT" | sudo tee "$APPARMOR_PROFILE" >/dev/null
logg info "Profile copied to $APPARMOR_PROFILE"
sudo apparmor_parser -r "$APPARMOR_PROFILE"
logg success "AppArmor profile updated and reloaded."
}
# -------------------------------------------------------------------
# Function to install the AppImage:
# - Copy the file to DOWNLOAD_DIR
# - Set executable permissions
# - Update desktop shortcut and icon
# - Update AppArmor profile
# - Update executable symlink in /usr/local/bin
# -------------------------------------------------------------------
install_appimage() {
local file="$1"
local filename
filename=$(basename "$file")
local target_path="$DOWNLOAD_DIR/$filename"
logg info "Installing AppImage: $file"
if ! create_directory "$DOWNLOAD_DIR" "AppImage directory"; then
return 1
fi
# Clean up old backup files
cleanup_backups "$DOWNLOAD_DIR"
# Check if target file already exists and is busy
if [[ -f "$target_path" ]]; then
logg info "Target file exists, checking if it's in use..."
# Optimized process detection using the most efficient method available
local pids_using_file=""
local processes_info=""
local detection_method=""
# Method 1: Using lsof (most reliable and efficient)
if command -v lsof >/dev/null 2>&1; then
local lsof_output
lsof_output=$(lsof "$target_path" 2>/dev/null || true)
if [[ -n "$lsof_output" ]]; then
pids_using_file=$(echo "$lsof_output" | awk 'NR>1 {print $2}' | sort -u)
processes_info=$(echo "$lsof_output" | awk 'NR>1 {print $2, $1}' | sort -u)
detection_method="lsof"
logg debug "Processes using file (lsof): $processes_info"
fi
fi
# Method 2: Using fuser as fallback (only if lsof failed)
if [[ -z "$pids_using_file" ]] && command -v fuser >/dev/null 2>&1; then
local fuser_pids
fuser_pids=$(fuser "$target_path" 2>/dev/null | sed 's/.*://' | tr ',' '\n' | tr -d '[:space:]' || true)
if [[ -n "$fuser_pids" ]]; then
pids_using_file="$fuser_pids"
processes_info=$(fuser -v "$target_path" 2>/dev/null || true)
detection_method="fuser"
logg debug "Processes using file (fuser): $processes_info"
fi
fi
# Method 3: Enhanced cursor process check (only if necessary)
if [[ -n "$pids_using_file" ]]; then
local cursor_pids
cursor_pids=$(pgrep -f "cursor" 2>/dev/null || true)
if [[ -n "$cursor_pids" ]]; then
logg debug "Found running Cursor processes: $cursor_pids"
# More efficient check using associative array concept
for pid in $cursor_pids; do
if echo "$pids_using_file" | grep -q "^$pid$"; then
logg warn "Cursor process $pid is using the AppImage file"
fi
done
fi
fi
if [[ -n "$pids_using_file" ]]; then
logg warn "File is currently in use by processes:"
echo "$processes_info" | while read -r line; do
if [[ -n "$line" ]]; then
local pid proc_name
pid=$(echo "$line" | awk '{print $1}')
proc_name=$(echo "$line" | awk '{print $2}')
logg warn " PID $pid: $proc_name"
fi
done
# Offer different options for handling busy file
echo
logg prompt "Options:"
echo "1) Wait for processes to finish (recommended)"
echo "2) Terminate processes and continue"
echo "3) Skip file replacement (keep existing)"
echo "4) Cancel installation"
echo
local choice=""
local wait_attempts=0
local max_wait_attempts=$MAX_WAIT_ATTEMPTS
while [[ -z "$choice" ]] || ! [[ "$choice" =~ ^[1-4]$ ]]; do
read -t $MENU_CHOICE_TIMEOUT -rp "Choose option [1-4]: " choice
if [[ $? -ne 0 ]]; then
logg warn "Timeout waiting for choice. Cancelling installation."
return 1
fi
case "$choice" in
1)
logg info "Waiting for processes to finish..."
while [[ $wait_attempts -lt $max_wait_attempts ]] && [[ -n "$(lsof "$target_path" 2>/dev/null | awk 'NR>1 {print $2}' || true)" ]]; do
sleep $WAIT_INTERVAL
wait_attempts=$((wait_attempts + 1))
logg debug "Still waiting... ($((wait_attempts * WAIT_INTERVAL))s elapsed)"
done
if [[ $wait_attempts -ge $max_wait_attempts ]]; then
logg error "Timeout waiting for processes to finish"
return 1
fi
logg success "Processes finished, continuing with installation"
;;
2)
if confirm_action "This will terminate the listed processes. Continue?"; then
for pid in $pids_using_file; do
if kill -TERM "$pid" 2>/dev/null; then
logg info "Terminated process $pid"
sleep 2
else
logg warn "Failed to terminate process $pid"
fi
done
# Wait a bit more to ensure processes are fully terminated
sleep 3
else
logg info "Installation cancelled by user."
return 1
fi
;;
3)