#!/usr/bin/env bash

#*******************************************************************************
#
# Bare Conductive Pi Cap Audio Mapper
# -----------------------------------
#
# map-audio-to-picap - outputs audio via the Pi Cap audio socket
#
# Written by Stefan Dzisiewski-Smith.
#
# 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

CONFIG_DTOVERLAY_COMMENT="# remap audio to Pi Cap socket"
CONFIG_DTOVERLAY_LINE="dtoverlay=pwm-2chan,pin=12,pin2=13,func=4,func2=4"
CONFIG_FILE_PATH="/boot/config.txt"

THIS_SCRIPT_NAME=$(basename "$0")

if [ "$EUID" -ne 0 ]; then
  echo -e "This utility needs to be run as root to work. Try running: \n  sudo $THIS_SCRIPT_NAME"
  exit 1
fi

# if the config line already exists (but prepended with "#") in /boot/config.txt, remove the "#"
sudo sed -i -e "s/#$CONFIG_DTOVERLAY_LINE/$CONFIG_DTOVERLAY_LINE/g" "$CONFIG_FILE_PATH"

# if we still can't find the config line (probably because we didn't find it first time around) append two newlines, a comment, the config lines and another newline (phew!)
sudo sed -i -e "\|$CONFIG_DTOVERLAY_LINE|h; \${x;s|$CONFIG_DTOVERLAY_LINE||;{g;t};a\\" -i -e "\n\n$CONFIG_DTOVERLAY_COMMENT\n$CONFIG_DTOVERLAY_LINE" -i -e "}" "$CONFIG_FILE_PATH"

if [ -z "$DONT_REBOOT" ]; then
  read -r -p $'PCM audio has been mapped to the Pi Cap headphone socket. \nFor this change to take effect, we need to reboot.\n\nDo you want to do this now? [y/n]\n'
  case $REPLY in
    [yY][eE][sS]|[yY])
      sync
      sudo reboot now
      ;;
    *)
      ;;
  esac
fi

exit 0
