#!/bin/bash

if [[ $USER = "root" ]]; then
    echo "You should run this script as user, not as root."
    exit 1
fi

# app files
INSTALL_FOLDER="/opt/ikeybase/"

if [ -d "$INSTALL_FOLDER" ]; then
    sudo rm -r "$INSTALL_FOLDER"
fi

sudo mkdir -p "$INSTALL_FOLDER"
sudo cp -a ./lib "$INSTALL_FOLDER"
sudo cp -a ./libexec "$INSTALL_FOLDER"
sudo cp -a ./translations "$INSTALL_FOLDER"
sudo cp -a ./plugins "$INSTALL_FOLDER"
sudo cp -a ./resources "$INSTALL_FOLDER"
sudo cp iKeyBase "$INSTALL_FOLDER"
sudo cp README.txt "$INSTALL_FOLDER"
sudo cp README.ru.txt "$INSTALL_FOLDER"
sudo cp qt.conf "$INSTALL_FOLDER"
sudo cp ikeybase.png /usr/share/icons/hicolor/128x128/apps/
sudo cp ikeybase.desktop /usr/share/applications/
sudo chmod +x /usr/share/applications/ikeybase.desktop
sudo update-desktop-database

# add a link to the desktop
cp ikeybase.desktop "`xdg-user-dir DESKTOP`"

# rules for usb-based devices
sudo cp 99-hid.rules /etc/udev/rules.d
sudo cp 93-pn53x.rules /lib/udev/rules.d

# permissions for devices
sudo adduser $USER dialout
sudo adduser $USER tty
sudo adduser $USER uucp

# this is used to avoid conflicts between the driver and one of the default kernel modules.
sudo cp blacklist-libnfc.conf /etc/modprobe.d

# removing sound delay
# https://askubuntu.com/questions/218444/sound-output-starts-delayed
sudo sed -i.bak '/^load-module module-suspend-on-idle/s/^\(.*\)$/#\1\n/' /etc/pulse/default.pa
sudo sed -i.bak '/^load-module module-suspend-on-idle/s/^\(.*\)$/#\1\n/' /etc/pulse/system.pa
pulseaudio -k

echo "To work with ACR122 you should install pcscd and start it:"
echo "$ sudo apt install pcscd"
echo "$ sudo systemctl start pcscd"
echo "You may need to reboot the computer"

echo "You should install 'xcb-xinerama' if application doesn't start."
echo "On Debian-based distros you should run: sudo apt-get install libxcb-xinerama0"
echo ""
echo "Check README.txt for details."
