#!/bin/bash
# Copyright (C) 2009 - 2015 vortexbox.org
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#

echo "----------------------------------------"
echo "Apple Time Machine support for xo|one"
echo "----------------------------------------"
echo ""
echo "We will now set up your xo|one to act as an Apple Time Capsule."
echo "This will allow you to use it for Time Machine backups."
echo ""
echo "Time machine is designed to use all avalible space on your Time Capsule for backups."
echo ""
echo "How much space would you like to tell Time Machine to use on your xo|one?"
echo -n "Enter the total space in GB: "
read TIMESPACE
echo ""
echo "Configuring your xo|one as an Apple Time Capsule..."
echo ""

let TIMESPACE=$TIMESPACE*1000

/bin/systemctl stop netatalk.service

dnf clean all
dnf -y update
dnf -y install netatalk

if ! grep guest /etc/passwd >/dev/null 2>&1 
 then
	useradd guest
	(echo xo-one; sleep 2; echo xo-one) | passwd guest
fi

if ! grep guest /etc/ssh/sshd_config >/dev/null 2>&1
 then
	echo "DenyUsers guest" >> /etc/ssh/sshd_config 
fi

cat > /etc/netatalk/AppleVolumes.default <<'EOF'
/storage "Files" veto:/lost+found/
/storage/music "Music" veto:/lost+found/ options:ro
EOF

echo "/storage/TimeMachine TimeMachine options:usedots,upriv,tm,volsizelimit:$TIMESPACE" >> /etc/netatalk/AppleVolumes.default
	
echo '- -tcp -noddp -uamlist uams_guest.so -nosavepassword -guestname "guest" -mimicmodel TimeMachine' > /etc/netatalk/afpd.conf

mkdir -p /storage/TimeMachine 
chmod -R 777 /storage
chown -R guest:guest /storage/TimeMachine

cd /storage
find . -name .AppleDouble  -type d -print0 | xargs -0 rm -rf
find . -name .AppleDesktop  -type d -print0 | xargs -0 rm -rf
find . -name .AppleDB  -type d -print0 | xargs -0 rm -rf
find . -name "Temporary Items"  -type d -print0 | xargs -0 rm -rf
find . -name "Network Trash Folder"  -type d -print0 | xargs -0 rm -rf
find . -name .DS_Store  -type f -print0 | xargs -0 rm -rf

if [ -f /etc/avahi/services/afpd.service ]; then
	rm /etc/avahi/services/afpd.service
fi

/bin/systemctl enable netatalk.service
/bin/systemctl start netatalk.service

echo ""
echo "Done."
echo ""