#!/bin/bash -e
#
# Configuration script for gom, user or systemwide.
#
#
# (c) 1998 Stephan Alexander Suerken <absurd@debian.org>
#

#
# Variables
#
gom_test_options_log=/tmp/gom_test_options.log.$$
gom_test_settings_log=/tmp/gom_test_settings.log.$$

if test `whoami` == root;
    then gomconfig_dir=/etc/gom ;
    else gomconfig_dir=${HOME}/.gom ;
fi
gomrc_file=${gomconfig_dir}/gomrc
default_settings_file=${gomconfig_dir}/default

#
# Continue Break
#
gomconfig_break ()
{
    echo -n "Hit RETURN to continue..."; read
}

#
# Test Prototype: $1:gom_options, $2:logfile, $3:logchoice
#
test_status ()
{
    if gom $1 >$2 2>&1 ;
	then echo -n "Fine.      Use '$3' for the log."
             return 0
	else echo -n "Problem.   Error(s) found - use '$3' for the log."
	     return 1
    fi
}

#
# Intro
#
intro ()
{
    echo
    echo "==========================================================================="
    echo "                   Configuring gom for user `whoami`.";
    # Warning for root
    if test `whoami` == root ;
	then echo "                ** Changing SYSTEM configuration **";
    fi
    echo "==========================================================================="
    echo " This configuration script assumes a correctly installed and configured"
    echo "sound driver. If you are using this as part of package configuration"
    echo "(especially when installing from scratch with a default kernel), you"
    echo "possibly need to fix the sound driver first, and rerun this script"
    echo "($0) later."
    echo
}

#
# Audio Users
#

# a recursive helper
add_audio_users ()
{
    if test -e /etc/debian_version;
	then echo
	     echo "'<user> [RETURN]': Add user to group audio."
	     echo "'[RETURN]'       : Quit adding users."
	     echo
	     echo -n "Add user: "
	     read user
	     if test ! "${user}" == "" ;
		then adduser ${user} audio ;
		     add_audio_users ;
	     fi
	else echo "This is not Debian GNU/Linux."
             echo "I don't know the recommended way to give users audio access on this system."
             echo "You need to figure this out by yourself."
    fi
}

# yet another (not yet recursive) helper
del_audio_users ()
{
    if test -e /etc/debian_version;
	then echo
	     echo "Sorry -- I don't yet know a reasonable and recommended"
	     echo "way to delete a user from a certain group in Debian GNU/Linux."
             echo "Please edit /etc/group manually."
             echo
	else echo
	     echo "This is not Debian GNU/Linux."
             echo "I don't know the recommended way to deny users audio access on this system."
             echo "You need to figure this out by yourself."
	     echo
    fi
}

audio_users_status ()
{
    # Test for Debian
    if test ! -e /etc/debian_version;
	then echo -n "Unknown.  This is not Debian GNU/Linux.";
	else if test `whoami` == root ;
		then if grep --quiet "^audio:.*:.*:$" /etc/group ;
			then echo -n "Problem.   No user in group audio."
			else echo -n "Fine.      At least one user in group audio."
                     fi
		else if grep --quiet "^audio.*`whoami`" /etc/group ;
			then echo -n "Fine.      `whoami` is audio user."
			else echo -n "Problem.   `whoami` is _not_ audio user."
		     fi
	     fi
    fi
}

audio_users ()
{
    echo
    echo "Audio users"
    echo "============"
    echo " Adding a user to the group 'audio' is the recommended way (at least"
    echo "in Debian GNU/Linux) to grant a user to 'do sound', including"
    echo "controlling the soundcard mixer(s) with gom."
    echo
    echo    "[RETURN] : Cancel  (don't touch current settings)."
    echo    "0        : Add     (add user(s) to group audio)."
    echo    "1        : Delete  (delete user(s) from group audio)."
    echo
    echo -n "Current status: "; audio_users_status; echo
    echo -n "Current value : "; grep audio /etc/group || true
    echo 
    if test `whoami` == root ;
       then echo -n "Your choice: "
	    read choice
	    if test "${choice}" == "0" ;
		then add_audio_users
	    elif test "${choice}" == "1"
		then del_audio_users
		else echo
                     echo "Not touching anything...done."
		     echo
	    fi
       else echo "These system settings can only be changed by root."
	    echo
    fi
    gomconfig_break
}

