#!/bin/bash

# Generates list of all spells which we need caches for as well as
# a list of all spells that should not be dispelled from the chroot
# (all others are). They are stored in $STATE_DIR==../data

. ${0%/*}/config

# Adds known dependencies to the spell list $1
# Code stolen from mkiso
function add_dependencies() {
  local NUM_LINES=0
  while [ "$NUM_LINES" != "$(wc -l $1)" ] ;do

    NUM_LINES=$(wc -l $1)
    # When nothing here sees new spells, stop.

    local spell
    while read spell ;do
      grep "^$spell:[^:]*:on" /var/state/sorcery/depends
    done <$1 >/tmp/moredeps
    cat /tmp/moredeps | cut -d: -f2 | sed 's/(.*$//' >/tmp/morespells
    # The sed kills (BOOTLOADER) etc.

    mv $1 /tmp/oldspells
    cat /tmp/oldspells /tmp/morespells | sort -u >$1
    rm -f /tmp/oldspells /tmp/morespells /tmp/moredeps

  done # repeat until number of lines does not change anymore
}

if ! [ -e $STATE_DIR/list.reqd ] ;then
  echo "basesystem" >$STATE_DIR/list.reqd
  echo   "linux"   >>$STATE_DIR/list.reqd
fi

cat $STATE_DIR/iso.packages |
grep "unpack " | grep -v "end_unpack" |
sed "s/\(begin_\)\?unpack //" >/tmp/iso-list
cat /tmp/iso-list $STATE_DIR/install-list $STATE_DIR/optional-list |
  sed -e 's/#.*$//' -e 's/[[:blank:]]*$//' | grep -v "^$" |
  sort -u >$STATE_DIR/list.all
rm /tmp/iso-list

add_dependencies $STATE_DIR/list.reqd
add_dependencies $STATE_DIR/list.all
