#!/usr/bin/env bash

#*******************************************************************************
#
# Bare Conductive Pi Cap example installer
# ----------------------------------------
#
# install-picap-examples - copies the Pi Cap examples into the current folder
#
# Written by Stefan Dzisiewski-Smith and Szymon Kaliski.
#
# This work is licensed under a MIT license https://opensource.org/licenses/MIT
#
# Copyright (c) 2016, Bare Conductive
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
#*******************************************************************************

# halt on any error
set -e

if [ "$EUID" -eq 0 ]; then
  echo -e "This utility should not be be run as root."
  exit 1
fi

USER="$(whoami)"

EXAMPLES_PATH="/usr/share/doc/picap/examples/."
DESTINATION_PATH="$(pwd)/PiCapExamples"
PROCESSING_EXAMPLES="/home/$USER/sketchbook"
DESKTOP_SYMLINK="/home/$USER/Desktop/PiCapExamples"

if [ "$#" -eq 1 ]; then
  DESTINATION_PATH="$1"
fi

# copy all examples from Deb installer location to $DESTINATION_PATH
mkdir -p "$DESTINATION_PATH"
sudo cp -R "$EXAMPLES_PATH" "$DESTINATION_PATH" > /dev/null

# transfer ownership of files to current user (us!)
sudo chown -R "$USER" "$DESTINATION_PATH"
sudo chmod -R +w "$DESTINATION_PATH"

# symlink processing examples to sketchbook only if processing is installed
if hash processing > /dev/null 2>&1; then
  mkdir -p "$PROCESSING_EXAMPLES" > /dev/null

  if [ -e "$PROCESSING_EXAMPLES/PiCap" ]; then
    rm "$PROCESSING_EXAMPLES/PiCap" > /dev/null
  fi

  ln -s "$DESTINATION_PATH/Processing" "$PROCESSING_EXAMPLES/PiCap"
fi

# symlink examples on desktop
if [ -e "$DESKTOP_SYMLINK" ]; then
  rm "$DESKTOP_SYMLINK" > /dev/null
fi

mkdir -p "/home/$USER/Desktop/" > /dev/null
ln -s "$DESTINATION_PATH" "$DESKTOP_SYMLINK"

exit 0
