#!/bin/sh

#####
#  Created By: Jason Plum <jplum@archlinuxarm.org>
#  Prepared for: Arch Linux ARM
#  ----------
#  Automation to convert NSA-310 to Arch Linux ARM on /dev/sda
#  : /dev/sda is sata port 1, left side of enclosure.
#####
echo "Automatic Installation of Arch Linux ARM"

###
#  setup u-boot environment
echo "- set bootloader"
fw_setenv arcNumber 4402
fw_setenv mainlineLinux yes
fw_setenv bootargs_stock 'console=ttyS0,115200 mtdparts=nand_mtd:0x100000(uboot),0x80000(uboot_env),0x80000(key_store),0x80000(info),0xA00000(etc),0xA00000(kernel_1),0x2FC0000(rootfs1),0xA00000(kernel_2),0x2FC0000(rootfs2) root=/dev/nfs rw init=/init'
fw_setenv bootargs_linux 'console=ttyS0,115200 mtdparts=nand_mtd:0x100000(uboot),0x80000(uboot_env),0x80000(key_store),0x80000(info),0xA00000(etc),0xA00000(kernel_1),0x2FC0000(rootfs1),0xA00000(kernel_2),0x2FC0000(rootfs2) root=/dev/sda2 rw rootwait loglevel=8'
fw_setenv bootcmd_linux 'setenv bootargs $(bootargs_linux); ide reset; ext2load ide 0:1 $(loadaddr) /uImage; bootm $(loadaddr)'
fw_setenv bootcmd_stock 'setenv bootargs $(bootargs_stock); nand read.e $(loadaddr) $(kernel_addr) 0xA00000; bootm $(loadadr)'
fw_setenv to_stock "setenv mainlineLinux no; setenv bootcmd \'run bootcmd_stock\'; saveenv; reset"
fw_setenv to_linux "setenv mainlineLinux yes; setenv bootcmd \'run bootcmd_linux\'; saveenv; reset"

###
#  setup the partitions on the disk (sda)
#  : 16M 1st partition, ext2/3
echo "- parition sda"
fdisk /dev/sda <<EOF
o
n
p
1

+16M

n
p
2


p
w

EOF
echo " * pause for ioctl to re-sync partitions"
sleep 5
###
#  make filesystems
echo "- make filesystems"
#  ext2 makes u-boot happy.
mkfs.ext2 -L "boot" /dev/sda1
#  stock does not know how to make ext4!
mkfs.ext4 -L "rootfs" /dev/sda2

###
#  make dirs & mount
echo "- mount destination"
mkdir -p /tmp/boot
mount -t ext2 /dev/sda1 /tmp/boot
mkdir -p /tmp/rootfs
mount -t ext4 /dev/sda2 /tmp/rootfs

###
#  prepare the system
#  extract the rootfs
echo "- extract rootfs"
tar xzf /mnt/parnerkey/rootfs.tgz -C /tmp/rootfs/

#  copy the uImage to the boot partition
echo "- prepare boot partition"
cp -aR /tmp/rootfs/boot/* /tmp/boot/

#  always make sure you're sync'd!
sync

###
#  prepare for first boot
#  set the bootcmd to run the steps to convert.
fw_setenv bootcmd 'run to_linux'
###
#  we're done here
echo "- REBOOTING!"
sync
reboot
