#!/bin/sh
if [ "$#" -ne 1 ]; then
  echo "usage: ${0##*/} <file>"
  exit 1
fi

first_link () {
  if [ "${1%/*}" != "$1" ]; then
    local x="$(first_link "${1%/*}")"
  fi
  if [ -z "$x" ] && [ -L "$1" ]; then
    echo "$1"
  else
    echo "$x"
  fi
}

NIX="$HOME/.local/nixos/user"
FIRST="$(first_link "$(realpath -s "$1")")"
if ! [ -z "$FIRST" ]; then
  LINKED="$(realpath "$FIRST")"
  if [ "${LINKED#/nix/store/}" != "$LINKED" ]; then
    CONFIG="${FIRST#~/.config/}"
    if [ "$CONFIG" != "$FIRST" ] && [ -e "$NIX/config/$CONFIG" ]; then
      rm "$FIRST"
      ln -s "$NIX/config/$CONFIG" "$FIRST"
      $EDITOR "$1"
      exit
    fi
    BIN="${FIRST#~/.local/bin}"
    if [ "$BIN" != "$FIRST" ] && [ -e "$NIX/bin/$BIN" ]; then
      rm "$FIRST"
      ln -s "$NIX/bin/$BIN" "$FIRST"
      $EDITOR "$1"
      exit
    fi
    SEARCH="$(fd "$CONFIG" "$NIX" -p1)"
    if [ -n "$SEARCH" ]; then
      rm "$FIRST"
      ln -s "$SEARCH" "$FIRST"
      $EDITOR "$1"
      exit
    fi
    echo "not symlinkable"
    exit 1
  fi
fi
if ! [ -e "$1" ]; then
  DIR="${1%/*}"
  [ "$DIR" != "$1" ] && mkdir -p "$DIR"
fi
$EDITOR "$1"
