#~/bin/bash

pkgs="${@:2}"
needed="--needed"
if [[ "$pkgs" =~ "--reinstall" ]]; then
  pkgs="${pkgs/"--reinstall"/""}"
  needed=""
fi

brokenpkgs=$(pacman-static -Sp $(pacman-static -Qq) ${pkgs} 2>/dev/null | \
             grep ':: unable to satisfy dependency' | cut -d"'" -f2)
brokenpkgs=$(echo $brokenpkgs)
brokenpkgs=${brokenpkgs//" "/","}

if [ "$1" == "install" ] || [ "$1" == "upgrade" ]; then
  pacman-static -Syu --noconfirm ${needed} --assume-installed=$brokenpkgs ${pkgs}
elif [ "$1" == "remove" ]; then
  pacman-static -R --noconfirm --assume-installed=$brokenpkgs ${pkgs}
  rempkgs=$(pacman-static -Qdtq)
  [ -n "$rempkgs" ] && pacman-static --noconfirm -Rns -
elif [ "$1" == "list" ]; then
  pacman-static -Q
else
  echo "Usage: $(basename $0) list|install|upgrade|remove [--reinstall]" [pkgname...]
fi

