#!/bin/env sh

handleYadmSymlinks() {
  foundSymlinks=false

  for file in $(yadm diff --name-only --cached); do
    lsResult=$(ls -1 -l "$file")
    if [[ $lsResult != *"->"* ]]; then
      continue
    fi

    symlinkTarget=$(echo "$lsResult" | awk '{print $NF}')

    if [[ $lsResult != *"##"* ]]; then
      continue
    fi

    echo "$file is a YADM symlink. Telling git to ignore it..."

    yadm restore --staged "$file"
    echo "$file" >>~/.gitignore

    foundSymlinks=true
  done

  if [ $foundSymlinks ]; then
    echo "Symlinks found. Adding .gitignore to commit..."
    yadm add ~/.gitignore
  fi
}

handleYadmSymlinks
