#!/bin/bash

cd ${0%/*}

echo
echo "Copyright Pointsharp AB"
echo

if [ "$(id -u)" != "0" ]; then
    echo "ERROR - Installation requires root access"
    exit
fi

echo "Install begin"

APP_PATH=/usr/bin/netid-access
if [ -d "$APP_PATH" ]; then
    echo "  Delete existing application"
    rm -rf "$APP_PATH"
fi

if [[ $(dpkg -s pcscd | grep "Status: ") == *installed* ]]; then
    echo "  PC/SC Smart Card Daemon already installed"
else
    echo $'\n'
    echo "  PC/SC Smart Card Daemon is missing and is required for Smart Card support."
    echo "  Install PC/SC Smart Card Daemon now? [Y/n]"
    read -t60 -n1 a
    echo $'\n'
    if [[ $a == "Y" || $a == "y" || $a = "" ]]; then
        sudo apt-get install pcscd
    fi
    echo $'\n'
fi

echo "  Copy application"
APP_ROOT=${APP_PATH%/*}
if [ ! -d "$APP_ROOT" ]; then
    mkdir "$APP_ROOT"
fi
mkdir "$APP_PATH"
mkdir "$APP_PATH/gui"
cp libnetid.so "$APP_PATH"
if [ -f libnetidgui.so ]; then
    cp libnetidgui.so "$APP_PATH"
fi    
cp netid "$APP_PATH"
cp netidapp "$APP_PATH"
cp logo.ico "$APP_PATH"
if [ -f netid.conf ]; then
    cp netid.conf "$APP_PATH"
fi    
if [ -f uninstall ]; then
    cp uninstall "$APP_PATH"
fi
if [ -f postsetup ]; then
    cp postsetup "$APP_PATH"
fi
unzip -q web.zip -d "$APP_PATH/gui"

echo "  Update execute mode"
chmod 755 "$APP_PATH/libnetid.so"
if [ -f libnetidgui.so ]; then
    chmod 755 "$APP_PATH/libnetidgui.so"
fi    
chmod 755 "$APP_PATH/netid"
chmod 755 "$APP_PATH/netidapp"
chmod 644 "$APP_PATH/logo.ico"
if [ -f netid.conf ]; then
    chmod 644 "$APP_PATH/netid.conf"
fi

echo "  Create desktop link"
read TMP < version
VERSION=${TMP%% *}
rm -f /tmp/netidaccess.desktop
cat << _EOF_ > /tmp/netidaccess.desktop
[Desktop Entry]
Version=1.1
Type=Application
Name=Net iD Access
Comment=Net iD Access $VERSION
Terminal=false
Exec=$APP_PATH/netidapp -root $APP_PATH %u
Path=$APP_PATH
Icon=$APP_PATH/logo.ico
Categories=System;Security
MimeType=x-scheme-handler/netid
_EOF_
USER_NAME=${HOME##*/}
cp -f /tmp/netidaccess.desktop /usr/share/applications/
rm -f /tmp/netidaccess.desktop
echo "  Update desktop database"
update-desktop-database
echo "  Create startup script"
read TMP < version
VERSION=${TMP%% *}
rm -f /tmp/netidaccess.sh
cat << _EOF_ > /tmp/netidaccess.sh
#!/bin/bash
URL=\$1
pkill netidapp
$APP_PATH/netidapp -root $APP_PATH \$URL
_EOF_
USER_NAME=${HOME##*/}
cp -f /tmp/netidaccess.sh $APP_PATH
rm -f /tmp/netidaccess.sh
chmod 755 "$APP_PATH/netidaccess.sh"

echo "  Execute post install actions"
if [ -f postsetup ]; then
    sudo -u $USER_NAME ${0%/*}/postsetup install
fi

echo "Install end"

echo ""
echo "================================================================================"
echo ""
echo "Installation completed"
echo ""
echo "Start Net iD Access from Dash"
echo ""
echo "================================================================================"
echo ""