#!/bin/sh
set -e

# inline script to installa apt without building up caches
INSTALL_SCRIPT='mount -t tmpfs tmpfs /var/lib/apt;
mount -t tmpfs tmpfs /var/cache/apt;
opts="-o Dir::Log::Terminal=/dev/null -o APT::Sandbox::User=root";
apt-get $opts update;
apt-get $opts install -y '

binname="$1"
test -z "$binname" && ( echo "missing argument: programm name"; exit 1 )

echo "## searching package for: $binname"
plash init
package=$(plash run -i ubuntu --run "$INSTALL_SCRIPT command-not-found" -- python3 -c "
import sys;
from CommandNotFound.CommandNotFound import  CommandNotFound;
found = CommandNotFound().get_packages(sys.argv[-1]);
found and print(found[0][0])" "$binname")
test -z "$package" && ( echo "## error: no package found"; exit 1 )

echo "## caching package: $package"
path='/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games'
binpath=$(plash run -i ubuntu --run "$INSTALL_SCRIPT $package" -- env PATH=$path which "$binname")
test -z "$binpath" && ( echo "## internal error: could not find binary for package: $package"; exit 1 )

hostbin=~/bin/"$binname"
mkdir -p ~/bin
#echo "## writing recipe to $hostbin"
cat >"$hostbin" <<EOL
#!/usr/bin/env plash-exec
# plash-exec: exec=$binpath
--image
ubuntu
--run
$INSTALL_SCRIPT $package
EOL
chmod 755 "$hostbin"

nodepath=$(plash nodepath --include $hostbin)
disk_used=$(du -sh "$nodepath" | cut -f1)

echo "## executable: ~/bin/$binname"
echo "## disk usage: $disk_used"
echo "## to uninstall run: plash rm -I ~/bin/$binname && rm ~/bin/$binname"
