-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgitssh-setup.sh
More file actions
2136 lines (1812 loc) · 68.6 KB
/
gitssh-setup.sh
File metadata and controls
2136 lines (1812 loc) · 68.6 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
#!/bin/sh
#================================================================#
# GitSSH SETUP MODULE
# Interactive SSH key setup for GitHub and GitLab
#================================================================#
# Configuration
SSH_CONFIG_FILE="$HOME/.ssh/config"
SSH_DIR="$HOME/.ssh"
#================================================================#
# MAIN SETUP COMMANDS
#================================================================#
# Setup GitHub SSH key
setup_github() {
if ! _check_setup_dependencies; then
return 1
fi
printf "\n"
_print_color blue "=========================================="
printf "\n"
_print_color blue " GitHub SSH Key Setup Wizard"
printf "\n"
_print_color blue "=========================================="
printf "\n\n"
_print_info "This wizard will help you set up SSH authentication for GitHub"
printf "We'll guide you through each step with explanations.\n\n"
# Step 1: Gather user information
if ! _gather_github_info; then
return 1
fi
# Step 2: Check existing SSH setup
if ! _check_existing_ssh_setup "github"; then
return 1
fi
# Step 3: Generate SSH key if needed
if [ "$GENERATE_NEW_KEY" = "true" ]; then
if ! _generate_ssh_key "github"; then
return 1
fi
fi
# Step 4: Configure SSH
if ! _setup_ssh_config "github"; then
return 1
fi
# Step 5: Add to SSH agent
if ! _add_to_ssh_agent "github"; then
return 1
fi
# Step 6: Display public key and guide user
if ! _guide_github_key_addition; then
return 1
fi
# Step 7: Test connection
if ! _test_github_connection; then
return 1
fi
# Step 8: Integration with GitSSH Session Manager
_integrate_with_session_manager "github"
_print_success "GitHub SSH setup completed successfully!"
printf "\n"
_print_info "You can now use the GitSSH Session Manager:"
printf " • Run 'gitssh session set' to configure your identity for repositories\n"
printf " • Use 'gitssh clone', 'gitssh push', etc. for enhanced Git operations\n"
printf " • Run 'gitssh remote convert' to convert HTTPS repositories to SSH\n"
printf "\n"
}
# Setup GitLab SSH key
setup_gitlab() {
if ! _check_setup_dependencies; then
return 1
fi
printf "\n"
_print_color blue "=========================================="
printf "\n"
_print_color blue " GitLab SSH Key Setup Wizard"
printf "\n"
_print_color blue "=========================================="
printf "\n\n"
_print_info "This wizard will help you set up SSH authentication for GitLab"
printf "We'll guide you through each step with explanations.\n\n"
# Step 1: Gather user information
if ! _gather_gitlab_info; then
return 1
fi
# Step 2: Check existing SSH setup
if ! _check_existing_ssh_setup "gitlab"; then
return 1
fi
# Step 3: Generate SSH key if needed
if [ "$GENERATE_NEW_KEY" = "true" ]; then
if ! _generate_ssh_key "gitlab"; then
return 1
fi
fi
# Step 4: Configure SSH
if ! _setup_ssh_config "gitlab"; then
return 1
fi
# Step 5: Add to SSH agent
if ! _add_to_ssh_agent "gitlab"; then
return 1
fi
# Step 6: Display public key and guide user
if ! _guide_gitlab_key_addition; then
return 1
fi
# Step 7: Test connection
if ! _test_gitlab_connection; then
return 1
fi
# Step 8: Integration with GitSSH Session Manager
_integrate_with_session_manager "gitlab"
_print_success "GitLab SSH setup completed successfully!"
printf "\n"
_print_info "You can now use the GitSSH Session Manager:"
printf " • Run 'gitssh session set' to configure your identity for repositories\n"
printf " • Use 'gitssh clone', 'gitssh push', etc. for enhanced Git operations\n"
printf " • Run 'gitssh remote convert' to convert HTTPS repositories to SSH\n"
printf "\n"
}
# Show SSH setup status
ssh_status() {
printf "\n"
_print_color blue "=========================================="
printf "\n"
_print_color blue " SSH Setup Status"
printf "\n"
_print_color blue "=========================================="
printf "\n\n"
# Check SSH directory
printf "SSH Directory Status:\n"
if [ -d "$SSH_DIR" ]; then
_print_success "SSH directory exists: $SSH_DIR"
printf " Permissions: %s\n" "$(ls -ld "$SSH_DIR" | awk '{print $1}')"
else
_print_warning "SSH directory not found: $SSH_DIR"
fi
printf "\n"
# Check SSH keys
printf "SSH Keys:\n"
key_count=0
for key_type in ed25519 rsa ecdsa dsa; do
if [ -f "$SSH_DIR/id_$key_type" ]; then
_print_success "Found $key_type key: id_$key_type"
key_count=$((key_count + 1))
fi
done
# Check for custom GitHub/GitLab keys
for service in github gitlab; do
for key_type in ed25519 rsa; do
if [ -f "$SSH_DIR/${service}_$key_type" ]; then
_print_success "Found $service $key_type key: ${service}_$key_type"
key_count=$((key_count + 1))
fi
done
done
if [ "$key_count" -eq 0 ]; then
_print_warning "No SSH keys found"
printf " Run 'gitssh setup github' or 'gitssh setup gitlab' to create keys\n"
fi
printf "\n"
# Check SSH agent
printf "SSH Agent Status:\n"
if _is_ssh_agent_running; then
_print_success "SSH Agent is running"
printf "Loaded keys:\n"
_get_loaded_ssh_keys | sed 's/^/ /'
else
_print_warning "SSH Agent not running"
printf " Start with: eval \$(ssh-agent -s)\n"
fi
printf "\n"
# Check SSH config
printf "SSH Configuration:\n"
if [ -f "$SSH_CONFIG_FILE" ]; then
_print_success "SSH config exists: $SSH_CONFIG_FILE"
# Check for GitHub/GitLab hosts
github_hosts=$(grep '^Host github-' "$SSH_CONFIG_FILE" 2>/dev/null | wc -l)
gitlab_hosts=$(grep '^Host gitlab-' "$SSH_CONFIG_FILE" 2>/dev/null | wc -l)
printf " GitHub hosts configured: %s\n" "$github_hosts"
printf " GitLab hosts configured: %s\n" "$gitlab_hosts"
else
_print_warning "SSH config not found"
printf " Will be created during setup\n"
fi
printf "\n"
# Test connections
printf "Connection Tests:\n"
_test_service_connections
printf "\n"
_print_color blue "=========================================="
printf "\n"
}
# Test SSH
ssh_test() {
if [ $# -eq 0 ]; then
printf "Usage: gitssh ssh test <hostname> [timeout]\n"
printf "Example: gitssh ssh test github-work 10\n"
return 1
fi
hostname="$1"
timeout="${2:-5}"
printf "Testing SSH connection to %s...\n" "$hostname"
if _test_ssh_connection "$hostname" "$timeout"; then
_print_success "SSH connection to $hostname successful!"
# Try to get more details
test_output=$(ssh -o ConnectTimeout="$timeout" -T "git@$hostname" 2>&1)
if printf "%s" "$test_output" | grep -q "successfully authenticated\|Welcome to GitLab"; then
printf "Authentication details:\n"
printf "%s\n" "$test_output" | head -3
fi
else
_print_error "SSH connection to $hostname failed"
printf "Troubleshooting:\n"
printf " 1. Check if SSH host exists: grep 'Host %s' ~/.ssh/config\n" "$hostname"
printf " 2. Test SSH agent: ssh-add -l\n"
printf " 3. Run diagnostics: gitssh ssh doctor\n"
return 1
fi
}
#================================================================#
# INFORMATION GATHERING
#================================================================#
# Gather GitHub user information
_gather_github_info() {
printf "Step 1: GitHub Account Information\n"
printf "===================================\n"
printf "GitHub username: "
read -r GITHUB_USERNAME
if _is_empty "$GITHUB_USERNAME"; then
_print_error "GitHub username cannot be empty"
return 1
fi
if ! _validate_username "$GITHUB_USERNAME"; then
_print_error "Invalid GitHub username format"
return 1
fi
printf "Email address (for Git commits): "
read -r USER_EMAIL
if _is_empty "$USER_EMAIL"; then
_print_error "Email address cannot be empty"
return 1
fi
if ! _validate_email "$USER_EMAIL"; then
_print_error "Invalid email format"
return 1
fi
printf "Display name [%s]: " "$GITHUB_USERNAME"
read -r USER_NAME
USER_NAME=${USER_NAME:-$GITHUB_USERNAME}
USER_NAME=$(_trim "$USER_NAME")
# Set SSH host name
SSH_HOST="github-$GITHUB_USERNAME"
KEY_COMMENT="$USER_EMAIL"
printf "\n"
_print_success "Account information collected:"
printf " Username: %s\n" "$GITHUB_USERNAME"
printf " Name: %s\n" "$USER_NAME"
printf " Email: %s\n" "$USER_EMAIL"
printf " SSH Host: %s\n" "$SSH_HOST"
printf "\n"
return 0
}
# Gather GitLab user information
_gather_gitlab_info() {
printf "Step 1: GitLab Account Information\n"
printf "===================================\n"
printf "GitLab instance URL [gitlab.com]: "
read -r GITLAB_URL
GITLAB_URL=${GITLAB_URL:-gitlab.com}
GITLAB_URL=$(_trim "$GITLAB_URL")
# Remove protocol if provided
GITLAB_URL=$(printf "%s" "$GITLAB_URL" | sed 's|^https\?://||')
printf "GitLab username: "
read -r GITLAB_USERNAME
if _is_empty "$GITLAB_USERNAME"; then
_print_error "GitLab username cannot be empty"
return 1
fi
if ! _validate_username "$GITLAB_USERNAME"; then
_print_error "Invalid GitLab username format"
return 1
fi
printf "Email address (for Git commits): "
read -r USER_EMAIL
if _is_empty "$USER_EMAIL"; then
_print_error "Email address cannot be empty"
return 1
fi
if ! _validate_email "$USER_EMAIL"; then
_print_error "Invalid email format"
return 1
fi
printf "Display name [%s]: " "$GITLAB_USERNAME"
read -r USER_NAME
USER_NAME=${USER_NAME:-$GITLAB_USERNAME}
USER_NAME=$(_trim "$USER_NAME")
# Set SSH host name
if [ "$GITLAB_URL" = "gitlab.com" ]; then
SSH_HOST="gitlab-$GITLAB_USERNAME"
else
# For custom GitLab instances, include domain
sanitized_domain=$(printf "%s" "$GITLAB_URL" | sed 's/[^a-zA-Z0-9]/-/g')
SSH_HOST="gitlab-$sanitized_domain-$GITLAB_USERNAME"
fi
KEY_COMMENT="$USER_EMAIL"
printf "\n"
_print_success "Account information collected:"
printf " GitLab URL: %s\n" "$GITLAB_URL"
printf " Username: %s\n" "$GITLAB_USERNAME"
printf " Name: %s\n" "$USER_NAME"
printf " Email: %s\n" "$USER_EMAIL"
printf " SSH Host: %s\n" "$SSH_HOST"
printf "\n"
return 0
}
#================================================================#
# SSH KEY MANAGEMENT
#================================================================#
# Check existing SSH setup
_check_existing_ssh_setup() {
service="$1" # github or gitlab
printf "Step 2: Checking Existing SSH Setup\n"
printf "====================================\n"
# Check SSH directory
if [ ! -d "$SSH_DIR" ]; then
printf "Creating SSH directory...\n"
mkdir -p "$SSH_DIR"
chmod 700 "$SSH_DIR"
_print_success "Created $SSH_DIR with proper permissions"
else
_print_success "SSH directory exists: $SSH_DIR"
fi
# Check for existing keys
existing_keys=""
key_files=""
# Check for service-specific keys first
for key_type in ed25519 rsa; do
key_name="${service}_${key_type}"
if [ -f "$SSH_DIR/$key_name" ] && [ -f "$SSH_DIR/$key_name.pub" ]; then
existing_keys="$existing_keys $key_name"
key_files="$key_files $SSH_DIR/$key_name"
fi
done
# Check for default keys
for key_type in ed25519 rsa ecdsa dsa; do
key_name="id_$key_type"
if [ -f "$SSH_DIR/$key_name" ] && [ -f "$SSH_DIR/$key_name.pub" ]; then
existing_keys="$existing_keys $key_name"
key_files="$key_files $SSH_DIR/$key_name"
fi
done
if [ -n "$existing_keys" ]; then
_print_info "Found existing SSH keys:"
for key in $existing_keys; do
printf " • %s\n" "$key"
done
printf "\n"
printf "Options:\n"
printf " 1. Use existing key\n"
printf " 2. Generate new key\n"
printf " 3. Exit setup\n"
printf "\n"
while true; do
printf "Choose option (1-3): "
read -r choice
case "$choice" in
1)
GENERATE_NEW_KEY="false"
if ! _select_existing_key; then
return 1
fi
break
;;
2)
GENERATE_NEW_KEY="true"
_generate_key_name "$service"
break
;;
3)
printf "Setup cancelled\n"
return 1
;;
*)
_print_warning "Invalid choice. Please enter 1, 2, or 3."
;;
esac
done
else
_print_info "No existing SSH keys found"
GENERATE_NEW_KEY="true"
_generate_key_name "$service"
fi
printf "\n"
return 0
}
# Select existing SSH key
_select_existing_key() {
printf "\nSelect SSH key to use:\n"
i=1
key_list=""
for key_type in ed25519 rsa ecdsa dsa; do
for prefix in "${service}_" "id_"; do
key_name="${prefix}${key_type}"
if [ -f "$SSH_DIR/$key_name" ] && [ -f "$SSH_DIR/$key_name.pub" ]; then
printf " %d. %s\n" "$i" "$key_name"
key_list="$key_list $key_name"
i=$((i + 1))
fi
done
done
if [ "$i" -eq 1 ]; then
_print_error "No valid key pairs found"
return 1
fi
while true; do
printf "\nSelect key (1-%d): " "$((i-1))"
read -r choice
if [ "$choice" -ge 1 ] && [ "$choice" -le "$((i-1))" ] 2>/dev/null; then
SELECTED_KEY=$(printf "%s" "$key_list" | awk "{print \$$choice}")
KEY_PATH="$SSH_DIR/$SELECTED_KEY"
_print_success "Selected: $SELECTED_KEY"
break
else
_print_warning "Invalid choice"
fi
done
return 0
}
# Generate key name for new key
_generate_key_name() {
service="$1"
# Use ed25519 as default for new keys (best practice)
case "$service" in
github)
KEY_NAME="github_${GITHUB_USERNAME}_id_ed25519"
;;
gitlab)
if [ "$GITLAB_URL" = "gitlab.com" ]; then
KEY_NAME="gitlab_${GITLAB_USERNAME}_id_ed25519"
else
sanitized_domain=$(printf "%s" "$GITLAB_URL" | sed 's/[^a-zA-Z0-9]/-/g')
KEY_NAME="gitlab-${sanitized_domain}_id_ed25519"
fi
;;
esac
KEY_PATH="$SSH_DIR/$KEY_NAME"
_print_info "Will generate new key: $KEY_NAME"
}
# Generate SSH key with user guidance
_generate_ssh_key() {
service="$1"
printf "Step 3: Generating SSH Key\n"
printf "==========================\n"
_print_info "About SSH Keys:"
printf "SSH keys provide secure, passwordless authentication to Git services.\n"
printf "We'll use Ed25519 encryption (recommended).\n\n"
# Check if key already exists
if [ -f "$KEY_PATH" ]; then
_print_warning "Key file already exists: $KEY_PATH"
printf "Overwrite existing key? (y/N): "
read -r overwrite
case "$overwrite" in
[Yy]*) ;;
*)
_print_info "Using existing key"
return 0
;;
esac
fi
printf "Generating SSH key...\n"
printf "Key type: Ed25519 (recommended)\n"
printf "Key file: %s\n" "$KEY_PATH"
printf "Comment: %s\n\n" "$KEY_COMMENT"
_print_info "About Passphrases:"
printf "A passphrase adds extra security to your SSH key.\n"
printf "Recommended: Use a strong passphrase\n"
printf "Note: You can use ssh-agent to avoid entering it repeatedly\n\n"
# Generate the key
if ssh-keygen -t ed25519 -f "$KEY_PATH" -C "$KEY_COMMENT"; then
_print_success "SSH key generated successfully!"
# Set proper permissions
chmod 600 "$KEY_PATH"
chmod 644 "$KEY_PATH.pub"
printf "\nKey details:\n"
printf " Private key: %s (keep this secret!)\n" "$KEY_PATH"
printf " Public key: %s (this will be added to $service)\n" "$KEY_PATH.pub"
printf " Fingerprint: "gitssh ssh
ssh-keygen -lf "$KEY_PATH.pub" 2>/dev/null | awk '{print $2}'
else
_print_error "Failed to generate SSH key"
return 1
fi
printf "\n"
return 0
}
# Setup SSH configuration
_setup_ssh_config() {
service="$1"
printf "Step 4: Configuring SSH\n"
printf "=======================\n"
_print_info "About SSH Config:"
printf "The SSH config file (~/.ssh/config) tells SSH how to connect to different hosts.\n"
printf "This allows you to use custom hostnames like 'github-username'.\n\n"
# Determine hostname and host entry
case "$service" in
github)
REAL_HOSTNAME="github.com"
HOST_ENTRY="Host $SSH_HOST
HostName github.com
User git
IdentityFile $KEY_PATH
IdentitiesOnly yes"
;;
gitlab)
REAL_HOSTNAME="$GITLAB_URL"
HOST_ENTRY="Host $SSH_HOST
HostName $GITLAB_URL
User git
IdentityFile $KEY_PATH
IdentitiesOnly yes"
;;
esac
# Create SSH config if it doesn't exist
if [ ! -f "$SSH_CONFIG_FILE" ]; then
printf "Creating SSH config file...\n"
touch "$SSH_CONFIG_FILE"
chmod 600 "$SSH_CONFIG_FILE"
_print_success "Created $SSH_CONFIG_FILE"
fi
# Check if host entry already exists
if grep -q "^Host $SSH_HOST$" "$SSH_CONFIG_FILE"; then
_print_warning "SSH host '$SSH_HOST' already exists in config"
printf "Update the existing entry? (Y/n): "
read -r update_config
case "$update_config" in
[Nn]*)
_print_info "Keeping existing SSH config"
return 0
;;
esac
# Remove existing entry
_remove_ssh_host_entry "$SSH_HOST"
fi
# Add new host entry
printf "Adding SSH host configuration...\n"
printf "\n# %s SSH configuration\n%s\n\n" "$service" "$HOST_ENTRY" >> "$SSH_CONFIG_FILE"
_print_success "Added SSH configuration for $SSH_HOST"
printf " You can now use: git@%s:username/repository.git\n" "$SSH_HOST"
printf "\n"
return 0
}
# Add key to SSH agent
_add_to_ssh_agent() {
service="$1"
printf "Step 5: Adding Key to SSH Agent\n"
printf "================================\n"
_print_info "About SSH Agent:"
printf "SSH Agent manages your SSH keys and handles authentication.\n"
printf "This allows you to enter your passphrase once per session.\n\n"
# Check if SSH agent is running
if ! _is_ssh_agent_running; then
printf "Starting SSH agent...\n"
eval "$(ssh-agent -s)" >/dev/null
if _is_ssh_agent_running; then
_print_success "SSH agent started"
else
_print_error "Failed to start SSH agent"
return 1
fi
else
_print_success "SSH agent is already running"
fi
# Add key to agent
printf "Adding SSH key to agent...\n"
if ssh-add "$KEY_PATH"; then
_print_success "SSH key added to agent successfully!"
# Show loaded keys
printf "\nCurrently loaded keys:\n"
_get_loaded_ssh_keys | sed 's/^/ /'
else
_print_error "Failed to add SSH key to agent"
return 1
fi
printf "\n"
return 0
}
#================================================================#
# SERVICE-SPECIFIC GUIDES
#================================================================#
# Guide user through GitHub key addition
_guide_github_key_addition() {
printf "Step 6: Adding Key to GitHub\n"
printf "============================\n"
_print_info "Now you need to add your public key to GitHub:"
printf "\n"
# Display the public key
printf "Your public key (copy this entire text):\n"
printf "%s\n" "$(cat "$KEY_PATH.pub")"
printf "%s\n" "$(printf '=%.0s' {1..60})"
printf "\n"
_print_info "GitHub Setup Steps:"
printf "1. Go to https://github.com/settings/keys\n"
printf "2. Click 'New SSH key'\n"
printf "3. Give it a title (e.g., 'My Laptop - %s')\n" "$(date '+%Y-%m-%d')"
printf "4. Paste the public key above into the 'Key' field\n"
printf "5. Click 'Add SSH key'\n\n"
# Auto-copy to clipboard if possible
if command -v xclip >/dev/null 2>&1; then
cat "$KEY_PATH.pub" | xclip -selection clipboard
_print_success "Public key copied to clipboard!"
elif command -v pbcopy >/dev/null 2>&1; then
cat "$KEY_PATH.pub" | pbcopy
_print_success "Public key copied to clipboard!"
elif command -v wl-copy >/dev/null 2>&1; then
cat "$KEY_PATH.pub" | wl-copy
_print_success "Public key copied to clipboard!"
else
_print_info "Tip: Select and copy the public key above"
fi
printf "Press Enter after adding the key to GitHub..."
read -r _
return 0
}
# Guide user through GitLab key addition
_guide_gitlab_key_addition() {
printf "Step 6: Adding Key to GitLab\n"
printf "============================\n"
_print_info "Now you need to add your public key to GitLab:"
printf "\n"
# Display the public key
printf "Your public key (copy this entire text):\n"
printf "%s\n" "$(cat "$KEY_PATH.pub")"
printf "%s\n" "$(printf '=%.0s' {1..60})"
printf "\n"
_print_info "GitLab Setup Steps:"
if [ "$GITLAB_URL" = "gitlab.com" ]; then
printf "1. Go to https://gitlab.com/-/user_settings/ssh_keys\n"
else
printf "1. Go to https://%s/-/user_settings/ssh_keys\n" "$GITLAB_URL"
fi
printf "2. Paste the public key above into the 'Key' field\n"
printf "3. Give it a title (e.g., 'My Laptop - %s')\n" "$(date '+%Y-%m-%d')"
printf "4. Set an expiration date (optional but recommended)\n"
printf "5. Click 'Add key'\n\n"
# Auto-copy to clipboard if possible
if command -v xclip >/dev/null 2>&1; then
cat "$KEY_PATH.pub" | xclip -selection clipboard
_print_success "Public key copied to clipboard!"
elif command -v pbcopy >/dev/null 2>&1; then
cat "$KEY_PATH.pub" | pbcopy
_print_success "Public key copied to clipboard!"
elif command -v wl-copy >/dev/null 2>&1; then
cat "$KEY_PATH.pub" | wl-copy
_print_success "Public key copied to clipboard!"
else
_print_info "Tip: Select and copy the public key above"
fi
printf "Press Enter after adding the key to GitLab..."
read -r _
return 0
}
#================================================================#
# CONNECTION TESTING
#================================================================#
# Test GitHub connection
_test_github_connection() {
printf "Step 7: Testing GitHub Connection\n"
printf "==================================\n"
_print_info "Testing SSH connection to GitHub..."
printf "This verifies that your key was added correctly.\n\n"
printf "Testing connection to %s...\n" "$SSH_HOST"
# Test with timeout and capture output
test_output=$(ssh -o ConnectTimeout=10 -T "git@$SSH_HOST" 2>&1)
test_result=$?
if printf "%s" "$test_output" | grep -q "successfully authenticated"; then
_print_success "SSH connection successful!"
# Extract username from GitHub response
github_user=$(printf "%s" "$test_output" | sed -n 's/.*Hi \([^!]*\)!.*/\1/p')
if [ -n "$github_user" ]; then
printf "Authenticated as GitHub user: %s\n" "$github_user"
if [ "$github_user" != "$GITHUB_USERNAME" ]; then
_print_warning "Username mismatch!"
printf " Expected: %s\n" "$GITHUB_USERNAME"
printf " Actual: %s\n" "$github_user"
printf "This might indicate a key conflict or wrong account.\n"
fi
fi
else
_print_error "SSH connection failed"
printf "Error output:\n%s\n\n" "$test_output"
_print_info "Troubleshooting tips:"
printf "1. Make sure you added the public key to the correct GitHub account\n"
printf "2. Check that the key was pasted completely without extra spaces\n"
printf "3. Verify your SSH agent is running: ssh-add -l\n"
printf "4. Try adding the key to SSH agent again: ssh-add %s\n" "$KEY_PATH"
printf "\nWould you like to try again? (y/N): "
read -r retry
case "$retry" in
[Yy]*) return _test_github_connection ;;
*) return 1 ;;
esac
fi
printf "\n"
return 0
}
# Test GitLab connection
_test_gitlab_connection() {
printf "Step 7: Testing GitLab Connection\n"
printf "==================================\n"
_print_info "Testing SSH connection to GitLab..."
printf "This verifies that your key was added correctly.\n\n"
printf "Testing connection to %s...\n" "$SSH_HOST"
# Test with timeout and capture output
test_output=$(ssh -o ConnectTimeout=10 -T "git@$SSH_HOST" 2>&1)
test_result=$?
if printf "%s" "$test_output" | grep -q "Welcome to GitLab"; then
_print_success "SSH connection successful!"
# Extract username from GitLab response if available
gitlab_user=$(printf "%s" "$test_output" | sed -n 's/.*Welcome to GitLab, @\([^!]*\)!.*/\1/p')
if [ -n "$gitlab_user" ]; then
printf "Authenticated as GitLab user: %s\n" "$gitlab_user"
if [ "$gitlab_user" != "$GITLAB_USERNAME" ]; then
_print_warning "Username mismatch!"
printf " Expected: %s\n" "$GITLAB_USERNAME"
printf " Actual: %s\n" "$gitlab_user"
printf "This might indicate a key conflict or wrong account.\n"
fi
fi
else
_print_error "SSH connection failed"
printf "Error output:\n%s\n\n" "$test_output"
_print_info "Troubleshooting tips:"
printf "1. Make sure you added the public key to the correct GitLab account\n"
printf "2. Check that the key was pasted completely without extra spaces\n"
printf "3. Verify your SSH agent is running: ssh-add -l\n"
printf "4. Try adding the key to SSH agent again: ssh-add %s\n" "$KEY_PATH"
printf "\nWould you like to try again? (y/N): "
read -r retry
case "$retry" in
[Yy]*) return _test_gitlab_connection ;;
*) return 1 ;;
esac
fi
printf "\n"
return 0
}
#================================================================#
# INTEGRATION FUNCTIONS
#================================================================#
# Integrate with GitSSH Session Manager
_integrate_with_session_manager() {
service="$1"
printf "Step 8: Integration with GitSSH Session Manager\n"
printf "================================================\n"
_print_info "About GitSSH Session Manager:"
printf "This tool helps you manage multiple Git identities and SSH keys.\n"
printf "It automatically configures the right user for each repository.\n\n"
# Check if GitSSH Session Manager is available
if ! _check_dependencies 2>/dev/null; then
_print_warning "GitSSH Session Manager not fully configured"
printf "Run 'gitssh init' to complete the setup\n\n"
return 0
fi
# Add user to session manager if not exists
case "$service" in
github)
username="$GITHUB_USERNAME"
;;
gitlab)
username="$GITLAB_USERNAME"
;;
esac
if ! _user_exists "$username" 2>/dev/null; then
printf "Adding user to GitSSH Session Manager...\n"
# Add user to config
if _add_user_to_config "$username" "$USER_NAME" "$USER_EMAIL" "$SSH_HOST"; then
_print_success "Added '$username' to session manager"
else
_print_warning "Failed to add user to session manager"
printf "You can add manually later with 'gitssh user add'\n"
fi
else
_print_success "User '$username' already exists in session manager"
fi
printf "\n"
return 0
}
#================================================================#
# UTILITY FUNCTIONS
#================================================================#
# Check setup dependencies
_check_setup_dependencies() {
missing_deps=""
# Check for required commands
for cmd in ssh-keygen ssh-add ssh git; do
if ! command -v "$cmd" >/dev/null 2>&1; then
missing_deps="$missing_deps $cmd"
fi
done
if [ -n "$missing_deps" ]; then
_print_error "Missing required dependencies:$missing_deps"
printf "Please install them first:\n"
os=$(_detect_os)
case "$os" in
linux)
printf " Ubuntu/Debian: sudo apt install openssh-client git\n"
printf " RHEL/CentOS: sudo yum install openssh-clients git\n"
printf " Arch: sudo pacman -S openssh git\n"
;;
macos)
printf " macOS: git and ssh should be pre-installed\n"
printf " If missing: xcode-select --install\n"
;;
esac
return 1
fi
return 0
}
# Remove existing SSH host entry
_remove_ssh_host_entry() {
host_name="$1"
temp_file=$(_create_temp_file)
# Remove the host block (Host line and all following indented lines)
awk -v host="$host_name" '
BEGIN { skip = 0 }
/^Host / {
if ($2 == host) {
skip = 1
} else {
skip = 0
}
}
/^[[:space:]]/ && skip { next }
/^[^[:space:]#]/ && !/^Host / { skip = 0 }
!skip { print }
' "$SSH_CONFIG_FILE" > "$temp_file"
_safe_file_replace "$temp_file" "$SSH_CONFIG_FILE"
}