#!/bin/sh

set -ex

DEV=$1

test -b $DEV || { echo "$DEV is not a block device" >& 2; exit 2; }
mount | grep $DEV && { echo "$DEV is mounted" >& 2; exit 2; }
pvs | grep $DEV && { echo "$DEV is LVM physical device" >& 2; exit 2; }

sector=$( echo p | fdisk $DEV | grep Units: | cut -d= -f2 | cut -d' ' -f 2)

test $sector -ge 512 || { "Invalid sector size: $sector" >& 2; exit 2; }

# to create the partitions programatically (rather than manually)
# we're going to simulate the manual input to fdisk
# The sed script strips off all the comments so that we can 
# document what we're doing in-line with the actual commands
# Note that a blank line (commented as "defualt" will send a empty
# line terminated with a newline to take the fdisk default.
sed -re 's/^[ \t]+([\+0-9a-zA-Z]*)[ \t]*#.*$/\1/' << EOF | fdisk $DEV
    p # print the partion table
    o # delete a partitions
    n # new partition
    p # primary
    1 # partition number
      # default start offset
    $((1024 * 1024 * 1024 * 16 / $sector)) # 16 GB
    t # set partition type
    82 # linux swap
    n # new partition
    p # primary partition
    2 # partition number
      # default start offset
      # fill the disk completely
    a # make a partition bootable
    2 # bootable partition is partition 2 -- /dev/sd*2
    p # print the in-memory partition table
    w # write the partition table
    q # and we're done
EOF

SWAP=${DEV}1
ROOT=${DEV}2

mkswap -L archswap $SWAP

# create XFS filesystem
mkfs.xfs -f -L arch $ROOT

MOUNT=/mnt/arch
mkdir -p $MOUNT
trap "umount $MOUNT" EXIT HUP INT ABRT TERM SEGV
mount $ROOT $MOUNT

# setup pacman
bash -c 'sleep 5; find / >& /dev/null' & # generate some entropy for pacman-key
pacman-key --init
pacman-key --populate archlinux
SELF="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
grep -q '^Server' /etc/pacman.d/mirrorlist || cp $SELF/conf/all/etc/pacman.d/mirrorlist /etc/pacman.d/

pacstrap $MOUNT base base-devel btrfs-progs dhcpcd openssh vim screen bind-tools perl-ldap git curl

genfstab -U -p $MOUNT | grep -v swap >> $MOUNT/etc/fstab

arch-chroot $MOUNT bash -c 'cd /root && git clone https://gitlab.fi.muni.cz/paradise/arch-deploy.git'
arch-chroot $MOUNT /root/arch-deploy/pdsupdate install $DEV
