#!/bin/sh
#
# Copyright (c) 2002 by 
# Roland Mainz <roland.mainz@informatik.med.uni-giessen.de>
# All rights reserved.
#
#ident  "@(#)xprint   0.5    2002/12/01 gisburn"
#
# chkconfig: 2345 61 61
# description: Xprt is the daemon for Xprint
#
# Startup/shutdown script for Xprint server(s)
#
############################################################################
#
# This script has three tasks:
# 1. Start Xprint servers ("Xprt") at boot time.
# 2. Shutdown Xprint servers when the machine is being shut down.
# 3. Query the list of available printers.
#
# Usage:
# - Start Xprint server(s) manually:
#   % /etc/init.d/xprint start
#
# - Stop Xprint server(s) manually:
#   % /etc/init.d/xprint stop
#
# - Populate $XPSERVERLIST env var (for example as part of a global
#   login script like /etc/profile or per-user login scripts like
#   $HOME/.profile (sh/ksh/bash))
#   % XPSERVERLIST="`/etc/init.d/xprint get_xpserverlist`"
#   % export XPSERVERLIST
#
# Installation:
#   Copy this script to /etc/init.d/xprint, create links to the matching
#   run levels and make sure that the script is executable.
#   Examples:
#     - Solaris 2.7:
#       % cp xprint /etc/init.d/xprint
#       % chmod a+rx /etc/init.d/xprint
#       % ln /etc/init.d/xprint /etc/rc0.d/K38xprint
#       % ln /etc/init.d/xprint /etc/rc1.d/K38xprint
#       % ln /etc/init.d/xprint /etc/rc2.d/S81xprint
#       % ln /etc/init.d/xprint /etc/rcS.d/K38xprint
#
#     - SuSE Linux 7.3
#       % cp xprint /etc/init.d/xprint
#       % chmod a+rx /etc/init.d/xprint
#       % ln -s ../xprint /etc/init.d/rc3.d/K13xprint
#       % ln -s ../xprint /etc/init.d/rc3.d/S12xprint
#       % ln -s ../xprint /etc/init.d/rc5.d/K13xprint
#       % ln -s ../xprint /etc/init.d/rc5.d/S12xprint
#       % ln -s ../xprint /etc/init.d/rc2.d/K13xprint
#       % ln -s ../xprint /etc/init.d/rc2.d/S12xprint
#
#     - SuSE Linux 6.4:
#       % cp xprint /sbin/init.d/xprint
#       % chmod a+rx /sbin/init.d/xprint
#       % ln -s ../xprint /sbin/init.d/rc2.d/K20xprint
#       % ln -s ../xprint /sbin/init.d/rc2.d/S20xprint
#       % ln -s ../xprint /sbin/init.d/rc3.d/K20xprint
#       % ln -s ../xprint /sbin/init.d/rc3.d/S20xprint
#
#   Notes: 
#   - The Xprint servers must be started _after_ the print
#     spooler or the server(s) may refuse to start
#   - The script should be readable by all users to ensure that they
#     can use the "get_xpserverlist"-option
#
# Custom configuration:
#   - Edit the function setup_config() in this script to match your needs
#
# Known bugs/ToDo/Notes:
#   - The shell script assumes that a Xserver can be reached via 
#     "hostname:displaynum" where "hostname" is obtained from
#     "/usr/bin/hostname". It may happen that a kernel firewall
#     blocks an X connection on the same host (e.g. client && Xserver 
#     are running on the same host).
#     Suggested fix: Fix the firewall config.
#     Suggested workaround: Edit this script and replace the use of 
#     /usr/bin/hostname with "echo 'localhost'".
#
############################################################################
#

# Force use of a POSIX conformant sh 
# (Solaris /sbin/sh is plain Bourne shell)
[ "$1" != "posix_sh_forced" -a -x /bin/ksh  ]   && exec /bin/ksh  "$0" posix_sh_forced "$@"
[ "$1" != "posix_sh_forced" -a -x /bin/ksh93  ] && exec /bin/ksh93  "$0" posix_sh_forced "$@"
[ "$1" != "posix_sh_forced" -a -x /bin/bash ]   && exec /bin/bash "$0" posix_sh_forced "$@"
if [ "$1" != "posix_sh_forced" ] ; then
    echo "${0}: No POSIX-shell found." 
    exit 1
