#!/bin/sh

echo "nix-cache: Setting up ssh key and host" >&2
STORE_HOST_PUB_KEY="$(cat "$NIX_CACHE_SSH_PUBLIC_KEY_PATH" | base64 | tr -d '\n')"
STORE_URL="ssh://nix-ssh@nix-cache.wopus.dev?trusted=true&compress=true&ssh-key=$NIX_CACHE_SSH_PRIVATE_KEY_PATH&base64-ssh-public-host-key=$STORE_HOST_PUB_KEY"
echo STORE_URL="$STORE_URL" >&2

NIX_EXTRA_CONFIG_FILE=$(mktemp)
cat > "$NIX_EXTRA_CONFIG_FILE" <<EOF
  extra-substituters = $STORE_URL
EOF

echo "nix-cache: Adding remote cache as substituter" >&2
export NIX_USER_CONF_FILES="$NIX_EXTRA_CONFIG_FILE:$NIX_USER_CONF_FILES"

echo "nix-cache: Setting up nix hook" >&2
nix() {
    echo "nix-cache: executing nix hook" >&2
    command nix "$@"
    local STATUS="$?"

    local BUILD=no
    if test "$STATUS" = "0"; then
        for arg in "$@"; do
            echo "nix-cache: evaluating arg '$arg'" >&2
            case "$arg" in
                build)
                    echo "nix-cache: enablig upload" >&2
                    BUILD=yes
                ;;
                -*)
                    echo "nix-cache: ignoring argument '$arg'" >&2
                ;;
                *)
                    if test "$BUILD" = yes; then
                        echo "nix-cache: Sending path $arg" >&2
                        command nix copy --to "$STORE_URL" "$arg" || true
                    else
                        echo "nix-cache: not building, ignoring argument '$arg'" >&2
                    fi
                ;;
            esac
        done
    else
        echo "nix-cache: nix exited with code '$STATUS', ignoring" >&2
    fi

    return "$STATUS"
}
