#!/bin/bash
# fontlinge_config
# (c) Christian Boltz 2002-2004 / GPL

function getpath {
	perl -e "use fontlinge::Config; print \$fontlinge::Config{'$1'};" || errorexit 250 "
ERROR: Cannot read configuration via perl and fontlinge::Config.
       Please check your Fontlinge installation."
}
function expandtilde {
    perl -e "use fontlinge::Filebasics; print &fontlinge_Expand_Filename('$1')" || errorexit 251 "
ERROR: Cannot expand path via perl and fontlinge::Filebasics
       Please check your Fontlinge installation."
}
function errorexit {
	echo "$2" >&2;
	exit $1;
}
function writeconf {
	if fontlinge_getconfig --status "$1" ; then 
		perl -pi -e "s^[ 	]*$1[ 	]*=.*$1=$2" "$FILENAME"
		test "`fontlinge_getconfig \"$1\"`" == "$1	$2" || errorexit 99 "Could not change setting $1"
	else
		echo "$1=$2" >> "$FILENAME"
		echo "" >> "$FILENAME"
	fi
}
function writecmt {
	fontlinge_getconfig --status "$1" || echo "$2" >> "$FILENAME"
}

# unset "external" variables we don't initialize to avoid problems
unset BATCHMODE SETPERMS UPDATE_MODE WEBGUICONF WEBGUIPATH # internally used in this script
unset apache_user database fontbase my_code mysqlserver password perl5lib sortername tarpath tmp_as_folder trusted_sorters username webgui_path webgui_conf webgui_download_filename webgui_path webgui_suffixes webgui_unsorted # config file options

#umask 077

HOMEDIR="`expandtilde ~`" || exit $?
BASHRC="`expandtilde \"~/.bashrc\"`" || exit $?
FILENAME="`expandtilde \"~/.fontlinge\"`" || exit $?
DEFAULT_TMP="/tmp"
DEFAULT_FONTBASE="$HOMEDIR/fontbase/"
DEFAULT_MYSQLSERVER="localhost"
DEFAULT_DATABASE="fontlinge"
DEFAULT_TRUSTED="core,ratti"
FONTLINGE_COMPLETE="`getpath shareddir`/fontlinge_complete" || errorexit 7 "
ERROR: could not detect path to fontlinge_complete.
Please check why this happened (there should be an error message above),
fix the problem and try again."


while [ -n "$1" ] ; do
	case "$1" in
		--help)
			echo '
fontlinge_config [ --file /path/to/.fontlinge ] [ --help ]
    [ --webgui-conf /path/to/config.inc.php ] [ --webgui-path /path/to/webgui/ ]

This script will ask you for some settings and generate or update
your ~/.fontlinge config file.

Options:

--change-option optionname new_value
    change option optionname in ~/.fontlinge to new_value
	(or insert it if optionname is not set yet)

--file /path/to/.fontlinge
    create /path/to/.fontlinge instead default file ~/.fontlinge

--webgui-conf /path/to/config.inc.php   and
--webgui-path /path/to/webgui/
    write path to WebGUI / config.inc.php to configfile and exit.
    Used by fontlinge_userinstall, usually no need to use manually ;-)

--setperms
    set configfile permissions

--help
      show this help message.
'
			exit 0
			;;
		--file)
			FILENAME="$2"
			test "$2" = "" && errorexit 254 "Option --file requires a parameter."
			shift ; shift

			;;
		--webgui-conf)
			WEBGUICONF="$2"
			BATCHMODE=1
			test "$2" = "" && errorexit 254 "Option --webgui-conf requires a parameter."
			shift ; shift
			;;
		--webgui-path)
			WEBGUIPATH="$2"
			BATCHMODE=1
			test "$2" = "" && errorexit 254 "Option --webgui-path requires a parameter."
			shift ; shift
			;;
		--change-option)
			BATCHMODE=1
			test "$2" = "" -o "$3" = "" && errorexit 254 "Option --change-option requires two parameters."
			writeconf "$2" "$3"
			shift; shift; shift
			;;
		--setperms)
			SETPERMS=1
			shift
			;;
		*)
			errorexit 255 "ERROR: unknown option: $1
See  fontlinge_config --help  for help."
			;;
	esac
done

[ -e "$FILENAME" -a ! -f "$FILENAME" ] && errorexit 1 "
$FILENAME already exists, but is not a file.
Please rename or delete it if you want to create a new
.fontlinge config file."