fi

shift # Drop "posix_sh_forced"

# Set search path for commands
export PATH=/usr/bin:/bin:/usr/sbin:/sbin
if [ "$(uname -s)" = "SunOS" ] ; then
    export PATH=/usr/xpg4/bin:${PATH}
fi

## Try to figure-out where X11 was installed
case "$(uname -s)" in
    *SunOS*)
        XPROJECTROOT=/usr/openwin
        ;;
    *)          
        [ -d /usr/X11/bin ]     && XPROJECTROOT=/usr/X11
        [ -d /usr/X11R6/bin ]   && XPROJECTROOT=/usr/X11R6
        [ -d /usr/lpp/X11/bin ] && XPROJECTROOT=/usr/lpp/X11
        ;;
esac
export XPROJECTROOT

if [ -z "${XPROJECTROOT}" ] ; then
    echo "$0: Unknown XProjectRoot."
    exit 1
fi

# Set the location of the Xprt binary we want to use.
XPRT_BIN=${XPROJECTROOT}/bin/Xprt

# Set the location of the global file where we store the locations 
# of the system-wide servers
if [ -d /var/run ] ; then
    XP_GLOBAL_SERVERS=/var/run/Xprint_servers
else
    XP_GLOBAL_SERVERS=/tmp/.Xprint_servers
fi

# ${LOGNAME} will not work if user su'ed into another account
export CURRLOGNAME="$(getent passwd $(id -u) | cut -f 1 -d ':')"

# Set location where we want to store the list of Xprint servers managed
# by this user
# - If we start as "root" use the global file
# - If we start as normal user use a per-user file

if [ "${CURRLOGNAME}" != "root" -a "${CURRLOGNAME}" != "" ] ; then
    XP_PER_USER_SERVERS="/tmp/.Xprint_servers_${CURRLOGNAME}"
    XP_SERVERS="${XP_PER_USER_SERVERS}"
else
    XP_SERVERS="${XP_GLOBAL_SERVERS}"
fi

# Set umask that owner can r/w all files and everyone else can read them
umask 022

############################################################################

# Get list of system fonts
get_system_fontlist()
{
    case "$(uname -s)" in
      *SunOS*)
          ## List the standard X11 fonts
          # echo "${XPROJECTROOT}/lib/X11/fonts/F3/"
          # echo "${XPROJECTROOT}/lib/X11/fonts/F3bitmaps/"
          echo "${XPROJECTROOT}/lib/X11/fonts/Type1/"
          echo "${XPROJECTROOT}/lib/X11/fonts/TrueType/"
          echo "${XPROJECTROOT}/lib/X11/fonts/Speedo/"
          echo "${XPROJECTROOT}/lib/X11/fonts/misc/"
          echo "${XPROJECTROOT}/lib/X11/fonts/75dpi/"
          echo "${XPROJECTROOT}/lib/X11/fonts/100dpi/"
  
          ## List all fonts in all locales installed on this machine
          cat $(find /usr/openwin -name OWfontpath 2>/dev/null) | tr "," "\n" | sort | uniq
          ;;
      Linux)
          ## List all fonts in all locales installed on this machine
          find ${XPROJECTROOT}/lib/X11/fonts -name fonts.dir | \
            while read i ; do echo "${i%/fonts.dir}" ; done | \
            (fontpath="" ; fpdelim=""; 
            while read i ; do
                fontpath="${fontpath}${fpdelim}${i}" ; fpdelim="," ; 
            done ; 
            echo "$fontpath") | \
            tr "," "\n" | sort | uniq
          ;;
      *)          
          ## List the standard X11 fonts
          echo "${XPROJECTROOT}/lib/X11/fonts/Type1/"
          echo "${XPROJECTROOT}/lib/X11/fonts/TrueType/"
          echo "${XPROJECTROOT}/lib/X11/fonts/TTF/"
          echo "${XPROJECTROOT}/lib/X11/fonts/Speedo/"
          echo "${XPROJECTROOT}/lib/X11/fonts/misc/"
          echo "${XPROJECTROOT}/lib/X11/fonts/75dpi/"
          echo "${XPROJECTROOT}/lib/X11/fonts/100dpi/"
          ;;
    esac
}

