forked from alrra/dotfiles
-
Notifications
You must be signed in to change notification settings - Fork 0
/
set_github_ssh_key.sh
executable file
·127 lines (79 loc) · 2.68 KB
/
set_github_ssh_key.sh
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
#!/bin/bash
cd "$(dirname "${BASH_SOURCE[0]}")" \
&& . "utils.sh"
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
add_ssh_configs() {
printf "%s\n" \
"Host github.com" \
" IdentityFile $1" \
" LogLevel ERROR" >> ~/.ssh/config
print_result $? "Add SSH configs"
}
copy_public_ssh_key_to_clipboard () {
if cmd_exists "pbcopy"; then
pbcopy < "$1"
print_result $? "Copy public SSH key to clipboard"
elif cmd_exists "xclip"; then
xclip -selection clip < "$1"
print_result $? "Copy public SSH key to clipboard"
else
print_warning "Please copy the public SSH key ($1) to clipboard"
fi
}
generate_ssh_keys() {
ask "Please provide an email address: " && printf "\n"
ssh-keygen -t rsa -b 4096 -C "$(get_answer)" -f "$1"
print_result $? "Generate SSH keys"
}
open_github_ssh_page() {
declare -r GITHUB_SSH_URL="https://github.com/settings/ssh"
# The order of the following checks matters
# as on Ubuntu there is also a utility called `open`.
if cmd_exists "xdg-open"; then
xdg-open "$GITHUB_SSH_URL"
elif cmd_exists "open"; then
open "$GITHUB_SSH_URL"
else
print_warning "Please add the public SSH key to GitHub ($GITHUB_SSH_URL)"
fi
}
set_github_ssh_key() {
local sshKeyFileName="$HOME/.ssh/github"
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# If there is already a file with that
# name, generate another, unique, file name.
if [ -f "$sshKeyFileName" ]; then
sshKeyFileName="$(mktemp -u "$HOME/.ssh/github_XXXXX")"
fi
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
generate_ssh_keys "$sshKeyFileName"
add_ssh_configs "$sshKeyFileName"
copy_public_ssh_key_to_clipboard "${sshKeyFileName}.pub"
open_github_ssh_page
test_ssh_connection \
&& rm "${sshKeyFileName}.pub"
}
test_ssh_connection() {
while true; do
ssh -T [email protected] &> /dev/null
[ $? -eq 1 ] && break
sleep 5
done
}
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
main() {
print_in_purple "\n • Set up GitHub SSH keys\n\n"
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
if ! is_git_repository; then
print_error "Not a Git repository"
exit 1
fi
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ssh -T [email protected] &> /dev/null
if [ $? -ne 1 ]; then
set_github_ssh_key
fi
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
print_result $? "Set up GitHub SSH keys"
}
main