#!/bin/bash
set -euo pipefail

FORCE=false
for arg in "$@"; do
  case "$arg" in
    --force|-f) FORCE=true ;;
  esac
done

ENVIRS="${HOME}/git/environs"

case "$(uname -s)" in
  Linux)  plat="linux" ;;
  Darwin) plat="mac"   ;;
  *)      plat=""      ;;
esac

for envdir in "${ENVIRS}"/*/; do
  [ -d "${envdir}" ] || continue
  repo=$(basename "${envdir}")
  target="${HOME}/git/${repo}"

  src=""
  if [ -n "${plat}" ] && [ -f "${envdir}${plat}.env.dev" ]; then
    src="${envdir}${plat}.env.dev"
  elif [ -f "${envdir}env.dev" ]; then
    src="${envdir}env.dev"
  fi

  if [ -z "${src}" ]; then
    echo "  Skipping ${repo}: no env.dev in environs"
    continue
  fi

  if [ ! -d "${target}" ]; then
    echo "  Skipping ${repo}: ${target} does not exist"
    continue
  fi

  if [ -L "${link}" ] || [ -e "${link}" ]; then
    if [ -L "${link}" ] && [ "$(readlink "${link}")" = "${src}" ]; then
      echo "  OK ${repo}: already linked"
      continue
    fi
    if $FORCE; then
      bak="${link}.bak"
      echo "  Force ${repo}: moving aside → $(basename "${bak}")"
      mv "${link}" "${bak}"
    else
      echo "  Skipping ${repo}: ${link} exists (use --force to override)"
      continue
    fi
  fi

  ln -s "${src}" "${link}"
  base_src=$(basename "${src}")
  echo "  Linked ${repo}: ${base_src} → .env"
done