# Get list of fonts for a given display
get_fontlist_from_display()
{
    ${XPROJECTROOT}/bin/xset -display "${1}" q | 
      awk "/Font Path:/ { i=1 ; next } i==1 { print \$0 ; i=0 }" | 
        fontpath2fontlist
}

# Filter fonts per given extended regular expressions
# (and make sure we filter any model-config fonts - they are managed by Xprt internally)
filter_fontlist()
{
    egrep -- "${1}" | fgrep -v "/models/" | egrep -v -- "${2}"
}

# Filter dirs with TrueType fonts
filter_ttf_fontlist()
{
    egrep -v "/TrueType|/TT(/$|$)|/TTF(/$|$)"
}

# Validate fontpath
# Only return valid font path entries
validate_fontlist()
{
    while read i ; do 
        [ -f "${i}/fonts.dir" ] && echo "$i";
    done
}

# Build a comma-seperated list of fonts (font path) from a list of fonts
fontlist2fontpath()
{
    fp=""
    read fp;
    while read i ; do
        fp="${fp},${i}"
    done
    
    echo "$fp"
}

# Build a list (one item per line) of fonts from a font path
fontpath2fontlist()
{
    while read i ; do
        echo "${i}" | tr "," "\n"
    done
}

# Sort scaleable fonts (PS Type1 and TrueType) first in a font list
sort_scaleable_fonts_first()
{
    i="$(fontlist2fontpath)"
    # First list PS Type1 fonts...
    echo "${i}" | fontpath2fontlist | fgrep "/Type1"
    # ... then TrueType fonts ...
    echo "${i}" | fontpath2fontlist | egrep "/TrueType|/TT(/$|$)|/TTF(/$|$)"
    # ... then all others
    echo "${i}" | fontpath2fontlist | egrep -v "/Type1|/TrueType|/TT(/$|$)|/TTF(/$|$)"
}

# Check if a X display is used by a Xserver or not
# Known bugs:
# - there is no way in plain bourne shell or bash (see comment about ksh93
#   below) to test if a Xserver sits only on a socket and not on a pipe
# - some Xserver's don't cleanup their stuff in /tmp on exit which may end
#   in the problem that we don't detect possible free display numbers
#   (one problem is that only ksh93 can do stuff like 
#   "cat </dev/tcp/0.0.0.0/6001")
CheckIfDisplayIsInUse()
{
    id=$1
    
    [ -r "/tmp/.X${id}-lock"     ] && return 0;
    [ -r "/tmp/.X11-unix/X${id}" ] && return 0;
    [ -r "/tmp/.X11-pipe/X${id}" ] && return 0;
    
    return 1;
}

lastdisplaynumreturned_store=/tmp/.Xp_last_display_returned_by_findfreexdisplaynum_${RANDOM}_${RANDOM}

# Try to find a free display number
FindFreeXDisplayNum()
{
    if [ -r "${lastdisplaynumreturned_store}" ] ; then
      i="$(cat "${lastdisplaynumreturned_store}")"
    else
      i=32 # start at display 32
    fi
    
    while [ $i -lt 127 ] ; do
        i=$(($i + 1))

        if CheckIfDisplayIsInUse $i ; then
            true
        else
            echo "$i"
            echo "$i" >"${lastdisplaynumreturned_store}"
            return 0
        fi
    done
    
    return 1
}

# Check if a process exists or not
pexists()
{
    [ "$1" == "" ] && return 1;

    # Use of /proc would be better but not all platforms (like AIX) have procfs
    [ "$(ps -p $1 | fgrep $1)" != "" ] && return 0;
    return 1
}

# Check if there is a spooler running...
is_spooler_running()
{
    [ "$(ps -A | egrep 'lpd|lpsched|cupsd' | fgrep -v 'grep')" != "" ] && return 0;
    return 1
}