#
# Startup Options
#
startup_options_status ()
{
    if test -e ${gomrc_file} ;
	then echo -n "Installed."
	else if test -e /etc/gom/gomrc ;
                 then echo -n "Purged.    Using system options."
		 else echo -n "Purged.    "
                      if test `whoami` != root ;
			  then echo -n "No system options available!"
		      fi
             fi
    fi
}

startup_options ()
{
    options_stubborn_default="-d/dev/mixer"
    echo
    echo "Startup options"
    echo "================"
    echo " These options are stored in the file '${gomrc_file}'; they"
    echo "will be loaded on every startup of gom."
    if test `whoami` == root ;
       then echo " These system options only have effect if there are no own"
            echo "user options."
       else echo " These user options make the system startup options"
            echo "ineffective."
    fi
    echo " I recommend to only supply one default mixer device (most likely"
    echo "'-d/dev/mixer'); however, you can use all gom one-character"
    echo "options just like on the command line here (but there must not"
    echo "be spaces between an option and its argument!)."
    echo " If you don't have any default options (with at least the mixer"
    echo "device given), you'll need to always explicitly name a mixer as"
    echo "option to gom."
    echo
    echo    "[RETURN] : Cancel  (don't touch anything)."
    echo    "0        : Default (use stubborn default '${options_stubborn_default}')."
    echo    "1        : Purge   (remove configuration file)."
    echo    "2        : Custom  (enter own configuration)."
    echo
    echo -n "Current status: "
    startup_options_status
    echo
    echo -n "Current value : "
    if test -e ${gomrc_file} ;
	then echo "'`cat ${gomrc_file}`'."
	else echo "NULL."
    fi
    echo 
    echo -n "Your choice: "
    read choice
    if test "${choice}" == "0" ;
	then echo -n "Writing default options to '${gomrc_file}'..."
             echo ${options_stubborn_default} >${gomrc_file}
    elif test "${choice}" == "1"
	then echo -n "Purging '${gomrc_file}'..."
	     rm -f ${gomrc_file} 
    elif test "${choice}" == "2"
	then echo -n "Enter custom options: "
	     read options_custom
             echo -n "Writing custom options to '${gomrc_file}'..."
 	     echo ${options_custom} >${gomrc_file}
	else echo
             echo -n "Not touching anything..."
    fi
    echo "done."
    echo
    gomconfig_break
}

#
# Default Settings
#
default_settings_status ()
{
    if test -e ${default_settings_file} ;
	then echo -n "Installed."
	else echo -n "Purged."
    fi
}

default_settings ()
{
    settings_stubborn_default='-M'
    echo
    echo "Default Settings"
    echo "================="
    echo " The file '${default_settings_file}' holds the default mixer"
    echo "settings (loaded with 'gom --get-settings')."
    if test `whoami` == root;
	then echo " These settings should preferably be loaded thusly"
	     echo "at some point of system bootup."
             echo " For the prepackaged version for Debian GNU/Linux, purging"
	     echo "(removing) this file implicitly means not to configure the"
	     echo "mixer at system bootup."
	else echo " These settings should preferably be loaded thusly"
	     echo "at some point of user login."
    fi
    echo
    echo    "[RETURN] : Cancel  (don't touch anything)."
    echo    "0        : Default (use stubborn default '${settings_stubborn_default}', muting all channels)."
    echo    "1        : Purge   (remove configuration file)."
    echo    "2        : Custom  (edit (existing) configuration using interactive gom)."
    echo
    echo -n "Current status: "; default_settings_status; echo
    echo -n "Current value : "
    if test -e ${default_settings_file} ;
	then echo "Sorry, can't display settings in reasonable form here."
	else echo "NULL."
    fi
    echo 
    echo -n "Your choice: "
    read choice
    if test "${choice}" == "0" ;
	then echo -n "Writing default settings to '${default_settings_file}'..."
             echo ${settings_stubborn_default} >${default_settings_file}
    elif test "${choice}" == "1"
	then echo -n "Purging '${default_settings_file}'..."
	     rm -f ${default_settings_file} 
    elif test "${choice}" == "2"
	then echo
	     echo "About to start gom (ncurses interface) to edit the default settings."
 	     echo "You only need to change settings, and then leave with 'q'."
	     echo
	     gomconfig_break
	     echo
	     gom --load-settings --interface=t --save-settings || true
	     echo
             echo -n "Editing default settings..."
	else echo
             echo -n "Not touching anything..."
    fi
    echo "done."
    echo
    gomconfig_break
}


test_anygomrc_file ()
{
    test -e ${gomrc_file} -o -e /etc/gom/gomrc
}

