#!/bin/bash
source "$ROOT_PATH"/scripts/common.sh
set -eo pipefail

# Function to handle errors
handle_error() {
    echo_red_bg "Error: $1"
    exit 1
}

if [ ! -d ~/.ssh ]; then
    # If it doesn't exist, create it with the correct permissions
    mkdir -m 700 ~/.ssh || handle_error "failed to create ~/.ssh directory"
fi

if [ -n "$SSH_PRIVATE_KEY" ]; then
    echo_red "SSH_PRIVATE_KEY is set and not empty."
    echo "$SSH_PRIVATE_KEY" > ~/.ssh/id_rsa
    chmod 600 ~/.ssh/id_rsa || handle_error "failed to give permissions for private key file"
    eval `ssh-agent`
    ssh-add || handle_error "failed to enable ssh agent"
    echo "SSH_AUTH_SOCK=$(echo $SSH_AUTH_SOCK)" >> $GITHUB_ENV
    cat << EOF >> ~/.ssh/config
Host github.com
    StrictHostKeyChecking no
    UserKnownHostsFile=/dev/null
    ForwardAgent yes
EOF
    echo_green "SSH private key is set successfully"
else
    echo_red_bg "SSH_PRIVATE_KEY is either not set or empty."
fi