# Wait until the spooler system has been started (but not more than 30secs)
wait_for_print_spooler()
{
    for i in 1 2 3 4 5 6 7 8 9 10 ; do
        # This covers Linux lpd, CUPS and Solaris - but what about AIX,
        # HP-UX and IRIX ?
        is_spooler_running && return 0;
        sleep 3
    done
    
    return 0
}

# Start Xprint servers
start_servers()
{
    # Write registry "intro" ...
    echo "# Xprint server list"                               >>"${XP_SERVERS}"
    echo "# File is for private use for ${0}."                >>"${XP_SERVERS}"
    echo "# Do not edit, rely on the content or file format." >>"${XP_SERVERS}"

    hostname="$(hostname)"

    default_fontpath="$(get_system_fontlist | fontlist2fontpath)"
    default_fontpath_acceptpattern=".*";
    default_fontpath_rejectpattern="_No_Match_"; # Match nothing   
    
    curr=0
    while [ $curr -lt $num_xpstart ] ; do
        if [ "${xpstart_remote_server[$curr]}" != "" ] ; then
            # Remote Xprt, just put the entry into the registry
            echo "display=${xpstart_remote_server[$curr]}" >>"${XP_SERVERS}"
        else
            # Run block in seperate process to avoid that changes to the
            # xpstart_* variables affect the next cycle
            (
              # Use defaults if there are no special options
              [ "${xpstart_fontpath[$curr]}"               == "" ] &&               xpstart_fontpath[$curr]="${default_fontpath}";
              [ "${xpstart_fontpath_acceptpattern[$curr]}" == "" ] && xpstart_fontpath_acceptpattern[$curr]="$default_fontpath_acceptpattern";
              [ "${xpstart_fontpath_rejectpattern[$curr]}" == "" ] && xpstart_fontpath_rejectpattern[$curr]="$default_fontpath_rejectpattern";
              [ "${xpstart_enable_truetype[$curr]}"        == "" ] &&        xpstart_enable_truetype[$curr]="false";
              [ "${xpstart_font_encodings_dir[$curr]}"     == "" ] &&     xpstart_font_encodings_dir[$curr]="${XPROJECTROOT}/lib/X11/fonts/encodings/encodings.dir";
              [ "${xpstart_displayid[$curr]}"              == "" ] &&              xpstart_displayid[$curr]="$(FindFreeXDisplayNum)"       
              [ "${xpstart_logger[$curr]}"                 == "" ] &&                 xpstart_logger[$curr]="logger -p lpr.notice -t Xprt_${xpstart_displayid[$curr]}";
              [ "${xpstart_logfile[$curr]}"                == "" ] &&                xpstart_logfile[$curr]="/dev/null";
              [ "${xpstart_xprt_binary[$curr]}"            == "" ] &&            xpstart_xprt_binary[$curr]="${XPRT_BIN}";

              # Check if the Xprt binary is available                                     
              if [ ! -x "${xpstart_xprt_binary[$curr]}" ] ; then                                            
                  echo "$0: Can't find \"${xpstart_xprt_binary[$curr]}\"."                                  
                  exit 1 # exit block                                                               
              fi                                                                          

              # Set location of font encodings directory file
              unset FONT_ENCODINGS_DIRECTORY
              if ${xpstart_enable_truetype[$curr]} ; then
                  if [ ! -f "${xpstart_font_encodings_dir[$curr]}" ] ; then
                      echo "$0: WARNING: Can't find \"${xpstart_font_encodings_dir[$curr]}\", TrueType font support disabled."
                      xpstart_enable_truetype[$curr]="false";
                  else
                      export FONT_ENCODINGS_DIRECTORY="${xpstart_font_encodings_dir[$curr]}"
                  fi
              fi

              # Generate font path (containing only valid font path elements)
              # from input font path and filter expressions
              curr_fp=$(echo "${xpstart_fontpath[$curr]}" | 
                        fontpath2fontlist |
                        (if ${xpstart_enable_truetype[$curr]} ; then cat ; else filter_ttf_fontlist ; fi) |
                        filter_fontlist "${xpstart_fontpath_acceptpattern[$curr]}" "${xpstart_fontpath_rejectpattern[$curr]}" | 
                        sort_scaleable_fonts_first | 
                        validate_fontlist | 
                        fontlist2fontpath)

              # Set Xserver auditing level option
              unset curr_audit
              if [ "${xpstart_auditlevel[$curr]}" != "" ] ; then
                  curr_audit="-audit ${xpstart_auditlevel[$curr]}"
              fi

              # Set Xprt -XpFile option
              unset curr_xpfile
              if [ "${xpstart_xpfile[$curr]}" != "" ] ; then
                  curr_xpfile="-XpFile ${xpstart_xpfile[$curr]}"
              fi

              # Set custom XPCONFIGDIR (if there is one)
              unset XPCONFIGDIR
              if [ "${xpstart_xpconfigdir[$curr]}" != "" ] ; then
                  export XPCONFIGDIR="${xpstart_xpconfigdir[$curr]}"
              fi

              (
                (
                  "${xpstart_xprt_binary[$curr]}" \
                      ${xpstart_options[$curr]} \
                      ${curr_xpfile} ${curr_audit} \
                      -fp ${curr_fp} \
                      :${xpstart_displayid[$curr]} &
                  echo "display=${hostname}:${xpstart_displayid[$curr]} display_id=${xpstart_displayid[$curr]} pid=$!" >>"${XP_SERVERS}"
                ) 2>&1 | tee -a "${xpstart_logfile[$curr]}" | ${xpstart_logger[$curr]}
              ) &
              sleep 2 # try to avoid that two started procs append to ${XP_SERVERS} at the same time
            )
        fi
        
        curr=$(($curr + 1))
    done
    
    # Remove tmp. file created by |FindFreeXDisplayNum()|
    rm -f "${lastdisplaynumreturned_store}"

    # Done.
    echo "# EOF." >>"${XP_SERVERS}"
    return 0
}


