#!/bin/sh

# Author: Benoit PAPILLAULT <benoit.papillault@sourcemage.org>
# Creation : 2004-12-09

# Requirements: 
#  - a working sourcemage system, with sorcery
#  - an internet access to download sources
#  - a cross compiler if you choose to cross compile
#
# Output: a working chroot system

# read the configuration file for IMAGE
. config
. config-auto

# save the existing /etc/sorcery/local/roots
if [ -f /etc/sorcery/local/roots ]; then
  cp /etc/sorcery/local/roots /etc/sorcery/local/roots.sav
fi &&

# you need to properly setup CROSS_INSTALL feature before running this script
# however, INSTALL_ROOT is automatically set (destroying your sorcery setting)

cat <<EOF > /etc/sorcery/local/roots &&
       INSTALL_CACHE="/var/cache/sorcery"
          STATE_ROOT="${IMAGE}"
          TRACK_ROOT=""
        INSTALL_ROOT="${IMAGE}"
EOF

# create the $IMAGE directory if needed
mkdir -p "${IMAGE}" &&

# copy dependency information (right now, resurrect does not take care
# of optional dependency, see
# http://bugs.sourcemage.org/show_bug.cgi?id=8515)

mkdir -p "${STATE_DIRECTORY}" &&
cp /var/state/sorcery/depends "${STATE_DIRECTORY}" &&

# cast all the needed spells (we did twice to properly handle optional
# dependencies like wget -> openssl)

yes "" | cast basesystem &&

# restore /etc/sorcery/local/roots
if [ -f /etc/sorcery/local/roots.sav ]; then
  mv /etc/sorcery/local/roots.sav /etc/sorcery/local/roots
fi &&

# update /lib and /usr/lib symlinks
touch "${IMAGE}/etc/ld.so.conf" &&
ldconfig -r "${IMAGE}" &&

# setup some files

mkdir -p "${IMAGE}/etc" &&
cp /etc/resolv.conf "${IMAGE}/etc" &&
cp base-files/passwd "${IMAGE}/etc" &&
cp base-files/group "${IMAGE}/etc" &&

# creates FHS 2.3 directories

cat data/FHS-2.3 | grep -v "^#" | grep -v "^$" | while read dir mode;
do
  mkdir -p "${IMAGE}/${dir}" &&
  if [ -n "${mode}" ]; then
    chmod "${mode}" "${IMAGE}/${dir}"
  fi
done &&

# install stable sorcery/grimoire
./install-sorcery-grimoire
