#!/usr/bin/env bash
# This utility pre-allocs a file and adds execution permissions. It also
# removes the resulting file if it is empty after the editor closes.

LD_INTERNAL=1
. $(dirname $(realpath $0))/ld.source

use_path=1
if [[ $1 == "-n" ]]; then
  shift
  use_path=0
fi

if [[ -z $1 ]];
then
  echo "No filename specified."
  exit 2
fi

if [[ -z "${EDITOR}" ]];
then
  # ched is defined in ld.source
  ched "EDITOR env variable not set! You will have to set it yourself in the next screen."
fi

file=$1
file_exist=0
file_in_path=$(whereis $1 | awk '{print $2}')
path_exist=0

[[ -e "$file" ]] && file_exist=1
[[ $use_path == 1 ]] && [[ -n "$file_in_path" ]] && path_exist=1

if [[ $path_exist == 1 && $file_exist == 0 ]]; then
  file=$file_in_path
elif [[ $path_exist == 1 && $file_exist == 1 ]]; then
  # Check if they are actually the same file
  if [[ $(realpath "$file") != $(realpath "$file_in_path") ]]; then
    echo "Multiple instances of \"$1\" were located, please make a selection:"
    echo "1. Local file: \"$file\""
    echo "2. File found in PATH: \"$file_in_path\""
    read -p "Please select a choice, the default choice (with no entry) is 2 [1..2]: " choice

    case "$choice" in
      1)
        file=$file
        ;;
      2|"")
        file="$file_in_path"
       ;;
      *)
        file="$file_in_path"
       ;;
    esac
  fi
fi

# Determine if the file already exists before we touch it
if [[ -e "$file" ]]; then
  existed=1
else
  existed=0
fi

touch "$file"
chmod +x "$file"
daisy editor "$file"

# Only remove if it's empty AND we created it in this session
if [[ ! -s "$file" && $existed -eq 0 ]]; then
  rm -f "$file"
fi