# Convenience function to check setup and start Xprt server(s)
do_start()
{
    if [ -f "${XP_SERVERS}" ] ; then
        echo "$0: Xprint servers are already running."
    else
        # Check if we can write the registry file
        touch "${XP_SERVERS}" 2>/dev/null
        if [ ! -f "${XP_SERVERS}" ] ; then
            echo "$0: Cannot create \"${XP_SERVERS}\"."
            exit 1
        fi

        if ! setup_config ; then
            echo "$0: setup_config failed."
            exit 1
        fi
 
        # Continue in the background if there is no spooler running yet (that
        # we don't hold off the boot process nor run in a possible race-condition
        # when /etc/init.d/lpd was not called yet but the runlevel script waits
        # for us to finish first ...
        if is_spooler_running ; then
            echo "Starting Xprint servers"
            start_servers
        else
            echo "Starting Xprint servers (in the background)"
            (wait_for_print_spooler ; start_servers) &
            sleep 5
        fi
        
        if [ "${CURRLOGNAME}" = "root" -a -d /var/lock/subsys/ ] ; then
            touch /var/lock/subsys/xprint
        fi
    fi
}

# Convenience function to stop Xprt server(s)
do_stop()
{
    echo "Stopping Xprint servers"

    if [ -f "${XP_SERVERS}" ] ; then
        cat "${XP_SERVERS}" |
          grep "^display=.*:.* pid=[0-9]*$" |
          while read i ; do
              (
                eval ${i}
                if pexists ${pid} ; then 
                    kill ${pid}
                fi

                # Remove the X sockets/pipes which are not in use anymore
                # (It would be better if the Xservers would cleanup this
                # automatically, but most Xservers do not do that... ;-(
                # Note that this will not work on Solaris where applications
                # must run with groupid="root" if they want to write into
                # /tmp/.X11-unix/ and/or /tmp/.X11-pipe/)
                if [ "${display_id}" != "" ] ; then
                    rm -f "/tmp/.X${display_id}-lock"     2>/dev/null
                    rm -f "/tmp/.X11-unix/X${display_id}" 2>/dev/null
                    rm -f "/tmp/.X11-pipe/X${display_id}" 2>/dev/null
                fi 
              )
          done
        rm -f "${XP_SERVERS}"
    fi

    if [ "${CURRLOGNAME}" = "root" -a -d /var/lock/subsys/ ] ; then
        rm -f /var/lock/subsys/xprint
    fi
}