[ -s "$FILENAME" ] && {
	# read existing config file
	eval "`fontlinge_getconfig --bash`" || errorexit 5 "
Error while reading $FILENAME via fontlinge_getconfig.
Please check why this happened (there should be an error message above,
maybe your .fontlinge has a syntax error) and fix the problem." 
	test `fontlinge_getconfig | grep "^[a-z]" | wc -l` -gt 2 && UPDATE_MODE=1
	# not more than two entries (possibly by fontlinge_userinstall) in configfile
	# -> Do not show "update mode" notice.
}


# handle --setperms
test -n "$SETPERMS" -a -n "$webgui_conf" && {
	setfacl -m "user:$apache_user:r--" "$FILENAME" "$webgui_conf" &>/dev/null && \
	chmod 640 "$FILENAME" "$webgui_conf" || errorexit 9 "
WARNING: The configfile permissions could not be set using ACL.
         Please secure (chmod) $FILENAME and 
         $webgui_conf yourself.
         Both files must be readable for the user running your webserver, but
         should not be readable by others since they contain the MySQL password."
  	exit
}


# Still here? So we have to create/update the .fontlinge file.

test -z "$BATCHMODE" && echo "
This script will create or update $FILENAME

You may enter what you want, but if you enter bullshit,
you'll get problems when running Fontlinge ;-)
"

[ "$UPDATE_MODE" = "1" -a -z "$BATCHMODE" ] && echo "
-----------------------------------------------------------------------
$FILENAME already exists.
I will only ask for new config options.

If I don't ask for any setting, your config file is already up to date.
-----------------------------------------------------------------------
"

# check if we can write to $FILENAME
	echo -n "" >> "$FILENAME" || errorexit 2 "
ERROR: Can't write to $FILENAME
Maybe the file or your homedir ($HOMEDIR) is set read-only.
"

# write first part of $FILENAME
test -s "$FILENAME" || writecmt "" \
"# .fontlinge - autogenerated by fontlinge_config

#
# WARNING!
#
# If you edit this file, run  fontlinge_getconfig --webgui  afterwards
# to update the WebGUI config file.
#
# If you want to use these parameters in your programm, DON'T
# read this file directly! Instead, use the fontlinge_getconfig
# script. This file's format is subject to change.
#
"

test -n "$WEBGUIPATH" && {
	# called by fontlinge_userinstall. Write path to WebGUI to configfile and exit
	writecmt webgui_path "# path to WebGUI"
	writeconf webgui_path "$WEBGUIPATH"
}

test -n "$WEBGUICONF" && {
	# called by fontlinge_userinstall. Write path to config.inc.php to configfile and exit
	writecmt webgui_conf "# path to WebGUI config.inc.php file"
	writeconf webgui_conf "$WEBGUICONF"
}

test -n "$BATCHMODE" && exit # exit - no questions if in BATCH MODE


### user running the webserver
#echo test -z "$apache_user" 
test -z "$apache_user" && \
{
echo -n "
Please enter the name of the user running your webserver (mostly Apache).
Common usernames are wwwrun, www-data, httpd or apache.
The username is needed to secure the Fontlinge config file.

Please note that your filesystem must support ACL.
Also note that ACL require at least permissions for the group, so you may want 
to chgrp $FILENAME $webgui_conf

Just press enter if you want to allow EVERYBODY to read your configfile
(which also contains the MySQL password).

Username running the webserver: "
unset APACHE_USER ; read APACHE_USER

test -n "$APACHE_USER" && {
	id "$APACHE_USER" >/dev/null || errorexit 8 "
ERROR: 'id' returned an error when checking for user $APACHE_USER.
       There should be an error message above.
"
	writecmt apache_user "# username running the webserver (mostly Apache)"
	writeconf apache_user "$APACHE_USER"
	fontlinge_config --setperms
}
}

# re-set permissios if $apache_user was already set
test -n "$apache_user" && "$0" --setperms

### MySQL Server
test -z "$mysqlserver" && \
{
echo -n "
First, enter the name of your MySQL server.
Usually, this is 'localhost', but maybe you use an external MySQL server.
Just press enter if you want to use the default value
    $DEFAULT_MYSQLSERVER

MySQL server: "
unset MYSQLSERVER ; read MYSQLSERVER
[ "$MYSQLSERVER" = "" ] && MYSQLSERVER="$DEFAULT_MYSQLSERVER"

	writecmt mysqlserver "# MySQL server (usually localhost)" 
	writeconf mysqlserver "$MYSQLSERVER"
}

