-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbootstrap-github-access
More file actions
executable file
·82 lines (71 loc) · 2.47 KB
/
Copy pathbootstrap-github-access
File metadata and controls
executable file
·82 lines (71 loc) · 2.47 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
#!/bin/bash
# bootstrap-github-access.sh
# Uploads remote system's SSH key to GitHub using GITHUB_TOKEN
# Load token from file if not in environment
if [[ -z "${GITHUB_TOKEN:-}" ]] && [[ -f ~/.config/github/mygithubtoken ]]; then
export GITHUB_TOKEN
GITHUB_TOKEN="$(cat ~/.config/github/mygithubtoken)"
fi
[[ -n "${GITHUB_TOKEN:-}" ]] && echo "✅ GITHUB_TOKEN is set" \
|| echo "❌ GITHUB_TOKEN is missing"
API="https://api.github.com/user/keys"
TITLE="$(hostname)-$(date +%Y%m%d)"
KEYFILE=""
if [[ -z "${GITHUB_TOKEN:-}" ]]; then
echo "❌ GITHUB_TOKEN not set. Aborting."
exit 1
fi
# --- Detect or generate SSH key ---
if [[ -f ~/.ssh/id_ed25519.pub ]]; then
KEYFILE=~/.ssh/id_ed25519.pub
elif [[ -f ~/.ssh/id_rsa.pub ]]; then
KEYFILE=~/.ssh/id_rsa.pub
else
echo "⚠️ No SSH public key found. Generating one..."
mkdir -p ~/.ssh
chmod 700 ~/.ssh
ssh-keygen -t ed25519 -f ~/.ssh/id_ed25519 -N "" -C "$(whoami)@$(hostname)"
KEYFILE=~/.ssh/id_ed25519.pub
fi
PUBKEY=$(<"$KEYFILE")
LOCAL_FP=$(ssh-keygen -lf "$KEYFILE" | awk '{print $2}')
EXISTING=$(curl -s -H "Authorization: token $GITHUB_TOKEN" "$API")
key_exists=false
if command -v jq >/dev/null 2>&1; then
if echo "$EXISTING" | jq -r '.[].key' 2>/dev/null \
| ssh-keygen -lf /dev/stdin 2>/dev/null \
| awk '{print $2}' | grep -q "$LOCAL_FP"; then
key_exists=true
fi
else
# Fallback: simple string match when jq is not available
local_key_data=$(awk '{print $2}' < "$KEYFILE")
if echo "$EXISTING" | grep -qF "$local_key_data"; then
key_exists=true
fi
fi
if $key_exists; then
echo "✅ Key already exists on GitHub (fingerprint $LOCAL_FP)."
else
echo "⬆️ Uploading SSH key to GitHub..."
RESP=$(curl -s -o /tmp/resp.json -w "%{http_code}" \
-H "Authorization: token $GITHUB_TOKEN" \
-H "Accept: application/vnd.github+json" \
-d "{\"title\":\"${TITLE}\",\"key\":\"${PUBKEY}\"}" \
"$API")
if [[ "$RESP" == "201" ]]; then
echo "✅ Key uploaded successfully."
else
echo "❌ Upload failed (HTTP $RESP). See /tmp/resp.json."
cat /tmp/resp.json
exit 1
fi
fi
# Only set up SSH URL rewriting and host key if the SSH key upload succeeded
if $key_exists || [[ "${RESP:-}" == "201" ]]; then
git config --global url."git@github.com:".insteadOf "https://github.com/"
ssh -o StrictHostKeyChecking=accept-new -T git@github.com || true
else
echo "⚠️ SSH key not on GitHub — will use HTTPS with token for git access."
fi
unset GITHUB_TOKEN