#!/bin/sh

set -e

test `id -u` -ne 0 ||
    exit 0

command -v makepkg &>/dev/null ||
    exit 0

install_pikaur() {
    PIKDIR="$HOME/.cache/pikaur/build/pikaur"
    test -d "$PIKDIR" ||
        git clone \
            https://aur.archlinux.org/pikaur.git \
            "$PIKDIR"

    cd "$PIKDIR"

    makepkg -si --noconfirm --needed
}

command -v pikaur &>/dev/null ||
    install_pikaur

cd "$HOME/.local/share/metapkg/"

source ./PKGBUILD

all_pkgs=$(pacman -Sql)
init_system=$(readlink /bin/init | cut -d- -f1)

pikaur \
    --pkgbuild \
    --install \
    --rebuild \
    --noconfirm \
    --keepbuilddep ||
    for depend in ${depends[@]}; do
        pikaur -S --needed --noconfirm $depend ||
        sudo pacman -S --needed --noconfirm $depend ||
        true
    done

init_deps=""
for depend in ${depends[@]}; do
    if printf "%s\n" $all_pkgs |
        grep "^$depend-$init_system\$" >/dev/null &&
        ! pacman -Qq "$depend-$init_system" >/dev/null; then
        init_deps="$init_deps $depend-$init_system"
    fi
done

if test -n "$init_deps"; then
    pikaur \
        --sync \
        --needed \
        --noconfirm \
        --keepbuilddep \
        $init_deps
fi