#
# Test Options Run
#
test_options_status ()
{
    if test_anygomrc_file ;
        then test_status "" "${gom_test_options_log}" "4"
	else echo -n "Need some option file first to test."
             return 1
    fi
}

#
# Test Default Load
#
test_settings_status ()
{
    if test_anygomrc_file
        then if test -e ${default_settings_file};
		 then test_status "--get-settings" "${gom_test_settings_log}" "5"
		 else echo -n "Need default settings file first to test."
                      return 1
	     fi
	else echo -n "Need some option file first to test."
             return 1
    fi
}

#
# Overall conf. status:
#
# 0: unconfigured
# 1: sufficiently configured
# 2: fully configured
#
unconfigured ()
{
    echo
    if test_options_status >/dev/null 2>&1 ;
	then if test_settings_status >/dev/null 2>&1 ;
		 then echo "Gom is fully configured for `whoami`."; return 2
		 else echo "Gom is sufficiently configured for `whoami`."; return 1
	     fi
	else echo "Gom is unconfigured for `whoami`."; return 0
    fi
}

#
# View err log
#
view_log ()
{
    echo
    echo "Showing log $1:"
    if test -s $1 ;
	then echo "--START LOG--"
             cat $1
	     echo "---END LOG---"
	else echo "Nothing logged!"
    fi
    gomconfig_break
}

#
# conf_dir_check
#
conf_dir_check ()
{
    if test -e ${gomconfig_dir} ;
	then if test ! -d ${gomconfig_dir} ;
		then echo
                     echo "Fatal error: configuration directory invalid."
		     echo "Because    : '${gomconfig_dir}' exists, but is not a directory."
		     echo "Please correct this manually, then rerun this script."
		     echo
		     exit 1 ;
	     fi
	else echo -n "Creating configuration directory '${gomconfig_dir}'..."
	     mkdir -ma=rx,u+w ${gomconfig_dir}
	     echo -n "done."
    fi
}

#
# gom_purge
#
gom_purge ()
{
    echo
    if test -e ${gomconfig_dir} ;
	then if test ! -d ${gomconfig_dir} ;
		then echo "Fatal error: configuration directory invalid (won't purge this)."
		     echo "Because    : '${gomconfig_dir}' exists, but is not a directory."
		     echo "Please correct this manually, then rerun this script."
		     exit 1 ;
		else echo -n "Making temporary backup..."
		     purge_backup_dir=/tmp/gomconfig_purge_backup.$$
		     cp -a ${gomconfig_dir} ${purge_backup_dir}
		     echo "done."
		     echo -n "Purging ${gomconfig_dir}..."
                     rm -rf ${gomconfig_dir}
		     echo "done."
		     echo
		     echo "If this was a mistake, you can manually retrieve the purged"
		     echo "configuration from '${purge_backup_dir}'."
	     fi
	else echo "Nothing to purge...done."
    fi
    echo
}

#
# Gom_Configure
#
gom_configure ()
{
    conf_dir_check

    selection='none'
    until test "${selection}" == "q" -o "${selection}" == "Q" ; do
	intro
	echo    "   1. Audio users     : `audio_users_status`"
	echo    "   2. Startup options : `startup_options_status`"
	echo    "      Testing stage 2 : `test_options_status`"
	echo    "   3. Default settings: `default_settings_status`"
	echo    "      Testing stage 3 : `test_settings_status`"
	echo
	echo    "  q,Q: Quit.  (It's save to simply quit if you are unsure.)"
	echo
	echo -n "  Quit or select number: "
	read selection
	if   test "${selection}" == "1"; then audio_users
	elif test "${selection}" == "2"; then startup_options
	elif test "${selection}" == "3"; then default_settings
	elif test "${selection}" == "4"; then view_log ${gom_test_options_log}
	elif test "${selection}" == "5"; then view_log ${gom_test_settings_log}
	fi;
    done
#
# Cleanup
#
    rm -f ${gom_test_options_log} ${gom_test_settings_log}
#
# Write Status
#
    unconfigured || true
}

###############
# Start code
#
if test "$1" == "--purge"
    then gom_purge
elif test "$1" == "--force"
    then gom_configure
elif test "$1" == "" && unconfigured
    then gom_configure
elif test "$1" == ""
    then echo
         echo "Use '$0 --force' to reconfigure."
    else echo
         echo "Usage: $0 [--force | --purge]"
	 echo "'--force' forces reconfiguration."
	 echo "'--purge' removes all configuration files."
fi
