#!/bin/sh

set -e
set -u

cd /

set +e
umount  /mnt/boot
umount  /mnt
swapoff /dev/sda2
set -e

dd if=/dev/zero of=/dev/sda bs=1M count=8
parted -- /dev/sda mklabel msdos
parted -- /dev/sda mkpart primary 0g 1g
parted -- /dev/sda mkpart primary 1g 2g
parted -- /dev/sda mkpart primary 2g -0g
parted -- /dev/sda set 1 boot on
mkfs.ext2  -L BOOT -F /dev/sda1
mkswap     -L SWAP -f /dev/sda2
mkfs.btrfs -L ROOT -f /dev/sda3

ROOTFS_UUID=`btrfs filesystem show /dev/sda3 |
  grep -o 'uuid: [a-z0-9-]*' |
  sed -e 's/uuid: //'`

swapon /dev/sda2
mount  /dev/sda3 /mnt -o compress=lzo,autodefrag
btrfs  subvolume create /mnt/rootfs
btrfs  subvolume create /mnt/home
mkdir  /mnt/rootfs/{boot,home}
umount /mnt
mount  /dev/sda3 /mnt -o compress=lzo,autodefrag,subvol=/rootfs
mount  /dev/sda1 /mnt/boot

cat <<'EOF' > /etc/pacman.d/mirrorlist
Server = http://ftp.jaist.ac.jp/pub/Linux/ArchLinux/$repo/os/$arch
Server = http://ftp.tsukuba.wide.ad.jp/Linux/archlinux/$repo/os/$arch
EOF

pacstrap -d /mnt base syslinux openssh
genfstab -U /mnt > /mnt/etc/fstab

mkdir -p -m 0700 /mnt/root/.ssh
cat <<EOF > /mnt/root/.ssh/authorized_keys
ecdsa-sha2-nistp521 [payload removed: 232 characters] miku@hachune
EOF
chmod 0600 /mnt/root/.ssh/authorized_keys

cat <<EOF > /mnt/boot/syslinux/syslinux.cfg
DEFAULT arch
PROMPT 0
TIMEOUT 50
UI menu.c32
MENU TITLE Arch Linux
MENU COLOR border       30;44   #40ffffff #a0000000 std
MENU COLOR title        1;36;44 #9033ccff #a0000000 std
MENU COLOR sel          7;37;40 #e0ffffff #20ffffff all
MENU COLOR unsel        37;44   #50ffffff #a0000000 std
MENU COLOR help         37;40   #c0ffffff #a0000000 std
MENU COLOR timeout_msg  37;40   #80ffffff #00000000 std
MENU COLOR timeout      1;37;40 #c0ffffff #00000000 std
MENU COLOR msg07        37;40   #90ffffff #a0000000 std
MENU COLOR tabmsg       31;40   #30ffffff #00000000 std

LABEL arch
    MENU LABEL Arch Linux
    LINUX ../vmlinuz-linux
    APPEND root=UUID=${ROOTFS_UUID} rootflags='subvol=rootfs' ro
    INITRD ../initramfs-linux.img

LABEL archfallback
    MENU LABEL Arch Linux Fallback
    LINUX ../vmlinuz-linux
    APPEND root=UUID=${ROOTFS_UUID} rootflags='subvol=rootfs' ro
    INITRD ../initramfs-linux-fallback.img

LABEL hdt
        MENU LABEL HDT (Hardware Detection Tool)
        COM32 hdt.c32

LABEL reboot
        MENU LABEL Reboot
        COM32 reboot.c32

LABEL poweroff
        MENU LABEL Poweroff
        COM32 poweroff.c32
EOF

arch-chroot /mnt systemctl enable sshd.service
arch-chroot /mnt syslinux-install_update -i -a -m

