#!/usr/bin/env bash

#
# This program creates symlinks in /usr/ports/installed to all the
# ports you have installed.
#

installed_path=/usr/ports/installed

# create a lookup table whose keys are the names of installed ports
declare -A my_installed
eval "my_installed=($(prt-get printf '%i: "%n" "%p/%n"\n' | awk -v FS=: '/^(yes|diff)/ {print $2}'))"

# check if the dir exists
if [ ! -d $installed_path ]; then
    mkdir -p $installed_path
fi

# Remove the link if the port is not installed, 
# or if the link does not point to a location known to prt-get.
OldCheck="Checking for obsolete links..."
while read -r LINK; do
    if [ "${my_installed[$LINK]}" != "$(realpath $installed_path/"$LINK")" ]; then
        rm "$LINK"
        OldCheck+=" $LINK"
    fi
done < <(find $installed_path -maxdepth 1 -xtype l -printf '%P\n')
echo "$OldCheck"

# Add links for installed ports if they don't exist.
NewCheck="Checking for missing links..."
for i in "${!my_installed[@]}"; do
    # packages do not have to have ports
    if [ ! -L "$installed_path/$i" ]; then
	ln -s "${my_installed[$i]}" $installed_path
        NewCheck+=" $i"
    fi
done
echo "$NewCheck"
