#!/bin/bash
set -e

TMP=/root/temp
umount $TMP 2>/dev/null || true
mkdir -p $TMP

modprobe -r ubifs 2>/dev/null || true
for i in $(seq 0 1)
do
	ubidetach -p /dev/mtd$i 2>/dev/null || true
done
modprobe -r ubi 2>/dev/null || true
modprobe -r nandsim 2>/dev/null || true

mtd=/dev/mtd0
ubi=/dev/ubi0

ID="0xec,0xa1,0x00,0x15" # 128M 128KB 2KB
#ID="0x20,0xa5,0x00,0x15" # 2GB 128KB PEB, 2KB page
#ID="0x20,0xa5,0x00,0x26" # 4G 256KB 4KB 1KB-sub-page
#ID="0x20,0xa7,0x00,0x26" # 4G 256KB 4KB 2KB-sub-page
#ID="0x20,0x33,0x00,0x00" # 16M 16KB PEB, 512 page

modprobe nandsim id_bytes=$ID

if [ "$1" == "1" ]
then
	modprobe ubi mtd="0,2048" fm_autoconvert
	ubimkvol -N vol_a -m -n 0 /dev/ubi0
	modprobe ubifs
	mount -t ubifs -osync /dev/ubi0_0 $TMP
else
	nandwrite /dev/mtd0 ubifs.img > /dev/null
	modprobe ubi mtd="0,4096" #fm_autoconvert
	modprobe ubifs
	mount -osync -t ubifs /dev/ubi0_0 $TMP
fi
