#!/bin/sh

set -eu

util_path="${GITHUB_ACTION_PATH:-.}/scripts/utils.sh"

# shellcheck source=scripts/utils.sh
. "${util_path}"

group 'Retrieving Flake information'
flake_info=$(nix flake show --json --quiet --quiet)
endgroup

system=$(nix eval --impure --json --expr 'builtins.currentSystem')

group 'Show Packages'
packages=$(echo "$flake_info" | jq --raw-output --argjson system "$system" 'getpath(["packages", $system]) | select(. != null) | keys[]')
[ -z "$packages" ] || log "$packages"
endgroup

group 'Show Home Manager Configurations'
hmConfigs=$(echo "$flake_info" | jq --raw-output '.homeConfigurations | select(. != null) | keys[]')
[ -z "$hmConfigs" ] || log "$hmConfigs"
endgroup

group 'Show NixOS Configurations'
nixosConfigs=$(echo "$flake_info" | jq --raw-output '.nixosConfigurations | select(. != null) | keys[]')
[ -z "$nixosConfigs" ] || log "$nixosConfigs"
endgroup

closure_size() {
  name=$1
  path=$2
  log "Calculating size of $name at $path"
  path_info=$(nix path-info --closure-size --json "$path")
  echo "$path_info" |
    jq --compact-output \
      --arg pkg "$name" \
      --arg path "$path" \
      '.[] | {"name": $pkg, "path": $path, "size": .closureSize, "narSize": .narSize, "raw": .}'
}

pkgs_json() {
  for package in $packages; do
    log "Building $package"
    path=$(nix build --print-out-paths ".#$package")
    closure_size "$package" "$path"
  done
}

hm_configs_json() {
  for config in $hmConfigs; do
    log "Building $config"
    path=$(nix build --print-out-paths ".#homeConfigurations.$config.activationPackages")
    closure_size "$config" "$path"
  done
}

nixos_configs_json() {
  for config in $nixosConfigs; do
    log "Building $config"
    path=$(nix build --print-out-paths ".#nixosConfigurations.$config.config.system.build.toplevel")
    closure_size "$config" "$path"
  done
}

group 'Building packages'
pkgs=$(pkgs_json | jq --slurp .)
endgroup
group 'Building Home Manager configurations'
hmConfigs=$(hm_configs_json | jq --slurp .)
endgroup
group 'Building NixOS configurations'
nixosConfigs=$(nixos_configs_json | jq --slurp .)
endgroup

echo "{}" | jq \
  --argjson pkgs "$pkgs" \
  --argjson hmConfigs "$hmConfigs" \
  --argjson nixosConfigs "$nixosConfigs" \
  '{"packages": $pkgs, "nixosConfigurations": $nixosConfigs, "homeConfigurations": $hmConfigs}' >"${1:-/dev/stdout}"
