#!/bin/sh -e
#
# uv-python-symlink - creates symlinks in `~/.local/bin` for uv python versions

LOCALBIN="${HOME}/.local/bin"
UVDIR=$(uv python dir)

# create symlinks for pythonX.Y to uv-managed Pythons
for ITEM in "${UVDIR}"/*; do
  BASEITEM=$(basename "${ITEM}")

  FULLVERSION=$(echo "${BASEITEM}" | cut -d '-' -f 2)
  MINORVERSION=$(echo "${FULLVERSION}" | rev | cut -d '.' -f 2- | rev)
  DEST="${LOCALBIN}/python${MINORVERSION}"

  if [ -L "${DEST}" ]; then
    if [ -e "${DEST}" ]; then
      echo "${DEST} already exists and is valid. Nothing to do."
      continue
    else
      echo "${DEST} already exists but is broken. Removing."
      rm -- "${DEST}"
    fi
  fi

  rm -rf -- "${DEST}"
  ln -s "${UVDIR}/${BASEITEM}/bin/python${MINORVERSION}" "${DEST}"
  echo "${DEST} created."
done

# create symlink for python to latest uv-managed python
LATESTPYTHON=$(uv python find)
DEST="${LOCALBIN}/python"

if [ -L "${DEST}" ]; then
  if [ -e "${DEST}" ]; then
    echo "${DEST} already exists and is valid. Nothing to do."
    exit
  else
    echo "${DEST} already exists but is broken. Removing."
    rm -- "${DEST}"
  fi
fi

rm -rf -- "${DEST}"
ln -s "${LATESTPYTHON}" "${DEST}"
echo "${DEST} created."
