#!/bin/bash
#
# Development builder
#
install_file="install.sh"
cat > ./$install_file << EOF
#!/bin/bash

program_name="raspscreen"
runtime_id=\$(id -u)
userland_name="\${1-systemec}"

# Check if the user is right (root) for the program
if [[ "\$runtime_id" -ne 0 ]]; then
    echo "Not running as root, please run as root."
    exit 1
fi
apt-get -y install \\
    default-jre libreoffice-impress libreoffice-java-common psmisc ssh vlc

systemctl enable --now ssh

# Create the systemd userland folder
if [[ ! -d /home/\${userland_name}/.config/systemd/user ]]; then
    mkdir -p /home/\${userland_name}/.config/systemd/user -m 755
fi

# Create the program place onto /opt
if [[ ! -d /opt/\${program_name} ]]; then
    mkdir -p /opt/\${program_name}/media/current -m 755
    mkdir -p /opt/\${program_name}/bin -m 755
fi

# THIS MUST BE THE SAME AS \$REPO/service-files/presentation.service
cat > /home/\${userland_name}/.config/systemd/user/presentation.service << EOF
EOF

# ABOVE AS WELL
# COMPILE presentation.service USERLAND SERVICE INTO INSTALL FILE!
#

cat ./service-files/presentation.service >> ./$install_file
echo -e "\nEOF\n" >> ./$install_file

#
# COMPILE video.service USERLAND SERVICE INTO INSTALL FILE!
#

cat >> ./$install_file << EOF
# THIS MUST BE THE SAME AS \$REPO/service-files/video.service
cat > /home/\${userland_name}/.config/systemd/user/video.service << EOF
EOF

cat ./service-files/video.service >> ./$install_file
echo -e "\nEOF\n" >> ./$install_file

#
# COMPILE disable-usb.service SYSTEM SERVICE INTO INSTALL FILE!
#

cat >> ./$install_file << EOF
# THIS MUST BE THE SAME AS \$REPO/service-files/disable-usb.service
cat > /etc/systemd/system/disable-usb.service << EOF
EOF

cat ./service-files/disable-usb.service >> ./$install_file
echo -e "\nEOF\n" >> ./$install_file

#
# COMPILE manage.sh SCRIPT INTO INSTALL FILE!
#

cat >> ./$install_file << EOF
# THIS MUST BE THE SAME AS \$REPO/bin/manage.sh
cat > /opt/raspscreen/bin/manage.sh << EOF
EOF

# Make sure to prefix all $ with a \
sed 's/\$/\\$/g' ./bin/manage.sh >> "$install_file"
echo -e "\nEOF\n" >> ./$install_file

#
# COMPILE disable-usb.sh SCRIPT INTO INSTALL FILE!
#

cat >> ./$install_file << EOF
# THIS MUST BE THE SAME AS \$REPO/bin/disable-usb.sh
cat > /opt/raspscreen/bin/disable-usb << EOF
EOF

sed 's/\$/\\$/g' ./bin/disable-usb.sh >> "$install_file"
echo -e "\nEOF\n" >> ./$install_file


cat >> ./$install_file << EOF
echo "alias userjournal='journalctl --user-unit'" /home/\${userland_name}/.bashrc

chmod +x /opt/raspscreen/bin/manage.sh
chown -Rv \${userland_name}:\${userland_name} /home/\${userland_name}/.config/systemd
chown -Rv \${userland_name}:\${userland_name} /opt/\${program_name}

su \${userland_name} -c "systemctl --user daemon-reload"

xmlstarlet ed -L -u "//prop[@oor:name='ShowTipOfTheDay']/value" -v "false" main.xcd

echo "Self-destruction NOW!"
rm \$(pwd)/\$0
EOF