#!/bin/bash

if [ -z "$url" ] ; then
    exit 0;
fi

disk=/dev/mmcblk0
part1=${disk}p1
part2=${disk}p2

# (re)create partitions
fdisk $disk >/dev/null 2>&1 <<EOF
d
1
d
2
d
3
d
4
n
p
1

+512M
n
p
2


t
1
ef
t
2
8e
w
EOF

udevadm settle --timeout 180

# create LVM
pvcreate -ff -y $part2
vgcreate -A n system $part2
lvcreate -A n -L 2G -n swap system
lvcreate -A n -L 10G -n root system
lvcreate -A n -L 8G -n home system
lvcreate -A n -l 100%FREE -n opt system

# format
mkfs.vfat $part1
mkfs.ext4 /dev/system/root
mkfs.ext4 /dev/system/home
mkfs.ext4 /dev/system/opt
mkswap    /dev/system/swap

# mount
mkdir -p /mnt
mount /dev/system/root /mnt
mkdir -p /mnt/boot/efi /mnt/home /mnt/opt
mount $part1 /mnt/boot/efi
mount /dev/system/home /mnt/home
mount /dev/system/opt /mnt/opt

# system copy
curl $url/root.tgz 2>/dev/tty0 | tar zx -C /mnt
curl --silent $url/efi.tgz | tar zx -C /mnt/boot/efi
curl --silent $url/home.tgz | tar zx -C /mnt/home
curl --silent $url/opt.tgz | tar zx -C /mnt/opt
curl --silent $url/patch.tgz | tar zx -C /mnt

# grub installation
mount -t proc proc /mnt/proc
mount -t sysfs sysfs /mnt/sys
mount -o bind /dev /mnt/dev
chroot /mnt /bin/bash -c '
sed -i s/-Xmx1024m/-Xmx512m/ /opt/tomcat/bin/setenv.sh
rm /etc/udev/rules.d/70-persistent-net.rules
grub2-mkconfig -o /boot/grub2/grub.cfg
dracut --persistent-policy by-path --force
grub2-install
'
umount /mnt/dev
umount /mnt/sys
umount /mnt/proc

# umount
umount /mnt/boot/efi
umount /mnt/home
umount /mnt/opt
umount /mnt
