#!/bin/sh
# Part of spindle http://asbradbury.org/projects/spindle
#
# See LICENSE file for copyright and license details

set -e

. ./common

CURIMG=stage0.$IMGFORMAT

create_partition_table() {
  # TODO: partition sizes shouldn't be hard-coded
  sudo parted $1 <<EOF
  unit b
  mklabel msdos
  mkpart primary fat32 $(expr 4 \* 1024 \* 1024) $(expr 60 \* 1024 \* 1024 - 1)
  mkpart primary ext4 $(expr 60 \* 1024 \* 1024) 100%
  print
  quit
EOF
}

do_debootstrap() {
  # Need bzip2 for http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=657560
  sudo debootstrap --components=main,contrib,non-free \
  --verbose \
  --foreign --arch $TGT_ARCH --include=bzip2 \
  --no-check-gpg \
  $1 $2 $DEB_MIRROR
}

APT_CACHE_IMG=wheezy_apt_cache.$IMGFORMAT

mkdir -p $WORKDIR
cd $WORKDIR
[ -b "$NBD_DEV" ] || die "nbd device '%s' does not exist. Try sudo modprobe nbd max_part=16" "$NBD_DEV"
# Delete apt cache if it was not successfully created
[ -e "$APT_CACHE_IMG.wip" ] && rm "$APT_CACHE_IMG"
if ! [ -f "$APT_CACHE_IMG" ]; then
  printf "No apt cache disk image exists. Making one.\n"
  dotask qemu-img create -f $IMGFORMAT $APT_CACHE_IMG 4G
  touch "$APT_CACHE_IMG.wip"
  sudo -v
  dotask attach_image_to_nbd $APT_CACHE_IMG $NBD_DEV
  dotask sudo mkfs.ext4 -O ^huge_file $NBD_DEV
  mkdir -p rootfs
  dotask sudo mount $NBD_DEV rootfs
  sudo mkdir -p rootfs/archives/partial
  sudo touch rootfs/archives/lock
  dotask sudo umount $NBD_DEV
  dotask detach_image_from_nbd $NBD_DEV
  rm "$APT_CACHE_IMG.wip"
fi
dotask qemu-img create -f $IMGFORMAT $CURIMG $SDSIZE
sudo -v
dotask attach_image_to_nbd $CURIMG $NBD_DEV
dotask create_partition_table $NBD_DEV
dotask sudo mkdosfs -n boot -S 512 -s 16 -v $BOOT_DEV
dotask sudo mkfs.ext4 -O ^huge_file $ROOT_DEV
mkdir -p boot
dotask sudo mount $BOOT_DEV boot
mkdir -p rootfs
dotask sudo mount $ROOT_DEV rootfs
dotask do_debootstrap wheezy rootfs
universal_cleanup
dotask finish_image
