# Execute before making package

# Require $prefix
recreate_link()
(
  set -e

  # This script searches $prefix for symlinks.
  # Whenever the symlinks' targets are absolute paths,
  # this script alters them with relative paths.

  find "$prefix" -type l -print0 |
  while read -r -d '' file
  do
    local target="$(readlink "$file")"
    if [[ "$target" != "$prefix"* ]]
    then
      continue
    fi

    local dir="$(dirname "$file")"

    #split paths
    local oldIFS="$IFS"
    IFS="/"
    target=($target)
    dir=($dir)
    IFS="$oldIFS"

    #how far are ${dir[@]} and ${target[@]} similar?
    local i
    for((i = 0; i < ${#dir[@]}; ++i))
    do
      if [[ "${dir[i]}" != "${target[i]}" ]]
      then
        break
      fi
    done

    local common=$i

    #make relative path
    local relpath=()
    for((i = ${#dir[@]}; i > common; --i))
    do
      relpath+=("..")
    done

    relpath+=(${target[@]:common})

    oldIFS="$IFS"
    IFS="/"
    relpath="${relpath[*]}"
    IFS="$oldIFS"

    #recreate link
    echo "relink: $file"
    rm -f "$file" && ln -s "$relpath" "$file"
  done
)
