#!/bin/sh
# shellcheck disable=SC1091,SC1090

# Description:
#   Initialize ssh-agent and set up environment variables for use in the current shell.
#
# Usage:
#   `eval "$(ssh-init)"` to set up environment
#   variables for ssh agent in the current shell.
#   TIPS: `bass "$(ssh-init)"` case in fish

mkdir -p "$HOME/.local/state"
agent_file="$HOME/.local/state/ssh-agent"

if [ -z "$SSH_AUTH_SOCK" ]; then
    if [ -f "$agent_file" ] && [ -r "$agent_file" ]; then
        . "$agent_file" > /dev/null 2>&1
        # check if the socket is actually working
        if [ "$(ssh-add -l > /dev/null 2>&1; echo $?)" -eq 2 ]; then
            # if not, unset it to create a new one
            unset SSH_AUTH_SOCK
        fi
    fi

    if [ -z "$SSH_AUTH_SOCK" ]; then
        rm -f "$agent_file"
        eval "$(ssh-agent -s | tee "$agent_file")" > /dev/null 2>&1
    fi

    [ -f "$agent_file" ] && cat "$agent_file"
fi
