#!/bin/bash

# SPDX-License-Identifier: GPL-2.0

# Downloads and reviews PKGBUILDs from a user and opens them up in $EDITOR
# fetch - downloads all packages from the user
# review - opens up each of the package directories in $EDITOR
# Default: fetches all packages and reviews them.

fetch(){
    pkgs=$(curl -s "https://aur.archlinux.org/rpc/?v=5&type=search&by=maintainer&arg=$1" | jq -r '.results[].PackageBase' | sort -u)

    if [[ -z ${pkgs} ]]; then
        printf "no packages found for %s\n" "$1"
        exit 1
    fi

    for pkg in $pkgs; do
        printf "===> Downloading %s...\n" "$pkg"
        curl -s "https://aur.archlinux.org/cgit/aur.git/snapshot/$pkg.tar.gz" | tar xzm
    done
}

review(){
    for pkgbuild in $(ls ./*/PKGBUILD | sort); do
        printf "Review %s?" "${pkgbuild%/*}"
        read
        pushd "${pkgbuild%/*}" > /dev/null
        "$EDITOR" .
        popd > /dev/null
    done
}

while (( $# )); do
    case "$1" in
        fetch) shift; fetch "$@" ; exit 0;;
        review) shift; review "$@" ; exit 0;;
        *) fetch "$@" && review "$@" ;;
    esac
done
