#!/usr/bin/env bash

#*******************************************************************************
#
# Bare Conductive Pi Cap Debian Package
# -------------------------------------
#
# picap-setup.sh - configures all aspects of Pi Cap installation
#                  can be re-run after install to clean up / reset
#
# Written by Szymon Kaliski.
#
# This work is licensed under a Creative Commons Attribution-ShareAlike 3.0
# Unported License (CC BY-SA 3.0) http://creativecommons.org/licenses/by-sa/3.0/
#
# 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.
#
#*******************************************************************************

# let's halt on any error

set -e

# can't be run as root

if [ "$EUID" -eq 0 ]; then
  echo -e "This utility needs to be run as user to work."
  exit 1
fi

# consts

PI_VERSION=$(printf "from RPi import GPIO\nprint GPIO.RPI_INFO['TYPE']" | python)

# ugly global variable

TELL_TO_REBOOT="no"

# helpers

function ask_user_question {
  echo -n "$(tput setaf 6)$1 $(tput sgr0)[y/n] "
  read -r -e
  echo
}

# functions

function hardware_setup {
  echo "$(tput setaf 3)Pi Cap Setup Script$(tput sgr0)"
  echo
  echo "$(tput setaf 3)We're setting up hardware, so you may be asked for a sudo password.$(tput sgr0)"
  echo

  CONFIG="/boot/config.txt"
  BLACKLIST="/etc/modprobe.d/raspi-blacklist.conf"
  TARGET_SETTING="on"

  CURRENT_SETTING="off" # assume disabled
  if [ -e "$CONFIG" ] && grep -q -E "^(device_tree_param|dtparam)=([^,]*,)*i2c(_arm)?(=(on|true|yes|1))?(,.*)?$" $CONFIG; then
    CURRENT_SETTING="on"
  fi

  TARGET_SETTING="on"
  if [ "$TARGET_SETTING" != "$CURRENT_SETTING" ]; then
    TELL_TO_REBOOT="yes"
  fi

  sudo sed "$CONFIG" -i -r -e "s/^((device_tree_param|dtparam)=([^,]*,)*i2c(_arm)?)(=[^,]*)?/\1=$TARGET_SETTING/"

  if ! grep -q -E "^(device_tree_param|dtparam)=([^,]*,)*i2c(_arm)?=[^,]*" "$CONFIG"; then
    (printf "dtparam=i2c_arm=%s\n" "$TARGET_SETTING" | sudo tee -a "$CONFIG") > /dev/null 2>&1
  fi

  if ! [ -e "$BLACKLIST" ]; then
    sudo touch "$BLACKLIST"
  fi

  sudo sed "$BLACKLIST" -i -e "s/^\(blacklist[[:space:]]*i2c[-_]bcm2708\)/#\1/"
  sudo sed /etc/modules -i -e "s/^#[[:space:]]*\(i2c[-_]dev\)/\1/"

  if ! grep -q "^i2c[-_]dev" /etc/modules; then
    (printf "i2c-dev\n" | sudo tee -a /etc/modules) > /dev/null 2>&1
  fi

  sudo modprobe i2c-bcm2708
  sudo modprobe i2c-dev
}

function cp_examples {
  EXAMPLES_PATH="$HOME/PiCapExamples"

  ask_user_question "Would you like to copy example code into $EXAMPLES_PATH?"

  if [[ "$REPLY" =~ ^[Yy]$ ]]; then
    install-picap-examples "$EXAMPLES_PATH"

    echo "Sample code copied to $EXAMPLES_PATH!"
  else
    echo "You can always copy them later using install-picap-examples command."
  fi

  echo
}

function setup_hq_audio {
  ask_user_question "It's recomended to setup high-quality audio, do you want to do it now?"

  if [[ "$REPLY" =~ ^[Yy]$ ]]; then
    CONFIG_PWM_COMMENT="# set high-quality PWM audio"
    CONFIG_PWM_LINE="audio_pwm_mode=2"
    CONFIG_FILE_PATH="/boot/config.txt"

    sudo sed -i -e "s/#$CONFIG_PWM_LINE/$CONFIG_PWM_LINE/g" "$CONFIG_FILE_PATH"
    sudo sed -i -e "\|$CONFIG_PWM_LINE|h; \${x;s|$CONFIG_PWM_LINE||;{g;t};a\\" -i -e "\n$CONFIG_PWM_COMMENT\n$CONFIG_PWM_LINE" -i -e "}" "$CONFIG_FILE_PATH"

    amixer cset numid=3 1 > /dev/null
    amixer sset PCM,0 90% > /dev/null

    TELL_TO_REBOOT="yes"

    echo "High Quality audio enabled!"
    echo
  fi
}

function pi_zero_audio {
  if [[ "$PI_VERSION" =~ "Zero" ]]; then
    echo "$(tput setaf 3)Running on RPI Zero, mapping audio to Pi Cap for you...$(tput sgr0)"

    sudo DONT_REBOOT=1 map-audio-to-picap
    TELL_TO_REBOOT="yes"

    echo
  fi
}

# run main code

hardware_setup
setup_hq_audio
pi_zero_audio
cp_examples

# note about picap-intro

echo "Run $(tput setaf 3)picap-intro$(tput sgr 0) for a feature tour!"
echo

# reboot if needed

if [ "$TELL_TO_REBOOT" == "yes" ]; then
  echo "Important system-level things changed."
  echo "You'll need to reboot before this takes effect."

  ask_user_question "Would you like to do this now?"

  if [[ "$REPLY" =~ ^[Yy]$ ]]; then
    echo "$(tput setaf 1)Rebooting...$(tput sgr 0)"
    sudo reboot
  else
    echo "Run $(tput setaf 3)sudo reboot$(tput sgr 0) to restart."
    echo
  fi
fi

exit 0
