#!/bin/bash
# run as: `sudo sync-asroot ...`
[[ -v AUR_DEBUG ]] && set -o xtrace
SUDO_HOME=$(eval echo "~$SUDO_USER")
XDG_CACHE_HOME=${XDG_CACHE_HOME:-$SUDO_HOME/.cache}
AURDEST=${AURDEST:-$XDG_CACHE_HOME/aurutils/sync}
argv0=sync-asroot

# default options
build_args=(-LR --chroot) sync_args=() keep_going=1

# colors (for build summary)
source /usr/share/makepkg/util/message.sh

if [[ ! -v NO_COLOR ]] && [[ ! -v AUR_DEBUG ]]; then
    [[ -t 2 ]] && colorize
fi

# option parsing
unset build_user
while getopts :U:d:k:fSuN OPT; do
    case $OPT in
        d) build_args+=(-d "$OPTARG"); sync_args+=(-d "$OPTARG") ;;
        f) build_args+=(-f "$OPTARG") ;;
        S) build_args+=(-S) ;;
        U) build_user=$OPTARG ;;
        k) keep_going=$OPTARG ;;
        u) sync_args+=(-u) ;;
        N) sync_args+=(--no-ver) ;;
    esac
done
shift $(( OPTIND-1 ))

# 1. define unprivileged commands ------------------------------------------------->
build_user=${build_user:-${SUDO_USER:-$USER}}
build_args+=(-U "$build_user")

build_env=(AUR_MAKEPKG="runuser -u $build_user -- makepkg"
           AUR_GPG="runuser -u $build_user -- gpg"
           AUR_REPO_ADD="runuser -u $build_user -- repo-add"
           AUR_BUILD_PKGLIST="runuser -u $build_user -- aur build--pkglist")

# 2. retrieve sources ------------------------------------------------------------->
ninja_dir=$(runuser -u "$build_user" -- mktemp -d) || exit
trap 'rm -rf "$ninja_dir"' EXIT

runuser -u "$build_user" -- \
    env AURDEST="$AURDEST" aur sync "${sync_args[@]}" "$@" --columns --save "$ninja_dir"/graph || exit 1

# 3. build queue ------------------------------------------------------------------>
if [[ -s $ninja_dir/graph ]]; then
    runuser -u "$build_user" -- aur sync--ninja "$AURDEST" <"$ninja_dir"/graph >"$ninja_dir"/build.ninja -- \
        env AUR_ASROOT=1 "${build_env[@]}" aur build "${build_args[@]}"

    env NINJA_STATUS='[%s/%t] ' ninja -C "$ninja_dir" -k "$keep_going"

    # The following is taken from aur-sync, but we want the build results always.
    #
    # Print all targets in dependency order
    NINJA_STATUS='[%s/%t] ' ninja -nC /var/empty -f "$ninja_dir"/build.ninja | \
        # [\w@\.\-\+]: valid characters for pkgname
        # alternative: [^\s]+ from rule `env -C ... > pkgbase.stamp`
        pcregrep -o1 -o3 '(\[\d+/\d+\] )(.+?)([\w@\.\-\+]+)(\.stamp)' | while read -r status pkg
    do
        if [[ -f $ninja_dir/$pkg.stamp ]]; then
            printf "${BOLD}${BLUE}%s${ALL_OFF} %s\t${BOLD}${GREEN}[OK]${ALL_OFF}\n" "$status" "$pkg"
        else
            printf "${BOLD}${BLUE}%s${ALL_OFF} %s\t${BOLD}${RED}[FAIL]${ALL_OFF}\n" "$status" "$pkg"
        fi
    done | column -t
fi
