#!/bin/sh

NIX_STASH_DIR="$XDG_CONFIG_HOME/nix_stash"
FILE_STACK_PATH="$NIX_STASH_DIR/nix_stash_stack"

# pop the last line from the file-stack and return it
pop_from_file_stack() {
  line="$(tail -n 1 "$FILE_STACK_PATH")"
  if [ -z "$line" ]; then
    exit 1
  fi
  sed -i "$ d" "$FILE_STACK_PATH"
  echo "$line"
}


do_pop() {
  last_file="$(pop_from_file_stack)" || exit 1
  echo "restoring $last_file"
  trash "$last_file"

  [ ! -s "$FILE_STACK_PATH" ] && home-manager switch
}


do_stash() {
  config_file="$(realpath --no-symlinks "$1")"
  if [ ! -L "$config_file" ]; then
    echo "Given file is not a symlink into the nix-store"
    exit 1
  fi

  file_in_store="$(readlink -f "$config_file")"

  if ! echo "$file_in_store" | grep -q "/nix/store"; then
    echo "file is not a symlink into the nix store"
    exit 1
  fi

  # remove the symlink and write the path to the stack
  mkdir -p "$NIX_STASH_DIR"
  rm -rf "$config_file"
  echo "$config_file" >> "$FILE_STACK_PATH"

  # replace the file with the contents of the generated config file
  cp -rp "$file_in_store" "$config_file"
  chmod 777 "$config_file"

  # open the file in nvim
  "$EDITOR" "$config_file"
}

do_list() {
  cat "$FILE_STACK_PATH"
}

print_usage() {
  echo "usage: $0 {<filepath> | pop | list}"
  echo "  to stash a file:   $0 <filepath>"
  echo "  to restore a file: $0 pop"
  echo "  list the stack:    $0 pop"
  exit 1
}

case "$1" in
  "")
    print_usage
    ;;
  pop) 
    do_pop 
    ;;
  list)
    do_list
    ;;
  *) 
    do_stash "$1" 
    ;;
esac



