#!/bin/bash

echo '******************************************************'
echo 'Installing Fleet DM'
echo '******************************************************'

wget -q https://github.com/fleetdm/fleet/releases/download/fleet-v4.72.1/fleet_v4.72.1_linux.tar.gz -O fleet.tgz
wget -q https://github.com/fleetdm/fleet/releases/download/fleet-v4.72.1/fleetctl_v4.72.1_linux_amd64.tar.gz -O fleetctl.tgz
tar zxvf fleet.tgz
tar zxvf fleetctl.tgz
sudo cp fleet_v4.72.1_linux/fleet /usr/bin/fleet
sudo cp fleetctl_v4.72.1_linux_amd64/fleetctl /usr/bin/fleetctl

echo '******************************************************'
echo 'Fleet install complete'
echo '******************************************************'

echo '******************************************************'
echo 'Setup Fleet DB'
echo '******************************************************'

echo "CREATE DATABASE fleetdm;" | mysql -u root -pmysqlrootpwd
/usr/bin/fleet prepare db --mysql_address=127.0.0.1:3306  --mysql_database=fleetdm --mysql_username=root --mysql_password=mysqlrootpwd

echo 'select * from enroll_secrets;' | mysql -u root -pmysqlrootpwd -D fleetdm
echo 'update enroll_secrets set secret="gKeUPHrzmiJshv8RThlFTA5tD8lOiblr";' | mysql -u root -pmysqlrootpwd -D fleetdm
echo 'select * from enroll_secrets;' | mysql -u root -pmysqlrootpwd -D fleetdm

echo '******************************************************'
echo 'Fleet DB complete'
echo '******************************************************'

echo '******************************************************'
echo 'Installing Fleet Service'
echo '******************************************************'

sudo sed -i "s/^supervised.*$/supervised systemd/" /etc/redis/redis.conf
sudo systemctl enable redis-server
sudo systemctl restart redis-server

sudo cp ../files/fleet.key /etc
sudo cp ../files/fleet.cert /etc

echo Installed Fleet Cert:
openssl x509 -in /etc/fleet.cert -noout -text | grep -i subject:

sudo cp ../files/fleet.service /etc/systemd/system
sudo systemctl daemon-reload
sudo systemctl start fleet.service
sudo systemctl enable fleet.service

fleetctl config set --address https://localhost:8443 --tls-skip-verify

echo "Systemctl status for fleet:"
systemctl --no-pager status fleet.service
echo "Netstat output:"
sudo netstat -antp | grep LISTEN

fleetctl setup --name student --email student@lab.internal --password student1234! \
  --org-name LAB
echo 'update enroll_secrets set secret="gKeUPHrzmiJshv8RThlFTA5tD8lOiblr";' \
  | mysql -u root -pmysqlrootpwd -D fleetdm
echo gKeUPHrzmiJshv8RThlFTA5tD8lOiblr > /home/student/fleetsecret
cat /home/student/fleetsecret

echo '******************************************************'
echo 'Fleet Service Installed'
echo '******************************************************'
