#!/bin/sh -xe

# check
test -e /sbin/vmdiskclean && echo "already setup." && exit

# keymap
setup-keymap us us
setup-keymap jp jp

sed -r "s;#(.*[0-9]/community);\1;g" -i /etc/apk/repositories
echo "Welcome to Alpine Linux!" > /etc/motd
sed -i -e "s/TIMEOUT [0-9]\+/TIMEOUT 1/" /boot/extlinux.conf
sed -i -e "s/PROMPT 0/PROMPT 1/" /boot/extlinux.conf

# editor
apk add nano nano-syntax
echo 'include "/usr/share/nano/*.nanorc"' >> /etc/nanorc

# inittab
sed -r "s;^(ttyS0:.*);#\1;g" -i /etc/inittab

# mdev.conf
sed -i "s/ttyUSB/ttyACM[0-9]\troot:dialout 0660 @ln -sf \$MDEV modem\nttyUSB/;" /etc/mdev.conf

# profile
echo "umask 002" > /etc/profile.d/umask
echo "alias nano='nano -w'" > /etc/profile.d/nano
echo -e "#!/bin/sh\nsudo poweroff\n" > /sbin/shutdown
chmod 755 /sbin/shutdown

# vagrant (passwd: vagrant)
umask 002
adduser -D vagrant
echo "vagrant:vagrant" | chpasswd 
addgroup vagrant dialout

# sudo
apk add sudo
echo "vagrant ALL=(ALL) NOPASSWD: ALL" > /etc/sudoers.d/vagrant
chmod 400 /etc/sudoers.d/vagrant

# doas
apk add doas
echo 'permit nopass :wheel' > /etc/doas.d/wheel.conf
chmod 400 /etc/doas.d/wheel.conf
addgroup vagrant wheel

# ssh
cd /home/vagrant
chmod 2755 .
mkdir -m 700 .ssh
wget https://raw.githubusercontent.com/hashicorp/vagrant/master/keys/vagrant.pub
mv vagrant.pub .ssh/authorized_keys
chmod 600 .ssh/authorized_keys
chown vagrant:vagrant .ssh .ssh/*

# random
apk add haveged
rc-update add haveged
#apk add rng-tools
#rc-update add rngd
#cat /proc/sys/kernel/random/entropy_avail

# vboxfs
apk add virtualbox-guest-additions
rc-update add virtualbox-guest-additions
rc-update add local
addgroup vagrant vboxsf

# mount
cd /home/vagrant
mkdir -m 777 /vagrant
ln -s /vagrant vagrant
chown vagrant:vagrant /vagrant vagrant
VUID=`id -u vagrant`
VGID=`id -g vagrant`
cat<<EOF>.profile
#!/bin/sh
if grep -q -E "vboxsf.*uid=0,gid=0" /proc/mounts ; then
  sudo umount /vagrant
  sudo mount.vboxsf -o uid=$VUID,gid=$VGID,rw vagrant /vagrant
fi
EOF
chmod 755 .profile
chown vagrant:vagrant .profile

# audio
addgroup vagrant audio

# bash
apk add bash

# vmdiskclean
cat<<EOF>/sbin/vmdiskclean
#!/bin/sh
rm -f /var/cache/apk/*
rm -f /var/log/* /var/log/*/*
rm -f /home/*/.ash_history
rm -f /root/.ash_history
rm -f /etc/resolv.conf
dd if=/dev/zero of=/zero bs=8192
rm /zero
dd if=/dev/zero of=/boot/zero bs=8192
rm /boot/zero
poweroff
EOF
chmod 755 /sbin/vmdiskclean

# reboot
echo "try reboot"

