#!/bin/bash
# Create a gist from the current directory
#
# Creates a gist on an OpenGist instance from the current directory.
# It will take care of initializing the git repo, committing all files, and
# pushing to the configured endpoint. On completion, it will update the remote
# URL to the created gist.
#
# The script requires that you create the file $HOME/.config/create-gist/url,
# and it should have the endpoint to an OpenGist creation URL (e.g.
# https://gist.example.org/init)

set -euo pipefail

if [[ ! -f $HOME/.config/create-gist/url ]]; then
    echo "In order to use this utility, you must define the file \$HOME/.config/create-gist/url" >2
    echo "and the contents of that file must be an endpoint to an OpenGist installation" >2
    echo "(e.g. https://gist.example.org/init)" >2
    exit 1
fi

gist_init_url=$(cat "$HOME/.config/create-gist/url" | tr -d '')
gist_dir="$PWD"

git init -b main
git add .
git commit -m 'Creating gist'
git remote add origin "$gist_init_url"

push_result=$(git push -u origin main 2>&1)
echo "$push_result"
remote_url=$(echo "$push_result" | grep -Po "git remote set-url origin https:\/\/\S+" | grep -Po "https:\/\/\S+")
if [[ "$remote_url" =~ ^https:// ]]; then
    git remote set-url origin "$remote_url"
    echo "Remote origin updated to ${remote_url}"
    echo "Visit the gist online: ${remote_url}"
else
    echo "Unable to determine gist URL; creation may have failed"
fi
