#!/usr/bin/env bash
set -euo pipefail

TMPDIR=$(pwd)/tmp
export TMPDIR

help() { declare -F | awk -v ORS="   " '{ print $3 }'; echo; }

build() {
  nix build .#"$1"
}

dump() {
  build "$@"
  if [ -e "vm-$1.nix" ]; then
    sudo cp -f result/vzdump* /mnt/share/proxmox/dump/
  elif [ -e "lxc-$1.nix" ]; then
    sudo cp -f result/tarball/nixos-image-lxc-*.tar.xz "/mnt/share/proxmox/template/cache/$1.tar.xz"
  fi
}

get-ip() {
  file="$1"
  if [[ "$file" = "proxmox" ]]; then
    echo 192.168.0.3
    return
  elif [[ "$file" != *.nix && -e "vm-$1.nix" ]]; then
    file="vm-$1.nix"
  elif [[ "$file" != *.nix && -e "lxc-$1.nix" ]]; then
    file="lxc-$1.nix"
  fi
  grep ip4 "$file" | grep -Po "[0-9]+(\.[0-9]+){3}"
}

deploy() {
  ip=$(get-ip "$1")
  TMPDIR=/tmp nix-shell -p '(nixos{}).nixos-rebuild' --run \
    'nixos-rebuild switch --flake .#'"$1"' --target-host admin@"'"$ip"'" --use-remote-sudo'
}

jump-deploy() {
  jump_ip=$(tailscale ip xalicas | head -n1)
  env NIX_SSHOPTS="-J robert@$jump_ip" ./Taskfile deploy "$1"
}

ssh() {
  command "${2:-mosh}" admin@"$(get-ip "$1")"
}

_modrinth() {
  slug="$1"
  mcversion=$(grep fabricServers vm-majcraft.nix | grep -Po "[0-9_]+" | head -n1)
  mcversion=${mcversion//_/.}
  curl -sSL "https://api.modrinth.com/v2/project/${slug}/version?loaders=fabric&game_versions=$mcversion"
}
majcraft-update() {
  mcversion=$(grep fabricServers vm-majcraft.nix | grep -Po "[0-9_]+" | head -n1)
  mcversion=${mcversion//_/.}
  versionWithoutPatch=${mcversion%.[0-9]}
  # nmDcB62a ModernFix # maintainer doesn't want to update past 1.21.4 until modpacks stabilize
  # Jrmoreqs AdvancedBackups # maintainer disappeared, replacing with fastback
  mods=(
    # r0v8vy1s Alternate_Current
    # sml2FMaA AntiXray
    # lhGA9TYQ Architectury_API
    # MBAkmtvl Balm
    # Y8o1j1Sf Better_Fabric_Console
    # e0M1UDsY Collective
    # P7dR8mSH Fabric_API
    ZHKrK8Rp FastBack
    # uXXizFIs FerriteCore
    # nvQzSEkH Jade
    # 7uh75ruZ KleeSlabs
    # fQEb0iXm Krypton
    # gvQqBUqZ Lithium
    # qQyHxfxd No_Chat_Reports
    # 34T8oVNY Pl3xMap
    # zQhsx8KF Servux
    # G9rHXWug Sessility
    # 9eGKb6K1 Simple_Voice_Chat
    # doqSKB0e Styled_Chat
    # DQIfKUHf Styled_Player_List
    # nxrXbh5K View_Distance_Fix
    # dbVXHSlv FabricExporter
    # l6YH9Als Spark
  )
  for (( i=0; i<${#mods[*]}; i+=2 )); do
    slug="${mods[$i]}"
    name="${mods[$i+1]}"
    uri="https://api.modrinth.com/v2/project/${slug}/version?loaders=fabric&game_versions=$mcversion"
    hash=$(curl -sSL "$uri" \
      | jq -r '.[] | select(.loaders[] | contains("fabric"))' \
      | jq -r 'select(.game_versions[] | . == ("'"$mcversion"'", "'"$versionWithoutPatch"'"))' \
      | jq -r --slurp 'first | .id')
    >&2 echo "$name ($mcversion $versionWithoutPatch) $uri $hash"
    echo "$name = pkgs.$(nix run github:Infinidoge/nix-minecraft#nix-modrinth-prefetch -- "$hash");"
  done
}

"$@"