### database name
test -z "$database" && \
{
echo -n "
Please enter the name of the database to use with fontlinge.
If the database doesn't exist, you can create it later with
fontlinge_database_assistant --create-database

Just press enter if you want to use the default value
    $DEFAULT_DATABASE

Database name: "
unset DATABASE ; read DATABASE
[ "$DATABASE" = "" ] && DATABASE="$DEFAULT_DATABASE"

	writecmt database "# MySQL database name to use with fontlinge"
	writeconf database "$DATABASE"
}

### MySQL Username
test -z "$username" && \
{
echo -n "
Enter MySQL username and password.
You may enter a MySQL username that doesn't exist yet and later
create the MySQL user with fontlinge_database_assistant --create-user

Please enter MySQL Username: "
unset MYSQL_USER ; read MYSQL_USER

	writecmt username "# MySQL login: username"
	writeconf username "$MYSQL_USER"
}

### MySQL Password
test -z "$password" && \
{
echo -n "Please enter MySQL Password (will not be displayed): "
unset MYSQL_PASS ; read -s MYSQL_PASS
	writecmt password "# MySQL login: password"
	writeconf password "$MYSQL_PASS"
}

### tempdir
test -z "${tmp_as_folder}" && \
{
echo -n "
Please enter a path to your fontlinge tmp folder.
(This setting is useful for people who have the PHP open_basedir
 option set. All the others may just use /tmp)
The directory will be created if it doesn't exist.
Just press enter if you want to use the default path
    $DEFAULT_TMP
Temp folder: "

unset TMP_FOLDER ; read -e TMP_FOLDER
[ "$TMP_FOLDER" = "" ] && TMP_FOLDER="$DEFAULT_TMP"
TMP_FOLDER="`expandtilde \"$TMP_FOLDER\"`" || exit $?

[ -d "$TMP_FOLDER" ] || { \
    echo ""
    mkdir -p "$TMP_FOLDER" && echo "$TMP_FOLDER created successfully." || \
    errorexit 3 "
ERROR: $TMP_FOLDER could not be created.
Maybe it exists and is a file, not a directory or
you don't have write access to the directory above."
}

echo "
#########################################################################
Please make sure your Apache user (for example wwwrun)
has write access to $TMP_FOLDER
See   man chmod   or   man setfacl   for details.
#########################################################################" >&2

	writecmt tmp_as_folder \
'# Path to tempdir.
# Please make sure your Apache user (for example wwwrun) has write access
# to this directory!'
	writeconf tmp_as_folder "$TMP_FOLDER"
}

### tar
test -z "$tarpath" && \
{
echo -n "
Please enter the path to tar.
Just press enter if you want to use the default path returned by 'which tar'
    `which tar`
tar path: "

unset TAR_PATH ; read -e TAR_PATH
[ -z "$TAR_PATH" ] && TAR_PATH="`which tar`"
TAR_PATH="`expandtilde \"$TAR_PATH\"`" || exit $?

writecmt tarpath "# where is your 'tar'?"

	writeconf tarpath "$TAR_PATH"
}

### fontbase directory
test -z "${fontbase}" && \
{
echo -n "

Please enter a path where your fonts should be sorted into by default.

Just press enter if you want to use the default path
    $DEFAULT_FONTBASE
fontbase folder: "

unset FONTBASE_FOLDER ; read -e FONTBASE_FOLDER
[ "$FONTBASE_FOLDER" = "" ] && FONTBASE_FOLDER="$DEFAULT_FONTBASE"
FONTBASE_FOLDER="`expandtilde \"$FONTBASE_FOLDER\"`" || exit $?

	writecmt fontbase "# fontbase directory"
	writeconf fontbase "$FONTBASE_FOLDER"
}

### sortername
test -z "$sortername" && \
{
echo -n '
Please enter a sorter name.
This must be a worldwide unique alphanumeric (No spaces etc.!!) name
to be inserted in database for fonts _you_ sorted into kategories.
Maximum 8 characters!
Sorter name: '

unset SORTERNAME ; read SORTERNAME

writecmt sortername \
'# Sortername to be used in database for fonts _you_ sort into categories.
# This must be a worldwide unique alphanumeric (No spaces etc.!) name.
# ___________________________________________________
# _____ Maximum 8 characters!!!!!!!!!!!!!!!!! _______'

	writeconf sortername "$SORTERNAME"
}