# Convenience function to obtain a list of available Xprint servers
do_get_xpserverlist()
{
    if [ -f "${XP_PER_USER_SERVERS}" -o -f "${XP_GLOBAL_SERVERS}" ] ; then
        xpserverlist=$(
          # Enumerate both per-user and global servers (in that order)
          (
            [ -f "${XP_PER_USER_SERVERS}" ]  && cat "${XP_PER_USER_SERVERS}"
            [ -f "${XP_GLOBAL_SERVERS}"   ]  && cat "${XP_GLOBAL_SERVERS}"
          ) |
            egrep "^display=.*:.* pid=[0-9]*$|^display=.*:[0-9]*$" |
              while read i ; do
                  (
                    pid="none"
                    eval ${i}
                    # Check if the Xprt process exists (if possible)
                    if [ "$pid" != "none" ] ; then
                        if pexists ${pid} ; then
                            echo ${display}
                        fi
                    else
                        echo ${display}
                    fi
                  )
              done | tr "[\n]" " "
          )
        # Only produce output if we have some entries...
        [ "${xpserverlist}" != "" ] && echo "${xpserverlist}"
    fi
}

do_restart()
{
    echo "Restarting Xprint server(s)"
    do_stop
    sleep 1
    do_start
}

############################################################################
# setup_config() sets the configuration parameters used to start one
# or more Xprint servers ("Xprt").
# The following variables are used:
# - "num_xpstart" - number of servers to start
# - "xpstart_fontpath[index]" - custom font path. Leave blank if you want
#   the platform-specific default
# - "xpstart_fontpath_acceptpattern[index]" - extended regular expression
#   (see egrep(1)) used to filter the font path - items only pass this
#   filter if they match the pattern (leave blank if you want to filter
#   nothing)
# - "xpstart_fontpath_rejectpattern[index]" - extended regular expression
#   (see egrep(1)) used to filter the font path - items only pass this
#   filter if they do not match the pattern (leave blank if you want to
#   filter nothing)
# - "xpstart_font_encodings_dir[index]" - location of "encodings.dir".
#   Leave blank to use the default.
# - "xpstart_enable_truetype[index]" - use "true" or "false" to enable or
#   disable use of TrueType fonts, leave blank to use the systems default
# - "xpstart_displayid[index]" - display id to use for the Xprint server
#   (leave blank to choose the next available free display id)
# - "xpstart_xpconfigdir[index]" - value for custom XPCONFIGDIR (leave blank
#   if you don not want that that XPCONFIGDIR is set at Xprt startup)
# - "xpstart_xpfile[index]" - value used for Xprt's "-XpFile" option (leave
#   blank if you do not want to set this option)
# - "xpstart_auditlevel[index]" - set Xserver auditing level (leave blank to
#   use no auditing)
# - "xpstart_options[index]" - set further Xprt options (leave blank to set
#   no further options)
# - "xpstart_logger[index]" - utility which gets stderr/stdout messages from
#   Xprt and sends them to a logging daemon. Leave blank to use /usr/bin/logger
#   to send such messages to the lpr.notice syslog)
# - "xpstart_logfile[index]" - log file to append stderr/stdout messages from
#   Xprt to. Leave blank to send messages to /dev/null
# - "xpstart_xprt_binary[index]" - set custom Xprt binary (leave blank to use
#   the platform-specifc default)

