#!/bin/bash

DIRECTORY="$(dirname "$(dirname "$( cd "$(dirname "$0")" >/dev/null 2>&1 ; pwd -P )")")"

function error {
  echo -e "\\e[91m$1\\e[39m"
  exit 1
}

#use the error function often!
#If a certain command is necessary for installation to continue, then add this to the end of it:
# || error 'reason'
#example below:

# Get dependencies
"${DIRECTORY}/pkg-install" "zenity python3-pip yad" "$(dirname "$0")" || exit 1
sudo pip3 install imapclient || error "Failed to install imapclient!"

output="$(yad --form --center --width=400 --separator='\n' \
  --title="Email Checker Settings" --window-icon="$(dirname "$0")/icon-64.png" \
  --field='IMAP Server:' 'Outlook: outlook.office365.com  Gmail: imap.gmail.com' \
  --field='Email:' 'user@example.com' \
  --field='Password::H' '' \
  --field='Folder:' 'Inbox' \
  --field='Check interval::NUM' '60!10..240!10' \
  --button=OK!${DIRECTORY}/icons/check.png:0)"
button=$?
[ $button -ne 0 ]&&error "User exited."

echo "Output: ${output}EOO"

if [ -d ~/raspi-email-checker ];then
  gio trash ~/raspi-email-checker
  echo -e "\\e[33mWARNING: Moved the raspi-email-checker folder to trash instead of deleting.
The checkmail.py script inside may contain a password!\\e[39m"
fi

git clone https://github.com/Botspot/raspi-email-checker || error 'Failed to clone repository!'

#hostname
sed -i "s/hostname2replace/$(echo "$output" | sed "1q;d")/g" ~/raspi-email-checker/checkmail.py

#email
sed -i "s/email2replace/$(echo "$output" | sed "2q;d")/g" ~/raspi-email-checker/checkmail.py

#password
sed -i "s/password2replace/$(echo "$output" | sed "3q;d")/g" ~/raspi-email-checker/checkmail.py

#mailbox
sed -i "s/mailbox2replace/$(echo "$output" | sed "4q;d")/g" ~/raspi-email-checker/checkmail.py

#checkinterval
sed -i "s/checkinterval2replace/$(echo "$output" | sed "5q;d")/g" ~/raspi-email-checker/checkmail.py

#run on boot
mkdir -p ~/.config/autostart
echo "[Desktop Entry]
Name=Email Checker
Comment=Displays a pop-up window if your $(echo "$output" | sed "4q;d") folder contains any unread emails.
Exec=sudo python ${HOME}/raspi-email-checker/checkmail.py
X-GNOME-Autostart-enabled=true
Hidden=false
Icon=$(dirname "$0")/icon-64.png
NoDisplay=false" > ~/.config/autostart/checkmail.desktop

"${DIRECTORY}/etc/terminal-run" "echo -e 'If checkmail.py throws errors, you may have entered invalid information.\nUse this opportunity to test it out.\nFrom now on, checkmail.py will be run on every boot.' ; sudo python ${HOME}/raspi-email-checker/checkmail.py ; sleep infinity" 'Running Email Checker (checkmail.py)' &
