#!/usr/bin/env fish

function usage
    echo "Usage: gist-pull <gist-url> [destination]"
    echo
    echo "Example:"
    echo "  gist-pull https://gist.example.com/william/my-gist ./config"
end

if test (count $argv) -lt 1
    usage
    exit 1
end

set -l gist_url $argv[1]
set -l destination "."

if test (count $argv) -ge 2
    set destination $argv[2]
end

# Remove query strings, fragments, trailing slash and optional .git suffix
set gist_url (string replace -r '[?#].*$' '' -- $gist_url)
set gist_url (string replace -r '/+$' '' -- $gist_url)
set gist_url (string replace -r '\.git$' '' -- $gist_url)

if not string match -rq '^https?://' -- $gist_url
    echo "Error: expected an HTTP or HTTPS OpenGist URL" >&2
    exit 1
end

set -l archive_url "$gist_url/archive/HEAD"
set -l archive (mktemp --suffix=.zip)

if test $status -ne 0
    echo "Error: could not create temporary file" >&2
    exit 1
end

function cleanup --on-event fish_exit
    rm -f $archive
end

echo "Fetching $gist_url"

if not curl --fail --location --silent --show-error \
    "$archive_url" \
    --output "$archive"
    echo "Error: failed to download gist" >&2
    exit 1
end

mkdir -p "$destination"

if command -q bsdtar
    if not bsdtar -xf "$archive" -C "$destination"
        echo "Error: failed to extract gist" >&2
        exit 1
    end
else if command -q unzip
    if not unzip -oq "$archive" -d "$destination"
        echo "Error: failed to extract gist" >&2
        exit 1
    end
else
    echo "Error: bsdtar or unzip is required" >&2
    exit 1
end

echo "Updated: $destination"