#!/bin/rc

rfork ne

flag e +

root=$home/lib/9legacy
cache=$root/cache
plan9=$root/plan9
pkg=$root/pkg
list=$cache/patch.html

if(! ~ $#* 1){
	echo usage: `{basename $0} name >[2=1]
	exit usage
}

if(test -f $pkg/$1/$1.diff){
	echo `{basename $0}: $1 is installed >[2=1]
	exit installed
}
if(! test -f $list){
	echo `{basename $0}: must run 9legacy/update once >[2=1]
	exit update
}

fn depends {
	#9legacy/deps $cache/patch.html |
	#awk '$1 == "'$1'" {
	#	for(i = 3; i <= NF; i++)
	#		print $i
	#}'
}

deps=`{depends $1}
required=()
for(p in $deps){
	if(! test -f $pkg/$p/$p.diff)
		required=($required $p)
}
if(! ~ $#required 0){
	echo `{basename $0}: $1 require to install: $required >[2=1]
	exit deps
}

9legacy/cache $1 || exit cache
files=`{sed -n 's!^\+\+\+ [ab]?/([^ 	]+)([ 	].*)?!\1!p' $cache/$1.diff}
if(~ amd64/include/ape/_apetypes.h $files)
	for(a in arm sparc power 386 spim mips){
		files=($files $a/include/ape/_apetypes.h)
		mkdir -p $plan9/$a/include/ape
		touch $plan9/$a/include/ape/_apetypes.h
	}
dirs=()
for(f in $files){
	dir=`{basename -d $f}
	if(! ~ $dir $dirs)
		dirs=($dirs $dir)
	mkdir -p $plan9/$dir
	if(! test -e $plan9/$f && test -f /$f)
		cp /$f $plan9/$f
}

mkdir -p $pkg/$1
cp $cache/$1.diff $pkg/$1/$1.diff
for(p in $deps){
	touch $pkg/$p/$1.dep
}

bind -ac $plan9 /
for(dir in `{ls -p $plan9})
	bind -c $plan9/$dir /$dir
cd /
ape/patch -p1 -t <$pkg/$1/$1.diff
unmount /sys
