#!/bin/bash

"${DIRECTORY}/manage" install-if-not-installed Box64 || error "Box64 failed to install somehow!"

sudo rm -rf /usr/local/bin/eagle ~/.local/share/applications/eagle.desktop &>/dev/null

status -n "Downloading Eagle 9.6.2... "
wget https://trial2.autodesk.com/NET17SWDLD/2017/EGLPRM/ESD/Autodesk_EAGLE_9.6.2_English_Linux_64bit.tar.gz -O /tmp/eagle.tar.gz || error "Failed to download Eagle!"

status -n "Extracting..."
sudo rm -rf /opt/eagle-9.6.2
sudo mkdir -p /opt/eagle-9.6.2
sudo tar -xvzf /tmp/eagle.tar.gz -C /opt || error "Failed to extract Eagle!"
sudo chmod 755 -R /opt/eagle-9.6.2
rm -f /tmp/eagle.tar.gz
status_green Done

mkdir -p $HOME/eagle &>/dev/null

#make it runnable from a terminal
sudo ln -s /opt/eagle-9.6.2/eagle /usr/local/bin/eagle

status -n "Creating menu button... "
echo "#!/usr/bin/env xdg-open
[Desktop Entry]
Version=9.6.2
Type=Application
Terminal=false
Icon=/opt/eagle-9.6.2/bin/icons/Epf.svg
Name=Eagle
Exec=box64 eagle %f
Comment=Design Circuit Boards with Eagle CAD
MimeType=application/brd;
Categories=Development;Electronics;" | sudo tee /usr/share/applications/eagle.desktop >/dev/null
status_green "Done"

status -n "Creating .brd mimetype... "
echo '<?xml version="1.0" encoding="UTF-8"?>
<mime-info xmlns="http://www.freedesktop.org/standards/shared-mime-info">
   <mime-type type="application/brd">
     <comment>EagleCAD Project</comment>
     <glob pattern="*.brd"/>
     <generic-icon name="eagle"/>
   </mime-type>
</mime-info>' | sudo tee /usr/share/mime/packages/brd.xml >/dev/null
sudo update-mime-database /usr/share/mime

#File icon
sudo cp /opt/eagle-9.6.2/bin/eagle-logo.png /usr/share/icons/eagle.png
sudo update-icon-caches /usr/share/icons/*

status_green Done

if ! grep -qF 'eagle.desktop' ~/.config/mimeapps.list ;then
  status -n "Associating the .brd mimetype with Eagle... "
  echo "[Added Associations]
application/brd=eagle.desktop;" >> ~/.config/mimeapps.list
  status_green Done
fi
