#!/bin/bash

sudo apt-get update && sudo apt-get install -y git

cd  ~/

git clone git@github.com:paulfarrow/linux-config.git

if [ -d ~/linux-config ]; then
    cd linux-config
    ./install.sh
    ./nvim_install.sh
    echo "Installation complete!!"
else
    echo "Error cloning repo"
    echo "If there was a permissions error, you need to add the local public key to github: https://github.com/settings/keys"
    GetLikelySshKey
fi



GetLikelySshKey() {
    CheckKey
    echo "The most likely key is:"
    ssh_key=$(ls ~/.ssh/ | grep -E "^id_\S*\.pub")
    if [[ -z "$ssh_key" ]]; then
        ssh_key=$(ls ~/.ssh/ | grep -E "\S*\.pub" | head -1)
    fi
    if [[ -z "$ssh_key" ]]; then
        echo "No key found!"
    else
        echo $(cat ~/.ssh/$ssh_key)
    fi
}

CheckKey() {
    if [ ! -d ~/.ssh ]; then
        CreateKey
    fi
}

CreateKey() {
    echo "There isnt a ~/.ssh directory, so a ssh key needs to be generated."
    rand_id=$(shuf -i 10000-99999 -n 1)
    while true; do
        read -p "Do you wish to create one? (y/n) " yn
        case $yn in
            [Yy]* ) mkdir -p ~/.ssh; ssh-keygen -f ~/.ssh/id_ed${rand_id} -q -N ""; echo "Key generated as ~/.ssh/id_ed${rand_id}.pub" break;;
            [Nn]* ) exit;;
            * ) echo "Please answer yes or no.";;
        esac
    done
}