setup_config()
{
    num_xpstart=0;
    
    # Source per-user ~/.Xprint_per_user_startup file if there is one
    # (and do not use the script's defaults below)
    if [ "${HOME}" != "" ] ; then
        if [ -r "${HOME}/.Xprint_per_user_startup" ] ; then
            # Define API version which should be checked by ${HOME}/.Xprint_per_user_startup
            # ${HOME}/.Xprint_per_user_startup should bail-out if the version differ
            etc_initd_xprint_api_version=2
            
            # Source per-user settings script
            . "${HOME}/.Xprint_per_user_startup"
            
            # done with setting the config for per-user Xprt instances
            return 0
        fi
    fi

    #### Defaults for Linux/Solaris
    # Start Xprt using builtin XPCONFIGDIR at a free display numer
    # (Solaris(=SunOS5.x)'s /usr/openwin/bin/Xprt supports TrueType fonts,
    # therefore we don't need to filter them)
                      xpstart_fontpath[$num_xpstart]="";
        xpstart_fontpath_acceptpattern[$num_xpstart]=".*";
    if [ "$(uname -s)" = "SunOS" ] ; then
        # Solaris /usr/openwin/bin/Xprt supports TrueType fonts
               xpstart_enable_truetype[$num_xpstart]="true";
        xpstart_fontpath_rejectpattern[$num_xpstart]="/Speedo|/F3bitmaps|/F3";
    else
        # xprint.mozdev.org-based Xprt servers support TrueType fonts since version 0.8
               xpstart_enable_truetype[$num_xpstart]="true";
        xpstart_fontpath_rejectpattern[$num_xpstart]="/Speedo";
    fi
                     xpstart_displayid[$num_xpstart]="";
                   xpstart_xpconfigdir[$num_xpstart]="";
                        xpstart_xpfile[$num_xpstart]="";
                    xpstart_auditlevel[$num_xpstart]="4";
                       xpstart_options[$num_xpstart]="-ac -pn";
                        xpstart_logger[$num_xpstart]="";
                       xpstart_logfile[$num_xpstart]="/dev/stderr";
                   xpstart_xprt_binary[$num_xpstart]="";

    #######################################################
    ###
    ### Debian default configuration
    ###
    if [ -f "/etc/debian_version" ] ; then
        # Set XPCONFIGDIR=/usr/share/Xprint/xserver
        xpstart_xpconfigdir[$num_xpstart]="/usr/share/Xprint/xserver";

        # Use fixed display ID (":64"), or else all client programs will have to be
        # restarted simply to update XPSERVERLIST to the latest ID when upgrading,
        # which would be a nightmare.
        xpstart_displayid[$num_xpstart]=64;

        # Do not send any messages to console
        xpstart_logfile[$num_xpstart]="/dev/null";

        # By default use binary provided by Debian's "xprt-xprintorg" package
        # (=/usr/bin/Xprt), otherwise leave blank (e.g. use script's default
        # (=/usr/X11R6/bin/Xprt))
        if [ -x "/usr/bin/Xprt" ] ; then
            xpstart_xprt_binary[$num_xpstart]="/usr/bin/Xprt";
        fi
    fi
    ###
    ### End Debian default configuration
    ###
    #######################################################

    num_xpstart=$(($num_xpstart + 1))


    #### Sample 1:
    # # Start Xprt on a free display ID with custom XPCONFIGDIR and without
    # # Speedo and TrueType fonts
    #    xpstart_fontpath_rejectpattern[$num_xpstart]="/Speedo|/TrueType|/TT(/$|$)|/TTF(/$|$)";
    #               xpstart_xpconfigdir[$num_xpstart]="/home/gisburn/cwork/Xprint/Xprt_config/XpConfig";
    #                xpstart_auditlevel[$num_xpstart]="4";
    #                   xpstart_options[$num_xpstart]="-ac -pn";
    #num_xpstart=$(($num_xpstart + 1))


    #### Sample 2: 
    # # Start Xprt without TrueType fonts on a display 55 with custom
    # # XPCONFIGDIR
    #    xpstart_fontpath_rejectpattern[$num_xpstart]="/TrueType|/TT(/$|$)|/TTF(/$|$)";
    #                 xpstart_displayid[$num_xpstart]=55;
    #               xpstart_xpconfigdir[$num_xpstart]="/home/gisburn/cwork/Xprint/Xprt_config/XpConfig";
    #                xpstart_auditlevel[$num_xpstart]=4;
    #                   xpstart_options[$num_xpstart]="-ac -pn";
    #num_xpstart=$(($num_xpstart + 1))

    #### Sample 3: 
    # # Start Xprt without TrueType fonts on a display 56 with custom
    # # XPCONFIGDIR and alternate "Xprinters" file
    #    xpstart_fontpath_rejectpattern[$num_xpstart]="/TrueType|/TT(/$|$)|/TTF(/$|$)";
    #                 xpstart_displayid[$num_xpstart]=56;
    #               xpstart_xpconfigdir[$num_xpstart]="/etc/XpConfig/default";
    #                    xpstart_xpfile[$num_xpstart]="/etc/XpConfig/default/Xprinters_test2"
    #                xpstart_auditlevel[$num_xpstart]="4";
    #                   xpstart_options[$num_xpstart]="-ac -pn";
    #               xpstart_xprt_binary[$num_xpstart]="";
    #num_xpstart=$(($num_xpstart + 1))

    #### Sample 4:
    # # Start Xprt with Solaris ISO-8859-7 (greek(="el") locale) fonts on
    # # display 57
    #                  xpstart_fontpath[$num_xpstart]="/usr/openwin/lib/locale/iso_8859_7/X11/fonts/75dpi,/usr/openwin/lib/locale/iso_8859_7/X11/fonts/Type1,/usr/openwin/lib/X11/fonts/misc/";
    #    xpstart_fontpath_acceptpattern[$num_xpstart]="";
    #    xpstart_fontpath_rejectpattern[$num_xpstart]="_No_Match_";
    #           xpstart_enable_truetype[$num_xpstart]="true";
    #                 xpstart_displayid[$num_xpstart]="57";
    #                xpstart_auditlevel[$num_xpstart]="4";
    #                   xpstart_options[$num_xpstart]="-ac -pn";
    #num_xpstart=$(($num_xpstart + 1))

    #### Sample 5:
    # # Start Xprt with the font list of an existing Xserver (excluding Speedo fonts) on
    # # display 58
    # # Note that this only works within a X session. At system boot time
    # # there will be no $DISPLAY to fetch the information from!!
    #                  xpstart_fontpath[$num_xpstart]="$(get_fontlist_from_display ${DISPLAY} | fontlist2fontpath)";
    #           xpstart_enable_truetype[$num_xpstart]="true";
    #    xpstart_fontpath_acceptpattern[$num_xpstart]="";
    #    xpstart_fontpath_rejectpattern[$num_xpstart]="";
    #                 xpstart_displayid[$num_xpstart]="58";
    #               xpstart_xpconfigdir[$num_xpstart]="";
    #                xpstart_auditlevel[$num_xpstart]="4";
    #                   xpstart_options[$num_xpstart]="-ac -pn";
    #               xpstart_xprt_binary[$num_xpstart]="";
    #num_xpstart=$(($num_xpstart + 1))

    #### Sample 6:
    # # List remote Xprt's here 
    # # (note that there is no test to check whether these DISPLAYs are valid!)
    #             xpstart_remote_server[$num_xpstart]="sera:12"    ; num_xpstart=$(($num_xpstart + 1))
    #             xpstart_remote_server[$num_xpstart]="gandalf:19" ; num_xpstart=$(($num_xpstart + 1))
    
    return 0;
}

############################################################################

# Main
case "$1" in
    ## Start Xprint servers
    'start')
        do_start
        ;;

    ## Stop Xprint servers
    # Note that this does _not_ kill Xprt instances started using this script 
    # by non-root users
    'stop')
        do_stop
        ;;

    ## Restart Xprint servers
    'restart'|'reload'|'force-reload')
        do_restart
        ;;

    ## Restart Xprint only if it is already running
    'condrestart')
        # only restart if it is already running
        [ -f /var/lock/subsys/xprint ] && do_restart || :
        ;;
    
    ## Get list of all Xprint servers for this user
    # (incl. per-user and system-wide instances)    
    'get_xpserverlist')
        do_get_xpserverlist
        ;;

    ## Get status of Xprint servers, RedHat-style
    'status')
        x="$(do_get_xpserverlist)"
        if [ "${x}" != "" ] ; then
            echo "Xprint (${x}) is running..."
            exit 0
        else
            echo "Xprint is stopped"
            exit 3
        fi 
        ;;

    ## Print usage
    *)
        echo "Usage: $0 { start | stop | restart | reload | force-reload | status | condrestart | get_xpserverlist }"
        exit 1
esac
exit 0

# EOF.
