#! /bin/sh

nix-instantiate --find-file nixpkgs >/dev/null || {
        echo "Could not find nixpkgs, please set up your NIX_PATH"
        exit 1
}

NIX_DO_STASH="${NIX_DO_STASH:-$HOME/.local/share/nix-do}"
NIX_DO_PROFILE="${NIX_DO_PROFILE:-$(readlink $HOME/.nix-profile)}"

mkdir -p "$NIX_DO_STASH"

op="$1"; shift

case "$op" in
        pull)
                cd "$(nix-instantiate --find-file nixpkgs)";
                git remote update
                git pull -v
                ;;
        expression)
                echo "let
                        pkgs = import <nixpkgs> {};
                        fullEnv = packages:
                          pkgs.buildEnv {
                              name = ''$USER-profile-env'';
                              paths = packages;
                              ignoreCollisions = true;
                              pathsToLink = [''/''];
                          };
                        in
                        fullEnv [
                          $(for p in "$NIX_DO_STASH"/*/output*; do
                                test -e "$p" && readlink -f "$p"
                          done)
                        ]
                "
                ;;
        rebuild)
                nix-env --set -p "$NIX_DO_PROFILE" "$(nix-instantiate -E "$("$0" expression)")"
                ;;
        install)
                for p in "$@"; do
                        nix-build "<nixpkgs>" -A "$p.all" -o "$NIX_DO_STASH/$p/output"
                done
                "$0" rebuild
                ;;
        upgrade)
                "$0" install $("$0" list)
                ;;
        remove)
                ( cd "$NIX_DO_STASH"; for p in "$@"; do rm -rf "$p"; done);
                "$0" rebuild
                ;;
        clean)
                nix-collect-garbage -d
                ;;
        list)
                ( cd "$NIX_DO_STASH"; ls )
                ;;
esac