#!/bin/bash

MULTISTRAP_CONFIG=myConfig.grip.multistrap # give name of configuration file
ROOTFS_DIR=/opt/multistrap
ROOTFS_IMG=rootfs.jffs2 # choose a suitable file system format
FILE_DIR=files
DEV_TABLE=device_table

set -e

echo "Multistrapping... "
if [ ! -d $ROOTFS_DIR ]; then mkdir -p $ROOTFS_DIR; fi
export MULTISTRAP_OUTPUT_DIR=$ROOTFS_DIR
multistrap -f $MULTISTRAP_CONFIG

echo "Create missing folders on rootfs..."
if [ ! -d $ROOTFS_DIR/etc/network ]; then mkdir -p $ROOTFS_DIR/etc/network; fi
if [ ! -d $ROOTFS_DIR/etc/init.d ]; then mkdir -p $ROOTFS_DIR/etc/init.d; fi
if [ ! -d $ROOTFS_DIR/etc/dhcp3 ]; then mkdir -p $ROOTFS_DIR/etc/dhcp3; fi
if [ ! -d $ROOTFS_DIR/etc/apt/apt.conf.d/ ]; then mkdir -p $ROOTFS_DIR/etc/apt/apt.conf.d; fi
if [ ! -d $ROOTFS_DIR/lib/modules/2.6.31 ]; then mkdir -p $ROOTFS_DIR/lib/modules/2.6.31; fi
if [ ! -d $ROOTFS_DIR/dev/shm ]; then mkdir -p $ROOTFS_DIR/dev/shm; fi
if [ ! -d $ROOTFS_DIR/usr/share/man/man1 ]; then mkdir -p $ROOTFS_DIR/usr/share/man/man1; fi
if [ ! -d $ROOTFS_DIR/usr/share/man/man7 ]; then mkdir -p $ROOTFS_DIR/usr/share/man/man7; fi
# more folders ...

echo "Copying config files to rootfs..."
cp -v $FILE_DIR/fstab $ROOTFS_DIR/etc/
cp -v $FILE_DIR/hostname $ROOTFS_DIR/etc/
cp -v $FILE_DIR/passwd $ROOTFS_DIR/etc/
touch $ROOTFS_DIR/lib/modules/2.6.31/modules.dep
# more config files ...

echo "Copying scripts to rootfs..."
cp -v $FILE_DIR/kversion $ROOTFS_DIR/opt/ntb/
cp -v $FILE_DIR/hwversion $ROOTFS_DIR/opt/ntb/
cp -v $FILE_DIR/hwclockfirst.sh $ROOTFS_DIR/etc/init.d/hwclockfirst.sh
cp -v $FILE_DIR/serial_config $ROOTFS_DIR/opt/ntb/
# more scripts ...

echo "Creating missing links on rootfs..."
if [ ! -L $ROOTFS_DIR/etc/mtab ]; then ln -v -s /proc/mounts $ROOTFS_DIR/etc/mtab; fi
if [ ! -L $ROOTFS_DIR/etc/rcS.d/S99smartmeter-init.sh ]; then ln -v -s ../init.d/smartmeter-init.sh $ROOTFS_DIR/etc/rcS.d/S99smartmeter-init.sh; fi
if [ ! -L $ROOTFS_DIR/etc/resolv.conf ]; then ln -v -s /var/run/resolv.conf $ROOTFS_DIR/etc/resolv.conf; fi
if [ ! -L $ROOTFS_DIR/etc/adjtime ]; then ln -v -s /var/local/adjtime $ROOTFS_DIR/etc/adjtime; fi

echo "Generating rootfs image file..."
mkfs.jffs2 -n -e 0x20000 -p 0x20000 -D $DEV_TABLE -l -d $ROOTFS_DIR -o $ROOTFS_IMG

echo "All done!"