#!/bin/sh

HOSTNAME=$1
PASSWD=$2

HD1=ada0
HD2=ada1
URL=http://mirror.yandex.ru/freebsd/releases/amd64/9.3-RELEASE

if [ -z ${PASSWD} ]; then
cat << EOF
 use:
 	'./freebsd-hetzner-install.sh hostname password
 	where 
 	hostname - hostname for this server
 	password - root password
EOF
	exit
fi

echo Erasing all hard disks data...
 gpart destroy -F /dev/${HD1}
 dd if=/dev/zero of=/dev/${HD1} count=1 bs=1024

 gpart destroy -F /dev/${HD2}
 dd if=/dev/zero of=/dev/${HD2} count=1 bs=1024

echo Creating disk mirror...
 gpart create -s gpt ${HD1}
 gpart add -t freebsd-boot -s 128k ${HD1}
 gpart bootcode -b /boot/pmbr -p /boot/gptboot -i 1 ${HD1}
 gpart add -t freebsd-swap -l swap${HD1} -s 16G ${HD1}
 gpart add -t freebsd-ufs -l rootfs${HD1} ${HD1}

 gpart create -s gpt ${HD2}
 gpart add -t freebsd-boot -s 128k ${HD2}
 gpart bootcode -b /boot/pmbr -p /boot/gptboot -i 1 ${HD2}
 gpart add -t freebsd-swap -l swap${HD2} -s 16G ${HD2}
 gpart add -t freebsd-ufs -l rootfs${HD2} ${HD2}

 gmirror load
 gmirror label -v rootfs /dev/gpt/rootfs${HD1} /dev/gpt/rootfs${HD2}
 gmirror label -v swap /dev/gpt/swap${HD1} /dev/gpt/swap${HD2}

 newfs -U /dev/mirror/rootfs

echo Mounting root filesystem...
 mount /dev/mirror/rootfs /mnt

echo Downloading freebsd base kernel lib32...

 cd /mnt

 fetch ${URL}/base.txz
 fetch ${URL}/kernel.txz
 fetch ${URL}/lib32.txz

echo Extracting data from base kernel lib32...
 tar xpf base.txz
 tar xpf kernel.txz
 tar xpf lib32.txz

 rm base.txz kernel.txz lib32.txz

echo Changing system settings...
 cat > /mnt/boot/loader.conf << EOF
geom_mirror_load="YES"
ahci_load="YES"
EOF

 cat > /mnt/etc/fstab << EOF
#Device			Mountpoint	FStype	Options	Dump	Pass#
/dev/mirror/swap	none		swap	sw	0	0
/dev/mirror/rootfs	/		ufs	rw	1	1
EOF

GW=`route -n get default | grep gateway | awk '{ print $2 }'`
INT=`route -n get default | grep interface | awk '{ print $2 }'`
IP=`netstat -rn | grep -w UHS | grep -v '::'  | awk '{ print $1 }'`
MASK=`netstat -rn | grep -w U | grep -v '::' | awk '{ print $1 }' | awk -F\/ '{ print $2 }'`

 cat > /mnt/etc/rc.conf << EOF
defaultrouter="${GW}"
hostname="${HOSTNAME}"
ifconfig_${INT}="inet ${IP}/${MASK}"
background_fsck="NO"
fsck_y_enable="YES"
sshd_enable="YES"
ntpdate_enable="YES"
ntpd_enable="YES"
EOF

 cat > /mnt/etc/resolv.conf << EOF
nameserver 213.133.98.98
nameserver 213.133.99.99
nameserver 213.133.100.100
EOF

echo ${PASSWD} | pw -V /mnt/etc/ usermod root -h 0
sed -i -e 's/^#PermitRootLogin.*$/PermitRootLogin yes/g' /mnt/etc/ssh/sshd_config

echo Installation process is done. Reboot system now...
