Files
dots/.config/fish/functions/gitea_key.fish
2026-06-19 19:16:09 +00:00

76 lines
3.5 KiB
Fish

function gitea_key -d "Generate (or regenerate) an ed25519 SSH key for Gitea and configure ~/.ssh/config"
set -l key_path "$HOME/.ssh/id_ed25519_gitea"
set -l pub_path "$key_path.pub"
set -l config_path "$HOME/.ssh/config"
set -l host "gitssh.toomuchtaco.net"
# ── Step 1: Handle existing key ─────────────────────────────────────────
if test -f "$key_path"
echo "An SSH key already exists at $key_path"
read -p 'echo "Overwrite it? [y/N] "' -l confirm
if test "$confirm" != "y" -a "$confirm" != "Y"
echo "Aborted."
return 1
end
echo ""
end
# ── Step 2: Generate the key ────────────────────────────────────────────
# -t ed25519: modern, secure, fast elliptic-curve key
# -f: output file
# -N "": empty passphrase (prompts to set one if desired)
ssh-keygen -t ed25519 -f "$key_path" -N ""
echo ""
# ── Step 3: Update ~/.ssh/config ────────────────────────────────────────
# If the host block already exists, update the IdentityFile line in place.
# Otherwise, append a new block at the end of the file.
if grep -q "^Host $host\$" "$config_path" 2>/dev/null
# Host block exists — update the IdentityFile line.
# If an IdentityFile line already exists under this Host, replace it;
# otherwise add one after the HostName line.
if grep -A5 "^Host $host\$" "$config_path" | grep -q "IdentityFile"
sed -i "/^Host $host\$/,/^Host /s|IdentityFile .*|IdentityFile $key_path|" "$config_path"
echo "Updated IdentityFile for Host $host in $config_path"
else
sed -i "/^Host $host\$/,/^Host /s|HostName .*|&\n\tIdentityFile $key_path|" "$config_path"
echo "Added IdentityFile for Host $host in $config_path"
end
else
# No Host block yet — append one.
# printf interprets \t as a literal tab (unlike echo in Fish).
printf "\n# Gitea\nHost %s\n\tHostName %s\n\tUser git\n\tIdentityFile %s\n" \
"$host" "$host" "$key_path" >>"$config_path"
echo "Appended Host block for $host to $config_path"
end
# ── Step 4: Set correct permissions ────────────────────────────────────
chmod 600 "$key_path"
chmod 644 "$pub_path"
chmod 600 "$config_path"
echo ""
# ── Step 5: Print the public key ────────────────────────────────────────
echo "=============================="
echo " Public key (add to Gitea): "
echo "=============================="
echo ""
cat "$pub_path"
echo ""
echo "=============================="
echo "Key copied to clipboard if pbcopy/xclip is available."
if command -v pbcopy &>/dev/null
cat "$pub_path" | pbcopy
echo "(copied to clipboard via pbcopy)"
else if command -v xclip &>/dev/null
cat "$pub_path" | xclip -selection clipboard
echo "(copied to clipboard via xclip)"
else if command -v wl-copy &>/dev/null
cat "$pub_path" | wl-copy
echo "(copied to clipboard via wl-copy)"
end
echo "=============================="
end