#!/bin/sh

## Install xbase bacause it's a dependency for jre
## edit default partition layout 2Gb home and rest /var/unifi

echo 'https://ftp.eu.openbsd.org/pub/OpenBSD' > /etc/installurl
/usr/sbin/syspatch

echo "0 0 * * *       /usr/sbin/syspatch >/dev/null 2>/dev/null" >/tmp/crontab
crontab /tmp/crontab

echo '
ntpd_flags=
sndiod_flags=NO
inetd_flags=NO
smtpd_flags=NO
' > /etc/rc.conf.local

cat <<EOF | uudecode -m -p >> /etc/motd2
begin-base64 644 motd
[payload removed: 932 characters in 13 lines]
====
EOF

echo 'cp -f /etc/motd2 /etc/motd' >> /etc/rc.local

echo 'UniFi' > /etc/myname

groupadd -g 555 _unifi
useradd -g 555 -u 555 -d /var/unifi -L daemon -c 'Unifi daemon' -s /bin/ksh _unifi

export PKG_PATH=http://ftp.eu.openbsd.org/pub/OpenBSD/`uname -r`/packages/`uname -m`/
pkg_add jre libexecinfo mongodb unzip

chown -R _unifi:_unifi /var/unifi

su - _unifi
chmod 0700 /var/unifi
echo "export PATH=$PATH:/var/unifi/mongo/bin:/usr/local/jre-1.8.0/bin" >> .profile

exit

cat <<EOF >>/etc/rc.local
if [ -e /var/unifi/UniFi/lib/ace.jar ]; then
        su - _unifi -c "cd /var/unifi/UniFi && nohup /usr/local/jre-1.8.0/bin/java -jar lib/ace.jar start &"
fi
EOF

cd /etc/                                                                                                                                                               
ln -s CJG malloc.conf

perl -p -i -e 's/rw/rw,noatime,softdep/g' /etc/fstab

#Begin to install things as the dedicated user
su - _unifi

#Protect the directory
chmod 0700 /var/unifi

#The Unifi package has to be downloaded (please read the EULA)
ftp http://dl.ubnt.com/unifi/5.5.19/UniFi.unix.zip

unzip UniFi.unix.zip
rm -f UniFi/bin/mongod && ln -s /usr/local/bin/mongod UniFi/bin/mongod
ftp https://arnor.org/files/unifi/snappy-java-1.0.5.jar
mv snappy-java-1.0.5.jar UniFi/lib/snappy*

find /var/unifi/ | xargs chmod o-rwx  
find /var/unifi/ | xargs chmod g-rwx

chown -R _unifi:_unifi /var/unifi

rm /var/unifi/UniFi.unix.zip

exit

echo 'securelevel=2' > /etc/rc.securelevel

