#!/usr/bin/env bash

#*******************************************************************************
#
# Bare Conductive Pi Cap Audio Unmapper
# -------------------------------------
#
# unmap-audio-from-picap - returns audio mapping to default
#
# 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

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 in the config file, prepend it with "#"
sudo sed -i -e "s/^$CONFIG_DTOVERLAY_LINE/#$CONFIG_DTOVERLAY_LINE/g" "$CONFIG_FILE_PATH"

read -r -p $'PCM audio has been unmapped from 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

exit 0
