#!/bin/sh
#
# Usage: rm-orphans [<location> [<sources>]]
#
# Without any parameters performs search on versions specified below
# Orphans are moved from ../bin/.. to ../orphans/.. (/bin/ in location is assued)
#

LOC="$1"
SRC="$2"
VERS=none
BASE=/Volumes/Builds/packages

if [ -z "$LOC" ]; then
    VERS=`sed 's/:.*//' vers`
    maj=`uname -r|sed 's:\..*::'`
    POSTFIX=universal
    if [ "$maj" = 8 ]; then OSCODE=tiger; else OSCODE=leopard; fi
    SYNTH=yes
    if [ "$maj" = 10 ]; then OSCODE=snowleopard; POSTFIX=x86_64; fi
    if [ "$maj" = 13 ]; then OSCODE=mavericks; POSTFIX=x86_64; fi
    if [ "`arch`" = arm64 ]; then OSCODE=big-sur; POSTFIX=arm64; fi
fi

wd=`pwd`

for ver in $VERS; do
    if [ "$SYNTH" = yes ]; then
	LOC=$BASE/$OSCODE-$POSTFIX/bin/$ver
    fi
    if [ -z "$SRC" ]; then
	SRC=$BASE/CRAN/src/contrib
    fi

    echo "Checking $LOC vs $SRC"
    ORPH=`echo "${LOC}"|sed 's:/bin/:/orphan/:'`
    mkdir -p "$ORPH"

    R --vanilla --no-save -s -q <<EOF
src=Sys.glob("$SRC/*")
src.p=gsub("_.*","",substr(src,nchar("$SRC/*"),1e3))
bin=Sys.glob("$LOC/*")
bin=bin[!grepl("/00",bin)] 
bin.p=gsub("_.*","",substr(bin,nchar("$LOC/*"),1e3))
orp=bin[!(bin.p %in% src.p)]
if (length(orp)) {
  cat("Orphans:\n", paste(orp, collapse="\n"))
  for (o in orp) system(paste("mv", shQuote(o), shQuote("$ORPH/")))
} else cat("No orphans.\n");
EOF
done

cd "$wd"