### trusted sorters
test -z "$trusted_sorters" && \
{
echo -n "
Please enter a list of trusted sorters.
This option is used for fontlinge_database_assistant --import-text.
Sortlist entries from these sorters will always be overwritten,
even if --overwrite-duplicates is not given.

Use a comma-separated list to specify more than one.
Enter '-' if you don't trust anybody.
Just press enter if you want to use the default value
    $DEFAULT_TRUSTED

Trusted sorters: "

unset TRUSTED_SORTERS ; read TRUSTED_SORTERS
[ -z "$TRUSTED_SORTERS" ] && TRUSTED_SORTERS="$DEFAULT_TRUSTED"

writecmt trusted_sorters "# Trusted sorters (for fontlinge_database_assistant --import-text)
# Multiple entries can be given as comma-separated list."

	writeconf trusted_sorters "$TRUSTED_SORTERS"
}

### custom code
# This will often be unset, so we grep for my_code instead ;-)
grep "my_code[ 	]*=" "$FILENAME" >/dev/null ||
{
echo -n "
If you want to use custom code, enter the path and filename of the code sniplet.
If you don't want to use this feature or if you even don't know what this means,
just press Enter.
This is equivalent to the --my-code option.
Custom code: "

unset CUSTOMCODE ; read -e CUSTOMCODE
test -n "$CUSTOMCODE" && { CUSTOMCODE="`expandtilde \"$CUSTOMCODE\"`" || exit $? ; }

writecmt my_code "# use your own perl-code.
# If you don't want to use this feature comment it out.
#
# Example:
#my_code=/path/to/my_code_sniplet.pl
"

[ -n "$CUSTOMCODE" ] && {
	writeconf my_code "$CUSTOMCODE"
}

# my_code is new in 2.1, so it's the perfect moment to fix the ~/.fontlinge permissons
# without breaking new configfiles with intentionally more permissions
#chmod go-r "$FILENAME"

}

# include fontlinge_complete into ~/.bashrc
ask_completion=1
complete >/dev/null 2>&1 || {
	ask_completion=10
	echo
	echo "Sorry, bash autocompletion isn't available because">&2
	echo "your bash doesn't support the 'complete' command.">&2
}
grep "fontlinge_complete" "$BASHRC" >/dev/null && ask_completion=11
grep "you didn't want fontlinge_complete to be included in your bashrc" "$FILENAME" >/dev/null && ask_completion=12
test \! -f "$FONTLINGE_COMPLETE" -a "$ask_completion" = "1" && {
	echo
	echo "Sorry, bash autocompletion isn't available because">&2
	echo "$FONTLINGE_COMPLETE does not exist or is not a file.">&2
	echo "Please check your Fontlinge installation.">&2
	ask_completion=13
}	

[ "$ask_completion" = 1 ] && {
echo -n "
Do you want to have fontlinge_complete included to your $BASHRC?
fontlinge_complete enables auto-completion for the --options of the fontlinge
scripts, so you can type i. e. fontlinge_base --c<tab> and it will be completed
to --copy.
Please enter 'y' for yes or 'n' for no.

Enable fontlinge_complete? "
unset enable_completion ; read enable_completion

[ "$enable_completion" = "y" ] && {
  echo "Adding 'source $FONTLINGE_COMPLETE' to $BASHRC"
  echo "" >> "$BASHRC" || errorexit 6 "
ERROR: could not append a line to $BASHRC.
Please check the error messages above!"

  echo "# autocompletion for fontlinge options - added by fontlinge_config" >> "$BASHRC"
  echo "source $FONTLINGE_COMPLETE" >> "$BASHRC"
}

[ "$enable_completion" = "n" ] && {
writecmt "" "# you didn't want fontlinge_complete to be included in your bashrc
# (fontlinge_config will ask for it again if you remove the line above)"

  echo "You choosed NOT to include fontlinge_complete in your $BASHRC."
  echo "I will not ask again as long as the comment added to $FILENAME exists."
}
}

### downwardly compatibility checks

fontlinge_getconfig --status "my_preview" && {
echo "
#########################################################################
Your $FILENAME contains a my_preview sniplet.

The my_preview option is no longer supported - use my_code instead.

To avoid this warning, remove the my_preview entry from your .fontlinge.
#########################################################################" >&2
}

### done!

echo -n "
$FILENAME created. Enjoy Fontlinge!


------------------------------------------------------
      now run
          fontlinge_database_assistant --phoenix
      to check and complete your database setup.
------------------------------------------------------
"
