#!/bin/sh
# WARNING: This file was auto-generated. Do not edit!
#
# $Id: svctool.in,v 2.531 2021-01-23 15:20:31+05:30 Cprogrammer Exp mbhangui $
#

#
# User Configuration
#
QmailHOME=/var/indimail
indimaildir=/var/indimail
QmailBinPrefix=/usr
mandir=/usr/share/man
libexecdir=/usr/libexec/indimail
sysconfdir=/etc/indimail
shareddir=/usr/share/indimail
LOGDIR=/var/log/svc
#indimaildir=`awk -F: '{print $6}' /etc/passwd|grep indimail|head -1`
CONCURRENCYINCOMING=150
min_free=52428800
DATABYTES=20971520
MASTER_HOST=localhost
MYSQL_HOST=localhost
MYSQL_USER=indimail
PRIV_USER=mysql
default_domain=$([ -n "$HOSTNAME" ] && echo "$HOSTNAME" || uname -n)
host=x86_64-pc-linux-gnu
shared_objects=0
use_dlmopen=0
skip_sendmail_check=0
RCSID="# \$Id: svctool.in,v 2.531 2021-01-23 15:20:31+05:30 Cprogrammer Exp mbhangui $"

if [ -d /run/mysqld ] ; then
	mysqlSocket=/run/mysqld/mysqld.sock
elif [ -d /var/run/mysqld ] ; then
	mysqlSocket=/var/run/mysqld/mysqld.sock
elif [ -d /var/lib/mysql ] ; then
	mysqlSocket=/var/lib/mysql/mysql.sock
else
	mysqlSocket=/var/run/mysqld/mysqld.sock
fi
#
# End of User Configuration
#
if [ -f /usr/bin/less ] ; then
	MORE=/usr/bin/less
else
	MORE=/usr/bin/more
fi
usage()
{
echo "Press ENTER for options, Cntrl C to quit" 1>&2
read key
$MORE <<EOF
Usage: svctool [OPTION]

Known values for OPTION are:

--smtp=Port --qbase=queue_path --qcount=N --qstart=I
  --servicedir=service_path
  [--cntrldir=cntrl_path]
  --localip=a --maxdaemons=m --maxperip=i
  [--no-multi]
  [--mysqlhost=mysqlhost --mysqluser=mysqluser --mysqlpass=mysqlpass]
  [--persistdb]
  [--dnscheck]
  [--helofqdn --helocheck]
  [--fsync --syncdir]
  [--qregex]
  [--memory=b]
  [--dmemory=c]
  [--databytes=d]
  [--overquota_mailsize=o]
  [--domainlimits]
  [--authsmtp --forceauthsmtp --authall]
  [--chkrecipient --chkrelay --cugmail]
  [--masquerade] [--antispoof]
  [--routes=smtp|qmtp|static]
  [--cname-lookup]
  [--min-free=M --skipsend --deliverylimit-count=D --deliverylimit-size=S]
  [--rbl=list]
  [--content-filter=c]
  [--virus-filter=v]
  [--qhpsi=q]
  [--spamfilter=spamfilter_args]
  [--logfilter=logfifo]
  [--rejectspam=r --spamexitcode=e --localfilter --remotefilter]
  [--paranoid --dmasquerade]
  [--remote-authsmtp=b]
  [--odmr]
  [--starttls]
  [--ssl]
  [--forcetls]
  [--shared-objects=0|1]
  [--use-dlmopen=0|1]
  [--dkverify=dk|dkim|both|none]
  [--dksign=dk|dkim|both|none --private_key=private_key]
  [--password-cache] [--query-cache]
  [--smtp-plugin]
  [--utf8]
  --default-domain=domain

 Installs a new queue with a SMTP Listener
  m              - Concurrency of connections to allow
  i              - Concurrency of connections to be allowed from a
                   single ip address
  a              - IP Address to listen
  N              - No of Queues
  I              - Numeral Prefix of first queue (i.e 1 for /var/indimail/queue/queue1)
  M              - Minimum Disk Space to maintain in queue after which
                   Temporary error will be returned
  b              - Max Memory that SMTP can allocate
  c              - Max Memory that qmail-daemon can allocate
  d              - Max size of email that can be submitted to SMTP or
                   injected locally
  D              - Max deliveries allowed per day for a user
  S              - Max sum total size of mails allowed per day for a user
  o              - Max size of mails to accept after user is overquota
  no-multi       - Do not set QMAILQUEUE to qmail-multi
  Port           - Bind on this port for SMTP
  service_path   - Path where supervise scripts will be installed
  queue_path     - Path where the queues are installed. If this is different from
                   /var/indimail appropriate links will be created in
                   /var/indimail
  cntrl_path     - Path where Qmail control files are stored
  domainlimits   - Apply Domain Limits configured by vmoddomlimits(1)
  chkrecipient   - Perform a User Status query before accepting mails
                   (qmail-smtpd)
  cugmail        - Allow only local valid senders to use SMTP.
  antispoof      - Turn on antispoofing code
  authsmtp       - Enable Authenticated SMTP 
  forceauthsmtp  - Enforce Authenticated SMTP before accepting MAIL FROM
  authall        - Accept mails to both remote & local domains only after
                   AUTH SMTP or POP/IMAP before SMTP
  chkrelay       - Accept mails to remote domains only after AUTH SMTP or
                   POP/IMAP before SMTP (closed relay)
  qregex         - Use regular expressions for matching entries in
                   badmailfrom, badrcptto, blackholedsenders, spamignore
                   relaymailfrom, authdomains, chkuserdomains
  q              - Full path to an external virus scanner (like clamdscan)
  v              - Enable Virus/Attachment scanner. v can have following values
                   1 - Internal Scanner
                   2 - Internal + External + Attachment Scan
                   3 - Internal + Attachment Scan
                   4 - External + Attachment Scan
                   5 - External Scanner
                   6 - Attachment Scan
  content-filter - Enable content filtering against regex in bodycheck control
                   file or the filename given as argument to content-filter
  c              - Optional filename passed to content-filter argument
  spamfilter     - Spamfilter program along with arguments
  logfifo        - Capture additional status message from spamfilter in 
                   qmail-logfifo logfile via logfifo
  r              - Mails get rejected as spam if exit status of spamfilter
                   equals the value of spamexitcode. r can have following values
                   0 - Do not reject SPAM mails
                   1 - Bounce SPAM Mails.
                   2 - Blackhole SPAM Mails
  e              - Exit value of spamfilter that should be treated as spam
  localfilter    - enable filtering of mails to qmail-local
  remotefilter   - enable filtering of mails to qmail-remote
  routes         - Perform SMTPROUTE / QMTPROUTE / static routing
  cname-lookup   - Perform CNAME lookup for recipient host in qmail-remote
  masquerade     - Allow user to change Mail From when using authenticated smtp
  rbl            - Deploy RBL lookups
  skipsend       - Skip creation of send script
  fsync          - Sync files and directories when writing files
  syncdir        - Use BSD style sync semantics for flushing directories
  dnscheck       - Check if mails can be sent to the sender domain 
                   (domain should have a proper MX record)
  helofqdn       - Enforce . in the argument to HELO/EHLO
  helocheck      - Check validity of HELO domain
                   (domain should have a proper MX record)
  b              - Authenticated SMTP method to use by qmail-remote (plain, login, cram-md5)
  paranoid       - Paranoid hostaccess check
  dmasquerade    - Allow domains to be masqueraded from known IPs
  default-domain - default domain name for which this host will handle mails
  mysqlhost      - MySQL Host having authentication tables
  mysqluser      - Username for connecting to mysql
  mysqlpass      - Passwd for connecting to mysql
  odmr           - Setup SMTP for ODMR (On Demand Mail Relay)
  private_key    - Path to Private key created by dknewkey
  starttls       - Advertise STARTTLS capability
  forcetls       - Force client to issue STARTTLS
  ssl            - Use SSL encrypted communication
  persistdb      - Enables qmail-lspawn to have persistent MySQL connection and set
                   PWSTRUCT environment variable. This eliminates the need for
                   vdelivermail to make a MySQL connection and hence improves
                   delivery times.
  password-cache - Enable caching of passwords (auth smtp)
  query-cache    - Enable caching of queries   (auth smtp)
  shared-objects - Enabled tcpserver plugins, 0 - disabled, 1 - enabled
  use-dlmopen    - Use dlmopen() instead of dlopen() to load shared objects
  smtp-plugin    - Enable SMTP Plugin support
  utf8           - Enable Email Address Internationalization Support (SMTPUTF8)

--delivery=ident --qbase=queue_path --qcount=N --qstart=I
  --servicedir=service_path
  [--cntrldir=cntrl_path]
  [--no-multi]
  [--mysqlhost=mysqlhost --mysqluser=mysqluser --mysqlpass=mysqlpass]
  [--persistdb]
  [--fsync --syncdir]
  [--qregex]
  [--dmemory=c]
  [--overquota_mailsize=o]
  [--domainlimits]
  [--routes=smtp|qmtp|static]
  [--cname-lookup]
  [--min-free=M --deliverylimit-count=D --deliverylimit-size=S]
  [--logfilter=logfifo]
  [--rejectspam=r --spamexitcode=e --localfilter --remotefilter]
  [--dkverify=dk|dkim|both|none]
  [--dksign=dk|dkim|both|none --private_key=private_key]
  [--remote-authsmtp=b]
  [--ssl]
  [--utf8]
  --default-domain=domain

 Installs a new queue with a delivery daemon
  N              - No of Queues
  I              - Numeral Prefix of first queue (i.e 1 for /var/indimail/queue/queue1)
  M              - Minimum Disk Space to maintain in queue after which
                   Temporary error will be returned
  c              - Max Memory that qmail-daemon can allocate
  D              - Max deliveries allowed per day for a user
  S              - Max sum total size of mails allowed per day for a user
  o              - Max size of mails to accept after user is overquota
  no-multi       - Do not set QMAILQUEUE to qmail-multi
  service_path   - Path where supervise scripts will be installed
  queue_path     - Path where the queues are installed. If this is different from
                   /var/indimail appropriate links will be created in
                   /var/indimail
  cntrl_path     - Path where Qmail control files are stored
  domainlimits   - Apply Domain Limits configured by vmoddomlimits(1)
  qregex         - Use regular expressions for matching entries in
                   badmailfrom, badrcptto, blackholedsenders, spamignore
                   relaymailfrom, authdomains, chkuserdomains
  spamfilter     - Spamfilter program along with arguments
  logfifo        - Capture additional status message from spamfilter in 
                   qmail-logfifo logfile via logfifo
  r              - Mails get rejected as spam if exit status of spamfilter
                   equals the value of spamexitcode. r can have following values
                   0 - Do not reject SPAM mails
                   1 - Bounce SPAM Mails.
                   2 - Blackhole SPAM Mails
  e              - Exit value of spamfilter that should be treated as spam
  localfilter    - enable filtering of mails to qmail-local
  remotefilter   - enable filtering of mails to qmail-remote
  routes         - Perform SMTPROUTE / QMTPROUTE / static routing
  cname-lookup   - Perform CNAME lookup for recipient host in qmail-remote
  fsync          - Sync files and directories when writing files
  syncdir        - Use BSD style sync semantics for flushing directories
  paranoid       - Paranoid hostaccess check
  dmasquerade    - Allow domains to be masqueraded from known IPs
  default-domain - default domain name for which this host will handle mails
  mysqlhost      - MySQL Host having authentication tables
  mysqluser      - Username for connecting to mysql
  mysqlpass      - Passwd for connecting to mysql
  private_key    - Path to Private key created by dknewkey
  persistdb      - Enables qmail-lspawn to have persisten MySQL connection and set
                   PWSTRUCT environment variable. This eliminates the need for
                   vdelivermail to make a MySQL connection and hence improves
                   delivery times.
  b              - Authenticated SMTP method to use by qmail-remote (plain, login, cram-md5)
  ssl            - Use SSL encrypted communication in qmail-remote
  utf8           - Enable Email Address Internationalization Support (SMTPUTF8)

--queueParam=dir --qbase=queue_path --qcount=N --qstart=I
  [--cntrldir=cntrl_path]
  [--min-free=M]
  [--no-multi]
  [--fsync --syncdir]
  [--qregex]
  [--content-filter=c]
  [--virus-filter=v]
  [--qhpsi=q]
  [--spamfilter=spamfilter_args]
  [--logfilter=logfifo]
  [--rejectspam=r --spamexitcode=e --localfilter --remotefilter]
  [--dkverify=dk|dkim|both|none]
  [--dksign=dk|dkim|both|none --private_key=private_key]

 Installs a new queue without a SMTP Listener
  dir            - dir where to install queuedef environment variable directory
  queue_path     - Path where the queues are installed. If this is different from
                   /var/indimail appropriate links will be created in
                   /var/indimail
  N              - No of Queues
  I              - Numeral Prefix of first queue (i.e 1 for /var/indimail/queue/queue1)
  cntrl_path     - Path where Qmail control files are stored
  M              - Minimum Disk Space to maintain in queue after which
                   Temporary error will be returned
  no-multi       - Do not set QMAILQUEUE to qmail-multi
  qregex         - Use regular expressions for matching entries in
                   badmailfrom, badrcptto, blackholedsenders, spamignore
                   relaymailfrom, authdomains, chkuserdomains
  q              - Full path to an external virus scanner (like clamdscan)
  v              - Enable Virus/Attachment scanner. v can have following values
                   1 - Internal Scanner
                   2 - Internal + External + Attachment Scan
                   3 - Internal + Attachment Scan
                   4 - External + Attachment Scan
                   5 - External Scanner
                   6 - Attachment Scan
  content-filter - Enable content filtering against regex in bodycheck control
                   file or the filename given as argument to content-filter
  c              - Optional filename passed to content-filter argument
  spamfilter     - Spamfilter program along with arguments
  logfifo        - Capture additional status message from spamfilter in 
                   qmail-logfifo logfile via logfifo
  r              - Mails get rejected as spam if exit status of spamfilter
                   equals the value of spamexitcode. r can have following values
                   0 - Do not reject SPAM mails
                   1 - Bounce SPAM Mails.
                   2 - Blackhole SPAM Mails
  e              - Exit value of spamfilter that should be treated as spam
  fsync          - Sync files and directories when writing files
  syncdir        - Use BSD style sync semantics for flushing directories
  private_key    - Path to Private key created by dknewkey

--greylist=port --min-resend-min=m --resend-win-hr=g --timeout-days=t
  --context-file=f --save_interval=s --whitelist=w --hash-size=s
  --localip=a --use-greydaemon --servicedir=service_path

  Installs a new Greylist Daemon
  a              - IP Address to listen
  Port           - Bind on this port for qmail-greyd
  service_path   - Path where supervise scripts will be installed
  m              - Minimum resend time after which mail will be accepted
  g              - Window in which mail must be seen
  t              - Max period for a mail to be received after which IP will be removed
                   from whitelist
  s              - Size of hash table (0 to disable hashing)
  context_file   - File in which context information is saved for startup
  save_interval  - Time interval in which context file gets saved
  whitelist      - List of whitelisted IP
  use-greydaemon - Use John Levine's greydaemon

--tlsa=port --timeout-days=t --context-file=f --save_interval=s --whitelist=w
  --hash-size=s --localip=a --servicedir=service_path

  Installs a new qmail-daned TLSA verification Daemon
  a              - IP Address to listen
  Port           - Bind on this port for qmail-greyd
  service_path   - Path where supervise scripts will be installed
  t              - Max period for a mail to be received after which IP will be removed
                   from whitelist
  s              - Size of hash table (0 to disable hashing)
  context_file   - File in which context information is saved for startup
  save_interval  - Time interval in which context file gets saved
  whitelist      - List of whitelisted IP

--qmtp=Port --qbase=queue_path --qcount=N --qstart=I
  --servicedir=service_path
  [--cntrldir=cntrl_path]
  --localip=a --maxdaemons=m --maxperip=i
  [--fsync --syncdir]
  [--memory=b --min-free=M]
  [--databytes=d]
  [--qhpsi=q]
  [--spamfilter=spamfilter_args]
  [--logfilter=logfifo]
  [--rejectspam=r --spamexitcode=e]
  [--dkverify=dk|dkim|both|none]
  [--dksign=dk|dkim|both|none --private_key=private_key]

 Installs a new queue with a QMTP Listener
  m              - Concurrency of connections to allow
  i              - Concurrency of connections to be allowed from a
                   single ip address
  a              - IP Address to listen
  N              - No of Queues
  I              - Numeral Prefix of first queue (i.e 1 for /var/indimail/queue/queue1)
  M              - Minimum Disk Space to maintain in queue after which
                   Temporary error will be returned
  b              - Max Memory that QMTP can allocate
  d              - Max size of email that can be submitted to SMTP or
                   injected locally
  Port           - Bind on this port for QMTP
  service_path   - Path where supervise scripts will be installed
  queue_path     - Path where the queues are installed. If this is different from
                   /var/indimail appropriate links will be created in
                   /var/indimail
  cntrl_path     - Path where Qmail control files are stored
  fsync          - Sync files and directories when writing files
  syncdir        - Use BSD style sync semantics for flushing directories
  q              - Full path to an external virus scanner (like clamdscan)
  spamfilter     - Spamfilter program along with arguments

  logfifo        - Capture additional status message from spamfilter in 
                   qmail-logfifo logfile via logfifo
  r              - Mails get rejected as spam if exit status of spamfilter
                   equals the value of spamexitcode. r can have following values
                   0 - Do not reject SPAM mails
                   1 - Bounce SPAM Mails.
                   2 - Blackhole SPAM Mails
  e              - Exit value of spamfilter that should be treated as spam
  private_key    - Path to Private key created by dknewkey

--qmqp=Port --qbase=queue_path --qcount=N --qstart=I
  --servicedir=service_path 
  [--cntrldir=cntrl_path]
  --localip=a --maxdaemons=m --maxperip=i
  [--fsync --syncdir]
  [--memory=b --min-free=M]
  [--qhpsi=q]
  [--spamfilter=spamfilter_args]
  [--logfilter=logfifo]
  [--rejectspam=r --spamexitcode=e]
  [--dkverify=dk|dkim|both|none]
  [--dksign=dk|dkim|both|none --private_key=private_key]

 Installs a new queue with a QMQP Listener
  m              - Concurrency of connections to allow
  i              - Concurrency of connections to be allowed from a
                   single ip address
  a              - IP Address to listen
  N              - No of Queues
  I              - Numeral Prefix of first queue (i.e 1 for /var/indimail/queue/queue1)
  M              - Minimum Disk Space to maintain in queue after which
                   Temporary error will be returned
  b              - Max Memory that QMTP can allocate
  Port           - Bind on this port for QMTP
  service_path   - Path where supervise scripts will be installed
  queue_path     - Path where the queues are installed. If this is different from
                   /var/indimail appropriate links will be created in
                   /var/indimail
  cntrl_path     - Path where Qmail control files are stored
  fsync          - Sync files and directories when writing files
  syncdir        - Use BSD style sync semantics for flushing directories
  q              - Full path to an external virus scanner (like clamdscan)
  spamfilter     - Spamfilter program along with arguments

  logfifo        - Capture additional status message from spamfilter in 
                   qmail-logfifo logfile via logfifo
  r              - Mails get rejected as spam if exit status of spamfilter
                   equals the value of spamexitcode. r can have following values
                   0 - Do not reject SPAM mails
                   1 - Bounce SPAM Mails.
                   2 - Blackhole SPAM Mails
  e              - Exit value of spamfilter that should be treated as spam
  private_key    - Path to Private key created by dknewkey

--imap=Port --servicedir=service_path
  --localip=a --maxdaemons=m --maxperip=i
  --default-domain=domain
  [--domainlimits --nolastauth]
  [--proxy=destport]
  [--infifo=fifo_path]
  [--legacyserver]
  [--postmaster=user[@domain]]
  [--common_name=CN]
  [--query-cache]
  [--ssl|--tlsprog|--starttls]

  Installs a new IMAP4 Listner
  Port           - Bind on this port for IMAP
  service_path   - Path where supervise scripts will be installed
  domainlimits   - Apply Domain Limits configured by vmoddomlimits(1)
  nolastauth     - Do not update lastauth
  proxy          - Install as a proxy and connect to actual imap on destport
  legacyserver   - To be set if destination IMAP server is not Indimail's IMAP server
  fifo_path      - Install fifo specified by this path
                   (e.g. /var/indimail/inquery/infifo)
  postmaster     - name of the user who will be the contact for Certificates.
  common_name    - Common Name (CN) for server
  query-cache    - Enable caching of queries
  tlsprog        - External progam to enable TLS session
  starttls       - Advertise STARTTLS capability
  ssl            - Use SSL encrypted communication
  m              - Concurrency of connections to allow
  i              - Concurrency of connections to be allowed from a
                   single ip address
  a              - IP Address to listen
  default-domain - default domain name for which this host will handle mails

--pop3=Port --servicedir=service_path
  --localip=a --maxdaemons=m --maxperip=i
  --default-domain=domain
  [--domainlimits --nolastauth]
  [--proxy=destport]
  [--legacyserver]
  [--postmaster=user[@domain]]
  [--common_name=CN]
  [--query-cache]
  [--ssl|--tlsprog|--starttls]

  Installs a new POP3 Listner
  Port           - Bind on this port for POP3
  service_path   - Path where supervise scripts will be installed
  domainlimits   - Apply Domain Limits configured by vmoddomlimits(1)
  nolastauth     - Do not update lastauth
  proxy          - Install as a proxy
  legacyserver   - To be set if destination POP3 server is not Indimail's POP3 server
  postmaster     - name of the user who will be the contact for Certificates.
  common_name    - Common Name (CN) for server
  query-cache    - Enable caching of queries
  tlsprog        - External progam to enable TLS session
  starttls       - Advertise STARTTLS capability
  ssl            - Use SSL encrypted communication
  m              - Concurrency of connections to allow
  i              - Concurrency of connections to be allowed from a
                   single ip address
  a              - IP Address to listen
  default-domain - default domain name for which this host will handle mails

--showctl=DIR

  Shows Qmail Control Information for Control Directory at DIR

--dumpconfig --servicedir=service_path --cntrldir=cntrl_path

  Dumps all service configuration for Supervise Scripts, control files and software information
  service_path - Path where supervise scripts will be installed
  cntrl_path   - Path where Qmail control files are stored

--queuefix=queue_path

  Fix Qmail Queue where queue_path is the absolute path of a queue

--rmsvc=service_name

  Disable supervise scripts for service
  service_name   - name of service with full path
                   e.g. (/service/qmail-smtpd.25)
                   (give multiple services enclosed in double quotes)
                   "/service/qmail-smtpd.25 /service/qmail-imapd.143"

--ensvc=service_name

  Enable supervise scripts for service
  service_name   - name of service with full path
                   e.g. (/service/.qmail-smtpd.25)
                   (give multiple services enclosed in double quotes)
                   "/service/.qmail-smtpd.25 /service/.qmail-imapd.143"

--refreshsvc=service_name
  [--run-file-only]

  Enable supervise scripts for service
  service_name   - name of service with full path
                   e.g. (/service/.qmail-smtpd.25)
                   (give multiple services enclosed in double quotes)
                   "/service/.qmail-smtpd.25 /service/.qmail-imapd.143"
                   service_name can be "all" to act on all services
  run-file-only  - Recreate run files but not variables
  NOTE: if the file .norefreshsvc is present in the variable or the config
  directory, refresh is skipped

--norefreshsvc="0|1 service_name"

  Disable/Enable auto refresh of supervise scripts for service
  0              - Disable autorefresh (create .norefreshsvc in variables directory)
  1              - Enable  autorefresh (delete .norefreshsvc in variables directory)
  service_name   - name of service with full path
                   e.g. (/service/.qmail-smtpd.25)
                   service_name can be "all" to act on all services

--enable-service name1 name2 ..

  Add a service to be started at system boot. The unit file for the service should exist
  name1 name2 .. - name of a service or list of services to be added
                   This should be a SYSV style service, systemd, event.d unit file

--disable-service name1 name2 ..

  Remove a service to be started at system boot. The unit file for the service should exist
  name1 name2 .. - name of a service or list of services to be removed
                   This should be a SYSV style service, systemd, event.d unit file

--inlookup=fifo_path --threads=N
  --servicedir=service_path
  --domainlimits
  [--activeDays=A]
  [--use-btree]
  [--max-btree-count=max_nodes]
  [--routes=smtp|qmtp|static]
  [--cntrldir=cntrl_path]
  [--password-cache] [--query-cache]

  Installs a new Fifo Server
  fifo_path      - Install fifo specified by this path
                   (e.g. /var/indimail/inquery/infifo)
  N              - No of parallel inlookup threads to spawn
  A              - Max days for which a user has been active
  service_path   - Path where supervise scripts will be installed
  cntrl_path     - Path where Qmail control files are stored
  domainlimits   - Apply Domain Limits configured by vmoddomlimits(1)
  use-btree      - Use Binary Tree algorithm to search for User records
  max_nodes      - Maximum number of Binary Nodes to allow
  password-cache - Enable caching of passwords
  query-cache    - Enable caching of queries
  routes         - Perform SMTPROUTE / QMTPROUTE / static routing

--pwdlookup=socket_path --threads=N --timeout=t
  [--mysqlhost=mysqlhost --mysqluser=mysqluser --mysqlpass=mysqlpass]
  [--mysqlport=port | --mysqlsocket=socket]
  --servicedir=service_path

  Installs a new Name Service Password Lookup Daemon
  socket_path    - Use socket_path as communication between
                   NSS clients and NSS Password Lookup server
  N              - No of parallel pwdlookup threads to spawn
  t              - Timeout wait for new Password Request
  mysqlhost      - MySQL Host having authentication tables
  mysqluser      - Username for connecting to mysql
  mysqlpass      - Passwd for connecting to mysql
  mysqlport      - Port for connecting to mysql
  mysqlsocket    - Unix Domain Socket for connecting to mysql
  service_path   - Path where supervise scripts will be installed

--indisrvr=Port --mysqlhost=mysqlhost --mysqluser=mysqluser --mysqlpass=mysqlpass
  --localip=a --maxdaemons=m --maxperip=i
  --domainlimits
  --avguserquota=quota --hardquota=quota
  --base_path=path --servicedir=service_path

  Installs a new Indi Admin Server
  Port           - TCP/IP port on which to bind
  mysqlhost      - MySQL Host having authentication tables
  mysqluser      - Username for connecting to mysql
  mysqlpass      - Passwd for connecting to mysql
  avguserquota   - Average Usage per user in Bytes
  hardqutoa      - Max Quota for a user
  base_path      - Default Filesystem Path for user mailbox creation
  m              - Concurrency of connections to allow
  i              - Concurrency of connections to be allowed from a
                   single ip address
  a              - IP Address to listen
  service_path   - Path where supervise scripts will be installed
  domainlimits   - Apply Domain Limits configured by vmoddomlimits(1)

--mysql=mysqlport --mysqlPrefix=mysqlPrefix --databasedir=databasedir
  --config=conf_file --servicedir=service_path
  [--mysqlsocket=socket]
  [--default-domain=domain]

  Installs a new MySQL Server
  mysqlport      - Install MySQL to listen on this port
  mysqlPrefix    - Installation Prefix for mysql
  databasedir    - Directory containing the Database and Logs
  mysqlsocket    - Unix Domain Socket for connecting to mysql
  config         - MySQL Configuration file (e.g. $sysconfdir/indimail.cnf)
  service_path   - Path where supervise scripts will be installed
  default-domain - default domain name for which this host will handle mails

--fetchmail --qbase=queue_path --qcount=N --qstart=I --servicedir=service_path
  [--cntrldir=cntrl_path]
  --default-domain=domain
  [--silent]
  [--fsync --syncdir]
  [--domainlimits]
  [--memory=b --min-free=M]
  [--spamfilter=spamfilter_args]
  [--logfilter=logfifo]
  [--rejectspam=r --spamexitcode=e]
  [--qhpsi=q]
  [--dkverify=dk|dkim|both|none]

  Install Fetchmail Server
  queue_path     - Path where the queues are installed. If this is different from
                   /var/indimail appropriate links will be created in
                   /var/indimail
  N              - No of Queues
  I              - Numeral Prefix of first queue (i.e 1 for /var/indimail/queue/queue1)
  M              - Minimum Disk Space to maintain in queue after which
                   Temporary error will be returned
  b              - Max Memory that Fetchmail can allocate
  service_path   - Path where supervise scripts will be installed
  cntrl_path     - Path where Qmail control files are stored
  fsync          - Sync files and directories when writing files
  syncdir        - Use BSD style sync semantics for flushing directories
  silent         - Display minimal output on stdout
  domainlimits   - Apply Domain Limits configured by vmoddomlimits(1)
  q              - Full path to an external virus scanner (like clamdscan)
  spamfilter     - Spamfilter program along with arguments
  logfifo        - Capture additional status message from spamfilter in 
                   qmail-logfifo logfile via logfifo  
  r              - Mails get rejected as spam if exit status of spamfilter
                   equals the value of spamexitcode. r can have following values
                   0 - Do not reject SPAM mails
                   1 - Bounce SPAM Mails.
                   2 - Blackhole SPAM Mails
  e              - Exit value of spamfilter that should be treated as spam
  default-domain - default domain name for which this host will handle mails

--qscanq --servicedir=service_path [--scanint=n]

  service_path - Path where supervise scripts will be installed
  n            - Scan interval for Virus scanning

--clamd --servicedir=service_path --clamdPrefix=clamdPrefix
  [--sysconfdir=sysconfdir]

  service_path - Path where supervise scripts will be installed
  clamdPrefix  - Installation Prefix for clamd
  sysconfdir   - Path for config files (scan.conf)

--poppass=Port --localip=a --setpassword=cmd --maxdaemons=m --maxperip=i
  --servicedir=service_path
  [--memory=b]
  [--certfile=certificate --ssl]
  Port           - TCP/IP port on which to bind
  m              - Concurrency of connections to allow
  i              - Concurrency of connections to be allowed from a
                   single ip address
  b              - Max Memory to allocate for poppassd
  a              - IP Address to listen
  cmd            - Path of a setpassword compatible program
  certficate     - Path to openssl certificate
  ssl            - Use SSL encrypted communication
  service_path - Path where supervise scripts will be installed

  Installs a new IndiMail poppassd Server

--udplogger=udp_port --servicedir=service_path --localip=1 --timeout=t
  Port         - UDP/IP port on which to bind
  a            - IP Address to listen
  t            - Timeout for reads
  service_path - Path where supervise scripts will be installed

--fifologger=fifo_path --servicedir=service_path
  fifo_path    - Path to a writeable fifo which can be used by
                 any application to log messages to qmail-logfifo
                 service
  service_path - Path where supervise scripts will be installed

--mrtg=htmldir --servicedir=service_path [--scanint=n]
  htmldir      - Path in /var/www/html directory
  service_path - Path where supervise scripts will be installed
  n            - Scan interval for mrtg command

--config=mysql|ssl_rsa|mysqldb|qmail|users|rmusers|clamd|foxhole|bogofilter|cert|add-boot|rm-boot
--config=add-alt|remove-alt|qselinux|iselinux
  [--postmaster=user[@domain]]
  [--common_name=CN]
  [--capath=ca_path_dir]
  [--certdir=certdir]
  [--default-domain=domain]
  [--mysqlPrefix=mysqlPrefix]
  [--mysqlhost=mysqlhost --mysqluser=mysqluser --mysqlpass=mysqlpass]
  [--mysqlport=port | --mysqlsocket=socket]
  [--databasedir=databasedir]
  [--use-grant]
  [--stdout]
  [--wipe]

  mysql          - Create $sysconfdir/indimail.cnf
  mysqldb        - Create an initidalized MySQL db for IndiMail
  ssl_rsa        - Create SSL/TLS Certs for MariaDB
  qmail          - Create default qmail control files
  users          - Create Internal System Users used by IndiMail
  rmusers        - Remove Internal System Users used by IndiMail
  clamd          - Create clamd configuration file
  bogofilter     - Create bogofilter.cf configuration file
  cert           - Generate SSL Certificate
  add-boot       - Add startup scripts for IndiMail to get started during boot
  rm-boot        - Remove Startup scripts to prevent IndiMail to get started after boot
  add-alt        - Install indiamil as default MTA
  remove-alt     - Remove indimail as the default MTA
  iselinux       - Enable selinux module for indimail
  qselinux       - Enable selinux module for indimail-mta
  postmaster     - name of the user who will recieve bounces on the local host.
                   This can also be a remote user i.e. &postmaster@indi.com
  common_name    - Common Name (CN) for server
  ca_path_dir    - Directory having CA certificate
  certdir        - Directory in which new certificates will be placed
  default-domain - default domain name for which this host will handle mails
  mysqlPrefix    - Installation Prefix for mysql
  mysqlhost      - MySQL Host having authentication tables
  mysqluser      - Username for connecting to mysql
  mysqlpass      - Passwd for connecting to mysql
  mysqlport      - Port for connecting to mysql
  mysqlsocket    - Unix Domain Socket for connecting to mysql
  databasedir    - Directory containing the Database and Logs
  use-grant      - Use the usual create user and grant statements for creating users
                   (implies --stdout)
  stdout         - Dump on the screen. Will not create a configuration
  wipe           - will wipe out users/assign (for config=qmail)

--check-install --servicedir=service_path --qbase=queue_path --qcount=N --qstart=I
  [--skip-sendmail]

  service_path  - Path where supervise scripts have been installed
  queue_path    - Path where the queues are installed.
  N             - No of Queues
  I             - Numeral Prefix of first queue (i.e 1 for /var/indimail/queue/queue1)
  skip-sendmail - Skip Checking sendmail paths in /usr/sbin and /usr/lib

--inittab --servicedir=service_path

  service_path - Path where supervise scripts will be installed

--svscanlog --servicedir=service_path [--initcmd=cmmd --scanint=n]

  service_path - Path where supervise scripts will be installed
  cmmd         - Program/Script to run instead of .svscan/run
  n            - Scan interval for svscan command

--backup=backupdir --servicedir=service_path --mysqlPrefix=mysqlPrefix

  mysqlPrefix  - Installation Prefix for mysql
  backupdir    - Directory to dump backup

--repair-tables
  Repair MySQL tables in /var/indimail/mysqldb/data

--mysqlupgrade --mysqlPrefix=mysqlPrefix
  mysqlPrefix  - Installation Prefix for mysql

--report=all| zddist| zdeferrals| zfailures| zoverall| zrecipients| zrhosts|
  zrxdelay| zsenders| zsendmail| zsuccesses| zsuids | zsmtp | zspam
  [--postmaster=user[@domain]]
  [--attach]
  [--logdir=multilog_base_dir]

  postmaster - name of the user who will recieve the report.
  attach     - zip and send the report as an attachment

--unshare
  Use unshare to mount private /etc/resolv.conf for using local dns

--down
  Create any of the above supervisor services in down state

--check-certs=[full path of certificate]
  Check certificate given as argument or
  Check IndiMail Certificates in $sysconfdir/certs without any arguments

--fixsharedlibs

  fix mysql shared library in $sysconfdir/control/mysql_lib

--help

  display this help and exit

--version

  output version information
EOF
exit $1
}

change_config()
{
if [ $# -ne 2 ] ; then
	echo "USAGE: change_config old_config_file new_config_file" 1>&2
	return 1
fi
conf_file=$1
temp_file=$2
if [ -f $conf_file ] ; then
	if ! cmp -s $conf_file $temp_file ; then
		echo "saving $temp_file as $conf_file.rpmnew"
		/bin/mv $temp_file "$conf_file".rpmnew
	else
		echo "$conf_file not changed" 1>&2
		/bin/rm -f $temp_file
	fi
else
	echo "Creating $conf_file"
	/bin/mv $temp_file $conf_file
fi
}

check_installation()
{
# check home
# check alias autoturn bin boot control doc etc lib libexec man \
#  modules plugins qscanq sbin share users
# check queues
# check users alias qmaild qmaill qmailp qmailq qmailr qmails mysql indimail qscand
# check groups qmail nofiles indimail qscand
# check IndiMail Installation Permission and Default MySQL Tables"
#       run instcheck
#       run install_tables
# check defaultdelivery"
# check service directory"
# check indimail startup (svscan) "
# check configured services"
# check mandatory services"
# check installed services"
# check Log Directories"
# check Firewall Rules"
# check Alias User"
# check Sendmail Status"
#
if [ $# -lt 5 ] ; then
	echo "USAGE: check_installation qbase queue_count first_queue_no supervise_dir verb" 1>&2
	return 1
fi
QUEUE_BASE=$1
NO_OF_QUEUES=$2
FIRST_QUEUE=$3
SERVICEDIR=$4
OK=1

if [ "$5" = "-v" ]; then
	VERB=y
else
	VERB=n
fi
echo "Checking IndiMail Home"
if [ ! -d "$DESTDIR"$QmailHOME ]; then
  echo "! Couldn't find qmail's home directory, "$DESTDIR"$QmailHOME!" 1>&2
else
  if [ "$VERB" = y ]; then
    echo ""$DESTDIR"$QmailHOME exists"
  fi
  echo "Checking Critical IndiMail directories"
  if [ -f "$DESTDIR"$QmailBinPrefix/vuserinfo ] ; then
    indimail_installed=1
    LIST1="alias autoturn bin qscanq sbin" # qmaildir/indimaildir
    LIST2="boot doc" # shareddir
    LIST3="control users" #sysoncdir
    LIST4="plugins modules" # /usr/lib/indimail
    #LIST="alias autoturn bin boot control doc etc lib libexec man modules plugins qscanq sbin share users"
  else
    indimail_installed=0
    LIST1="alias bin qscanq sbin"
    LIST2="boot doc"
    LIST3="control users"
    LIST4="plugins"
    #LIST="alias bin boot control doc etc lib man plugins qscanq sbin share users"
  fi
  for i in $LIST1; do
    echo $i
    if [ ! -d "$DESTDIR"$QmailHOME/$i -a ! -L "$DESTDIR"$QmailHOME/$i ]; then
      echo "! Couldn't find "$DESTDIR"$QmailHOME/$i!" 1>&2
      OK=0
    elif [ "$VERB" = y ]; then
      echo ""$DESTDIR"$QmailHOME/$i exists"
    fi
  done
  for i in $LIST2; do
    echo $i
    if [ ! -d "$DESTDIR"$shareddir/$i -a ! -L "$DESTDIR"$shareddir/$i ]; then
      echo "! Couldn't find "$DESTDIR"$shareddir/$i!" 1>&2
      OK=0
    elif [ "$VERB" = y ]; then
      echo ""$DESTDIR"$shareddir/$i exists"
    fi
  done
  for i in $LIST3; do
    echo $i
    if [ ! -d "$DESTDIR"$sysconfdir/$i -a ! -L "$DESTDIR"$sysconfdir/$i ]; then
      echo "! Couldn't find "$DESTDIR"$sysconfdir/$i!" 1>&2
      OK=0
    elif [ "$VERB" = y ]; then
      echo ""$DESTDIR"$sysconfdir/$i exists"
    fi
  done
  for i in $LIST4; do
    echo $i
    if [ ! -d "$DESTDIR"/usr/lib/indimail/$i -a ! -L "$DESTDIR"/usr/lib/indimail/$i ]; then
      echo "! Couldn't find "$DESTDIR"/usr/lib/indimail/$i!" 1>&2
      OK=0
    elif [ "$VERB" = y ]; then
      echo ""$DESTDIR"/usr/lib/indimail/$i exists"
    fi
  done
  echo $libexecdir
  if [ ! -d "$DESTDIR"$libexecdir ] ; then
      echo "! Couldn't find "$DESTDIR"$libexecdir!" 1>&2
      OK=0
  elif [ "$VERB" = y ]; then
    echo ""$DESTDIR"$libexecdir exists"
  fi
  echo "Checking IndiMail queues"
  QUEUE_NO=$FIRST_QUEUE
  COUNT=1
  while true
  do
    "$DESTDIR"$QmailBinPrefix/bin/queue-fix -N "$DESTDIR"$QUEUE_BASE/queue"$QUEUE_NO" > /dev/null 2>&1
    if [ $? -ne 0 ] ; then
      echo "status $? ! queue"$QUEUE_NO" should be fixed. Run queue-fix "$DESTDIR"$QUEUE_BASE/queue"$QUEUE_NO" !" 1>&2
      OK=0
    elif [ "$VERB" = y ]; then
      echo "queue "$DESTDIR"$QUEUE_BASE/queue"$QUEUE_NO" looks OK"
    fi
    if [ $COUNT -eq $NO_OF_QUEUES ] ; then
      break
    fi
    COUNT=`expr $COUNT + 1`
    QUEUE_NO=`expr $QUEUE_NO + 1`
  done
  "$DESTDIR"$QmailBinPrefix/bin/queue-fix -N "$DESTDIR"$QUEUE_BASE/nqueue > /dev/null 2>&1
  if [ $? -ne 0 ] ; then
    echo "status $? ! nqueue should be fixed. Run queue-fix "$DESTDIR"$QUEUE_BASE/nqueue !" 1>&2
    OK=0
  elif [ "$VERB" = y ]; then
    echo "queue "$DESTDIR"$QUEUE_BASE/nqueue looks OK"
  fi
fi

echo "Checking IndiMail users"
for i in alias qmaild qmaill qmailp qmailq qmailr qmails mysql indimail qscand; do
  echo $i
  case "$host" in
  *-*-darwin*)
    dscl . -list /Users/$i > /dev/null 2>&1
    if [ $? -ne 0 ]; then
      echo "! Couldn't find $i user in passwd database" 1>&2
      OK=0
    elif [ "$VERB" = y ]; then
      echo "$i user exists"
    fi
  ;;
  *)
    grep "^$i:" /etc/passwd >/dev/null
    if [ $? -ne 0 ]; then
      echo "! Couldn't find $i user in /etc/passwd" 1>&2
      OK=0
    elif [ "$VERB" = y ]; then
      echo "$i user exists"
    fi
    ;;
  esac
done

echo "Checking IndiMail groups"
for i in qmail nofiles indimail qscand; do
  echo $i
  case "$host" in
  *-*-darwin*)
    dscl . -list /Groups/$i > /dev/null 2>&1
    if [ $? -ne 0 ]; then
      echo "! Couldn't find $i group in group database" 1>&2
      OK=0
    elif [ "$VERB" = y ]; then
      echo "$i group exists"
    fi
  ;;
  *)
    grep "^$i:" /etc/group >/dev/null
    if [ $? -ne 0 ]; then
      echo "! Couldn't find $i group in /etc/group" 1>&2
      OK=0
    elif [ "$VERB" = y ]; then
      echo "$i group exists"
    fi
  ;;
  esac
done

echo "Checking IndiMail Installation Permission"
for i in indimail-mta daemontools ucspi-tcp
do
  if [ ! -x "$DESTDIR"$libexecdir/instcheck.$i ]; then
    echo "! Couldn't find "$DESTDIR"$libexecdir/instcheck.$i" 1>&2
    OK=0
  else
    if [ "$VERB" = y ]; then
      echo "instcheck.$i from $i is installed. Executing..."
    fi
    "$DESTDIR"$libexecdir/instcheck.$i "$DESTDIR"$QmailHOME
    if [ $? -ne 0 ]; then
      echo "instcheck.$i returned non-zero exit status. Check Installation"
      OK=0
    fi
  fi
done
if [ $indimail_installed -eq 1 ] ; then
  echo "Checking IndiMail Default MySQL Tables"
  if [ ! -x "$DESTDIR"$QmailBinPrefix/sbin/install_tables ]; then
    echo "! Couldn't find "$DESTDIR"$QmailBinPrefix/sbin/install_tables" 1>&2
    OK=0
  else
    if [ "$VERB" = y ]; then
      echo "install_tables from indimail is installed. Executing..."
    fi
    if [ ! -f /tmp/skip-install_tables ] ; then
      "$DESTDIR"$QmailBinPrefix/sbin/install_tables > /dev/null
      if [ $? -ne 0 ]; then
        echo "install_tables returned non-zero exit status. Check Installation" 1>&2
        OK=0
      fi
    fi
  fi
fi

echo "Checking defaultdelivery"
if [ ! -f "$DESTDIR"$CONTROLDIR/defaultdelivery ]; then
  echo "! Couldn't find "$DESTDIR"$CONTROLDIR/defaultdelivery" 1>&2
  OK=0
elif [ ! -s "$DESTDIR"$CONTROLDIR/defaultdelivery ]; then
  echo "! "$DESTDIR"$CONTROLDIR/defaultdelivery is empty" 1>&2
  OK=0
elif [ "$VERB" = y ]; then
  echo ""$DESTDIR"$CONTROLDIR/defaultdelivery looks OK"
fi

echo "Checking Service Directory"
if [ ! -d $servicedir ]; then
  echo "! $servicedir directory is missing" 1>&2
  OK=0
elif [ "$VERB" = y ]; then
  echo "$servicedir directory exists"
fi

echo "Checking IndiMail Startup (svscan)"
if [ -f /etc/init/svscan.conf -a -f /sbin/initctl ] ; then
  /sbin/initctl status svscan
  if [ $? -ne 0 ]; then
    echo "! svscan service not configured in upstart" 1>&2
    OK=0
  else
    echo "svscan service is configured to run via upstart"
  fi
  PS="ps -ax"
elif [ -d /etc/event.d -a -f /sbin/initctl ] ; then
  /sbin/initctl list svscan
  if [ $? -ne 0 ]; then
    echo "! svscan service not configured in upstart" 1>&2
    OK=0
  else
    echo "svscan service is configured to run via upstart"
  fi
  PS="ps -ax"
elif [ -f /lib/systemd/system/svscan.service -a -f /bin/systemctl ] ; then
  /bin/systemctl is-enabled svscan > /dev/null
  if [ $? -ne 0 ] ; then
    echo "! svscan service not configured in systemd" 1>&2
    OK=0
  else
    echo "svscan service is configured to run via systemd"
  fi
elif [ -f /usr/lib/systemd/system/svscan.service -a -f /bin/systemctl ] ; then
  /bin/systemctl is-enabled svscan > /dev/null
  if [ $? -ne 0 ] ; then
    echo "! svscan service not configured in systemd" 1>&2
    OK=0
  else
    echo "svscan service is configured to run via systemd"
  fi
elif [ -d /Library/LaunchDaemons ] ; then
  /bin/launchctl list org.indimail.svscan
  if [ $? -ne 0 ]; then
    echo "! svscan service not configured in launchd" 1>&2
    OK=0
  else
    echo "svscan service is configured to run via launchd" 1>&2
  fi
  PS="ps -ax"
else
  echo "Checking /etc/inittab"
  if [ -f /etc/inittab ]; then
    grep "^SV:" /etc/inittab >/dev/null
    if [ $? -ne 0 ]; then
      echo "! Couldn't find SV entry in inittab" 1>&2
      OK=0
    else
      grep "^SV:" /etc/inittab |grep respawn >/dev/null
      if [ $? -ne 0 ]; then
        echo "! SV entry in inittab is not set to respawn" 1>&2
        OK=0
      elif [ "$VERB" = y ]; then
        echo "svscan is configured to run via /etc/inittab"
      fi
    fi
    PS="ps -ax"
  else
    if [ -x /sbin/chkconfig -a -f /etc/init.d/svscan ] ; then
      /sbin/chkconfig --list svscan|grep on > /dev/null
      if [ $? -ne 0 ] ; then
      echo "! Couldn't find indimail referenced in any runlevel" 1>&2
        OK=0
      elif [ "$VERB" = y ]; then
        /sbin/chkconfig --list svscan|grep on
        echo "indimail service is configured to run through rc scripts"
      fi
    elif [ -f /etc/init.d/svscan ] ; then
      /bin/ls -l /etc/rc?.d/*/svscan > /dev/null 2>&1
      if [ $? -ne 0 ] ; then
        echo "! Couldn't find indimail referenced in any runlevel" 1>&2
        OK=0
      elif [ "$VERB" = y ]; then
        /sbin/chkconfig --list svscan|grep on
        echo "indimail service is configured to run through rc scripts"
      fi
    fi
    grep "qmailctl start" /etc/rc.local >/dev/null
    if [ $? -ne 0 ]; then
      echo "! Couldn't find 'qmailctl start' in /etc/rc.local" 1>&2
      grep "svscan /service" /etc/rc.local >/dev/null
      if [ $? -ne 0 ]; then
        echo "! Couldn't find 'svscan /service' in /etc/rc.local" 1>&2
        OK=0
      elif [ "$VERB" = y ]; then
        echo "svscan /service is configured to run via /etc/rc.local"
      fi
    elif [ "$VERB" = y ]; then
      echo "'qmailctl start' is in /etc/rc.local"
    fi
    PS="ps -waux"
  fi
  echo "Checking svscan"
  SVRUN=`$PS | grep "svscan $servicedir" | grep -v grep`
  if [ -z "$SVRUN" ]; then
    echo "'! svscan $servicedir' doesn't seem to be running" 1>&2
    OK=0
  elif [ "$VERB" = y ]; then
    echo "svscan $servicedir is running"
  fi
fi

echo "Checking mandatory services"
if [ -x "$DESTDIR"$QmailBinPrefix/sbin/nssd ] ; then
LIST="pwdlookup"
fi
LIST="$LIST qmail-send.25 qmail-smtpd.25 qmail-smtpd.366 qmail-smtpd.465 qmail-smtpd.587"
LIST="$LIST qmail-daned.1998 qmail-logfifo udplogger.3000 qscanq greylist.1999"
if [ $indimail_installed -eq 1 ] ; then
LIST="$LIST inlookup.infifo indisrvr.4000 mysql.3306 qmail-poppass.106 mrtg"
LIST="$LIST qmail-imapd.143 qmail-pop3d.110 qmail-imapd-ssl.993 qmail-pop3d-ssl.995"
LIST="$LIST proxy-imapd.4143 proxy-imapd-ssl.9143 proxy-pop3d.4110 proxy-pop3d-ssl.9110"
fi
if [ -x "$DESTDIR"$QmailBinPrefix/sbin/clamd -o -x "$DESTDIR"$QmailBinPrefix/bin/freshclam ] ; then
LIST="$LIST clamd freshclam"
elif [ -x /usr/sbin/clamd -o -x /usr/bin/freshclam ] ; then
LIST="$LIST clamd freshclam"
fi
for i in $LIST ; do
  echo $i
  if [ ! -d $servicedir/$i ]; then
    echo "! $servicedir/$i directory is missing" 1>&2
    OK=0
  fi
done

echo "Checking installed services"
SVCDIRS="`ls -A $servicedir`"
for i in $SVCDIRS; do
  if [ " $i" = " .svscan" -o " $i" = " .svlock" ] ; then
    continue
  fi
  echo $i
  interp=`head -1 $servicedir/$i/run|/bin/cat -vet`
  if [ ! -f $servicedir/$i/run ]; then
    echo "! $servicedir/$i/run file is missing" 1>&2
    OK=0
  elif [ " $interp" != " #!/bin/sh$" -a " $interp" != " #!/bin/bash$" -a " $interp" != " #!/usr/bin/sh$" -a " $interp" != " #!/usr/bin/bash$" ] ; then
    echo "! $servicedir/$i/run has bad magic cookie [$interp]" 1>&2
    echo "...try: dos2unix $servicedir/$i/run" 1>&2
    OK=0
  elif [ ! -x $servicedir/$i/run ]; then
    echo "! $servicedir/$i/run file is not executable" 1>&2
    OK=0
  elif [ "$VERB" = y ]; then
    echo "$servicedir/$i/run looks OK"
  fi
  if [ ! -d $servicedir/$i/log ] ; then
    echo "No log for $servicedir/$i" 1>&2
    continue
  fi
  if [ ! -f $servicedir/$i/log/run ]; then
    echo "! $servicedir/$i/log/run file is missing" 1>&2
    OK=0
  elif [ " $interp" != " #!/bin/sh$" -a " $interp" != " #!/bin/bash$" -a " $interp" != " #!/usr/bin/sh$" -a " $interp" != " #!/usr/bin/bash$" ] ; then
    echo "! $servicedir/$i/log/run has bad magic cookie [$interp]" 1>&2
    echo "...try: dos2unix $servicedir/$i/log/run" 1>&2
    OK=0
  elif [ ! -x $servicedir/$i/log/run ]; then
    echo "! $servicedir/$i/log/run file is not executable" 1>&2
    OK=0
  elif [ "$VERB" = y ]; then
    echo "$servicedir/$i/log/run looks OK"
  fi
done

echo "Checking Log Directories"
if [ -h $LOGDIR ] ; then
  logdir=`ls -ld $LOGDIR |awk '{print $11}'`
else
  logdir=$LOGDIR
fi
LOGDIRS="`ls -d $logdir/* 2>/dev/null`"
for i in $LOGDIRS; do
  if [ $i = $logdir"/services.log" ] ; then
    continue
  fi
  echo $i
  perm="`ls -ld $i|awk '{print $1}'|cut -d. -f1`"
  if [ ! -d $i ]; then
    echo "! $i looks strange" 1>&2
    echo "...try: rm -f $i" 1>&2
    OK=0
  elif [ "`ls -ld $i|awk '{print $3}'`" != "qmaill" ]; then
    echo "! $i has wrong owner, should be qmaill" 1>&2
    echo "...try: chown qmaill $i" 1>&2
    OK=0
  elif [ "$perm" != "drwxr-xr-x" -a "$perm" != "drwxr-sr-x" ]; then
    echo "! $i has wrong mode, should be 755" 1>&2
    echo "...try: chmod 755 $i" 1>&2
    OK=0
  elif [ "$VERB" = y ]; then
    echo "$i looks OK"
  fi
done

echo "Checking Firewall Rules"
if [ ! -f "$DESTDIR"$sysconfdir/tcp/tcp.smtp ]; then
  echo "! "$DESTDIR"$sysconfdir/tcp/tcp.smtp is missing" 1>&2
  echo "...try: echo '127.:allow,RELAYCLIENT=\"\"' >> "$DESTDIR"$sysconfdir/tcp/tcp.smtp" 1>&2
  OK=0
elif [ "$VERB" = y ]; then
  echo ""$DESTDIR"$sysconfdir/tcp/tcp.smtp exists"
fi

if [ ! -f "$DESTDIR"$sysconfdir/tcp/tcp.smtp.cdb ]; then
  echo "! "$DESTDIR"$sysconfdir/tcp/tcp.smtp.cdb is missing" 1>&2
  echo "...try: "$DESTDIR"$QmailBinPrefix/bin/qmailctl cdb" 1>&2
  OK=0
elif [ "$VERB" = y ]; then
  echo ""$DESTDIR"$sysconfdir/tcp/tcp.smtp.cdb exists"
fi

echo "Checking Alias User"
case $host in
  *-*-darwin*)
    AHOME=`dscl . -read /Users/alias|grep NFSHomeDi|awk '{print $2}'`
  ;;
  *)
    AHOME=`grep "^alias:" /etc/passwd | awk -F: '{print $6}'`
  ;;
esac
if [ -z "$AHOME" ]; then
  echo "! Couldn't find user alias's home directory" 1>&2
  OK=0
else
  for i in root postmaster mailer-daemon; do
  echo $i
    if [ ! -f "$DESTDIR"$AHOME/.qmail-$i ]; then
      echo "! Alias for $i is missing" 1>&2
      echo "...try: echo me > "$DESTDIR"$AHOME/.qmail-$i" 1>&2
      OK=0
    elif [ "$VERB" = y ]; then
      echo "$i alias exists"
    fi
  done
fi

echo "Checking Sendmail Status"
if netstat -a | grep smtp | grep -i listen >/dev/null; then
  if $PS | grep sendmail | grep -v grep >/dev/null; then
    echo "! Sendmail is still running" 1>&2
    echo "...try: $RCDIR/init.d/sendmail stop" 1>&2
    OK=0
  elif "$DESTDIR"$QmailBinPrefix/bin/svok $servicedir/qmail-smtpd.25; then
    if [ "$VERB" = y ]; then
      echo "$servicedir/qmail-smtpd.25 is running"
    fi
  else
    echo "! Something is listening on port 25 (not tcpserver/qmail-smtpd)" 1>&2
    echo "...try: disabling current MTA" 1>&2
    OK=0
  fi
fi

if [ $skip_sendmail_check -eq 1 ] ; then
for i in /usr/lib/sendmail /usr/sbin/sendmail; do
  if [ -f $i -a ! -L $i ]; then
    echo "! $i is a file, should be a link" 1>&2
    echo "...try: uninstalling current MTA or: mv $i $i.old; ln -s $QmailBinPrefix/bin/sendmail $i" 1>&2
    OK=0
  elif [ ! -f $i ];then
    echo "! $i is missing" 1>&2
    echo "...try: ln -s $QmailBinPrefix/bin/sendmail $i" 1>&2
    OK=0
  elif [ "$VERB" = y ]; then
    echo "$i exists"
  fi
done
fi

if [ $OK -eq 1 ]; then
  echo "Congratulations, your IndiMail installation in "$DESTDIR"$QmailHOME looks good!"
  return 0
else
  echo "! Potential problems were found with your IndiMail installation in "$DESTDIR"$QmailHOME" 1>&2
  return 1
fi
}

default_indimail_control()
{
if [ ! -d "$DESTDIR"$CONTROLDIR ] ; then
	/bin/mkdir -p "$DESTDIR"$CONTROLDIR
	if [ $? -ne 0 ] ; then
		return 1
	fi
fi
if [ ! -d "$DESTDIR"$sysconfdir/tcp ] ; then
	/bin/mkdir -p "$DESTDIR"$sysconfdir/tcp
	if [ $? -ne 0 ] ; then
		return 1
	fi
fi
echo "Creating Default IndiMail Control Files"
if [ ! -f "$DESTDIR"$sysconfdir/tcp/tcp.imap ] ; then
	(
	echo "127.:allow,IMAPCLIENT=\"\""
	echo "::1:allow,IMAPCLIENT=\"\"" 
	) > "$DESTDIR"$sysconfdir/tcp/tcp.imap
fi
if [ ! -f "$DESTDIR"$sysconfdir/tcp/tcp.pop3 ] ; then
	(
	echo "127.:allow,POP3CLIENT=\"\""
	echo "::1:allow,POP3CLIENT=\"\"" 
	) > "$DESTDIR"$sysconfdir/tcp/tcp.pop3
fi
if [ ! -f "$DESTDIR"$sysconfdir/tcp/tcp.poppass ] ; then
	(
	echo "127.:allow"
	echo "::1:allow"
	) > "$DESTDIR"$sysconfdir/tcp/tcp.poppass
fi
if [ ! -f "$DESTDIR"$CONTROLDIR/host.mysql ] ; then
	echo "host.mysql"
	if [ ! " $mysql_socket" = " " -o ! " $mysql_port" = " " ] ; then
		if [ " $mysql_host" = " " ]; then
			mysql_host=$MYSQL_HOST
		fi
		if [ " $mysql_user" = " " ]; then
			mysql_user=$MYSQL_USER
		fi
		if [ " $mysql_pass" = " " ]; then
			mysql_pass=$MYSQL_PASS
		fi
		if [ " $mysql_port" = " " ] ; then
			echo "$mysql_host:$mysql_user:$mysql_pass:$mysql_socket" > \
				"$DESTDIR"$CONTROLDIR/host.mysql
		else
			echo "$mysql_host:$mysql_user:$mysql_pass:$mysql_port" > \
				"$DESTDIR"$CONTROLDIR/host.mysql
		fi
	else
		echo "$mysql_host:$mysql_user:$mysql_pass:$mysqlSocket" > \
			"$DESTDIR"$CONTROLDIR/host.mysql
	fi
	/bin/chmod 640 "$DESTDIR"$CONTROLDIR/host.mysql
	$chown indimail:qmail "$DESTDIR"$CONTROLDIR/host.mysql
fi
LIST="tcp.imap tcp.pop3 tcp.poppass"
if [ -f "$DESTDIR"$QmailBinPrefix/bin/tcprules ] ; then
	for i in $LIST
	do
		t1=1
		if [ -f "$DESTDIR"$sysconfdir/tcp/$i ] ; then
			t1=`date -r "$DESTDIR"$sysconfdir/tcp/$i +'%s'`
		else
			continue
		fi
		if [ -f "$DESTDIR"$sysconfdir/tcp/$i.cdb ] ; then
			t2=`date -r "$DESTDIR"$sysconfdir/tcp/$i.cdb +'%s'`
		else
			t2=0
		fi
		if [ $t1 -gt $t2 ] ; then
			echo "Creating CDB "$DESTDIR"$sysconfdir/tcp/$i.cdb"
			"$DESTDIR"$QmailBinPrefix/bin/tcprules \
			"$DESTDIR"$sysconfdir/tcp/"$i".cdb \
			"$DESTDIR"$sysconfdir/tcp/"$i".tmp \
				< "$DESTDIR"$sysconfdir/tcp/$i
		fi
	done
else
	for i in $LIST
	do
		echo "ucspi-tcp not installed: Run tcprules to build cdb for rules defined in "$DESTDIR"$sysconfdir/tcp/$i" 1>&2
	done
fi
if [ -f "$DESTDIR"$QmailBinPrefix/bin/bogofilter ] ; then
	for i in spam ham register-spam register-ham
	do
		"$DESTDIR"$QmailBinPrefix/bin/maildirmake "$DESTDIR"$QmailHOME/alias/$i >/dev/null 2>&1
		if [ $? -eq 0 ] ; then
			$chown -R alias:qmail "$DESTDIR"$QmailHOME/alias/$i
			/bin/chmod -R 775 "$DESTDIR"$QmailHOME/alias/$i
		fi
		(
			echo "|$libexecdir/bogofilter-qfe"
			echo "$QmailHOME/alias/$i/"
		) > "$DESTDIR"$QmailHOME/alias/.qmail-B"$i"
		$chown alias:qmail "$DESTDIR"$QmailHOME/alias/.qmail-B"$i"
	done
fi
if [ ! -d "$DESTDIR"$QmailHOME/domains ] ; then
	/bin/mkdir -p "$DESTDIR"$QmailHOME/domains
	if [ $? -ne 0 ] ; then
		return 1
	fi
	$chown root:qmail "$DESTDIR"$QmailHOME/domains
	/bin/chmod 775 "$DESTDIR"$QmailHOME/domains
fi
if [ ! -d "$DESTDIR"$QmailHOME/inquery ] ; then
	/bin/mkdir -p "$DESTDIR"$QmailHOME/inquery
	if [ $? -ne 0 ] ; then
		return 1
	fi
	$chown indimail:qmail "$DESTDIR"$QmailHOME/inquery
	/bin/chmod 770 "$DESTDIR"$QmailHOME/inquery
fi
if [ ! -d "$DESTDIR"$QmailHOME/domains/$default_domain ] ; then
	/bin/mkdir -p "$DESTDIR"$QmailHOME/domains/$default_domain
	if [ $? -ne 0 ] ; then
		return 1
	fi
	$chown indimail:indimail "$DESTDIR"$QmailHOME/domains/$default_domain
fi
}

check_update_if_diff()
{
	val=`cat $1 2>/dev/null`
	if [ ! " $val" = " $2" ] ; then
		echo "updating $1 with $2"
		echo $2 > $1
		return 1
	else
		return 0
	fi
}

check_libmysqlclient_lib()
{
	if [ -z "$mysqlPrefix" ] ; then
		if [ -d /usr/lib/mysql -o -d /usr/lib64/mysql ] ; then
			mysqlPrefix=/usr
		elif [ -d /usr/local/lib/mysql ] ; then
			mysqlPrefix=/usr/local
		elif [ -L /usr/local/lib/mysql ] ; then
			mysqlPrefix=/usr/local
		elif [ -d /usr/local/mysql/lib ] ; then
			mysqlPrefix=/usr/local/mysql
		elif [ -L /usr/local/mysql/lib ] ; then
			mysqlPrefix=/usr/local/mysql
		fi
	fi
	if [ -z "$CONTROLDIR" ] ; then
		CONTROLDIR=$sysconfdir/control
	fi
	if [ -f "$DESTDIR"$CONTROLDIR/mysql_lib ] ; then
		mysqllib=`cat "$DESTDIR"$CONTROLDIR/mysql_lib 2>/dev/null`
		if [ -f $mysqllib ] ; then
			echo ""$DESTDIR"$CONTROLDIR/mysql_lib exists: No Change" 1>&2
			return 0
		fi
	fi
	# upgrade MYSQL_LIB for dynamic loading of libmysqlclient
	# mysql-community on 64bit systems
	if [ -z "$mysqllib" -a -d /usr/lib64/mysql ] ; then
		prev_num=0
		for i in `/bin/ls -t /usr/lib64/mysql/libmysqlclient.so.*.*.* 2>/dev/null`
		do
			file=`basename $i`
			num=`echo $file | cut -d. -f3`
			if [ $num -gt $prev_num ] ; then
				prev_num=$num
				mysqllib=$i
			fi
		done
	fi
	if [ -z "$mysqllib" -a -d /usr/lib64 ] ; then
		prev_num=0
		for i in `/bin/ls -t /usr/lib64/libmysqlclient.so.*.*.* 2>/dev/null`
		do
			file=`basename $i`
			num=`echo $file | cut -d. -f3`
			if [ $num -gt $prev_num ] ; then
				prev_num=$num
				mysqllib=$i
			fi
		done
		if [ -z "$mysqllib" ] ; then
			prev_num=0
			for i in `/bin/ls -t /usr/lib64/libmariadb.so.* 2>/dev/null`
			do
				file=`basename $i`
				num=`echo $file | cut -d. -f3`
				if [ $num -gt $prev_num ] ; then
					prev_num=$num
					mysqllib=$i
				fi
			done
		fi
	fi
	if [ -z "$mysqllib" ] ; then
		case "$host" in
			*-*-darwin**)
			LIBMYSQL=`/bin/ls -t $mysqlPrefix/lib/libmysqlclient.*.dylib 2>/dev/null`
			LIBMARIADB=`/bin/ls -t $mysqlPrefix/lib/libmariadb.*.dylib 2>/dev/null`
			x=2
			;;
			*-*-freebsd**)
			LIBMYSQL=`/bin/ls -t $mysqlPrefix/lib/mysql/libmysqlclient.so.* 2>/dev/null`
			LIBMARIADB=`/bin/ls -t $mysqlPrefix/lib/mysql/libmariadb.so.*. 2>/dev/null`
			x=3
			;;
			*)
			LIBMYSQL=`/bin/ls -t $mysqlPrefix/lib*/libmysqlclient.so.*.*.* 2>/dev/null`
			LIBMARIADB=`/bin/ls -t $mysqlPrefix/lib*/libmariadb.so.* 2>/dev/null`
			x=3
			;;
		esac
		prev_num=0
		for i in $LIBMYSQL
		do
			file=`basename $i`
			num=`echo $file | cut -d. -f"$x"`
			if [ $num -gt $prev_num ] ; then
				prev_num=$num
				mysqllib=$i
			fi
		done
		if [ -z "$mysqllib" ] ; then
			for i in $LIBMARIADB
			do
				file=`basename $i`
				num=`echo $file | cut -d. -f"$x"`
				if [ $num -gt $prev_num ] ; then
					prev_num=$num
					mysqllib=$i
				fi
			done
		fi
	fi
	if [ -z "$mysqllib" -a -f /etc/debian_version ] ; then
		# upgrade MYSQL_LIB for dynamic loading of libmysqlclient
		prev_num=0
		for i in `/bin/ls -t /usr/lib/*-linux-gnu/libmariadbclient.so.*.*.* 2>/dev/null`
		do
			file=`basename $i`
			num=`echo $file | cut -d. -f"$x"`
			if [ $num -gt $prev_num ] ; then
				prev_num=$num
				mysqllib=$i
			fi
		done
		if [ -z "$mysqllib" ] ; then
			prev_num=0
			for i in `/bin/ls -t /usr/lib/*-linux-gnu/libmariadb.so.* 2>/dev/null`
			do
				file=`basename $i`
				num=`echo $file | cut -d. -f"$x"`
				if [ $num -gt $prev_num ] ; then
					prev_num=$num
					mysqllib=$i
				fi
			done
		fi
	fi
	#
	# this is crazy. Both mariadb and oracle are breaking things
	# around
	# MariaDB-shared, mariadb-connector-c
	# MariaDB-Compat
	# mysql-community-libs
	#
	if [ -z "$mysqllib" ] ; then
		if [ -f /etc/debian_version ] ; then
			dir="/usr/lib/*-linux-gnu/libmysqlclient.so.*.*.* \
				/usr/lib/*-linux-gnu/libmariadbclient.so.*.*.* \
				/usr/lib*/mysql/libmariadbclient.so.*.*.*"
		else
			dir="$mysqlPrefix/lib*/libmariadb.so.* \
				$mysqlPrefix/lib*/libmysqlclient.so.*.*.* \
				$mysqlPrefix/lib*/mysql/libmysqlclient.so.*.*.*"
		fi
		for i in `ls -t $dir 2>/dev/null`
		do
			file=`basename $i`
			num=`echo $file | cut -d. -f3`
			if [ $num -gt $prev_num ] ; then
				prev_num=$num
				mysqllib=$i
			fi
		done
	fi
	if [ -n "$mysqllib" -a -f "$mysqllib" ] ; then
		check_update_if_diff "$DESTDIR"$CONTROLDIR/mysql_lib $mysqllib
		if [ $? -eq 0 ] ; then
			echo ""$DESTDIR"$CONTROLDIR/mysql_lib exists: No Change" 1>&2
		fi
	elif [ -f "$DESTDIR"$CONTROLDIR/mysql_lib ] ; then
		echo "removing "$DESTDIR"$CONTROLDIR/mysql_lib"
		/bin/rm -f "$DESTDIR"$CONTROLDIR/mysql_lib
	fi
	return 0
}

default_qmail_control()
{
if [ ! -d "$DESTDIR"$CONTROLDIR ] ; then
	/bin/mkdir -p "$DESTDIR"$CONTROLDIR
	if [ $? -ne 0 ] ; then
		return 1
	fi
fi
if [ ! -d "$DESTDIR"$sysconfdir/tcp ] ; then
	/bin/mkdir -p "$DESTDIR"$sysconfdir/tcp
	if [ $? -ne 0 ] ; then
		return 1
	fi
fi
echo "Creating Default qmail Control Files"
hostname=$([ -n "$HOSTNAME" ] && echo "$HOSTNAME" || uname -n)
echo "servicedir.conf"
echo "me"
echo "defaultdomain"
echo "plusdomain"
echo "locals"
echo "rcpthosts"
if [ -f ./config-fast ] ; then
	./config-fast $hostname $DESTDIR
else
	"$DESTDIR"$libexecdir/config-fast $hostname $DESTDIR
fi

echo "Setting Following Files to Reasonable Defaults"
if [ ! -f "$DESTDIR"$CONTROLDIR/servicedir.conf ] ; then
	echo "servicedir.conf"
	echo "$servicedir" > "$DESTDIR"$CONTROLDIR/servicedir.conf
fi
if [ ! -f "$DESTDIR"$CONTROLDIR/defaultdelivery ] ; then
	echo "defaultdelivery"
	echo "./Maildir/" > "$DESTDIR"$CONTROLDIR/defaultdelivery
fi
if [ ! -f "$DESTDIR"$CONTROLDIR/nodnscheck ] ; then
	# qmail-smtpd
	echo "nodnscheck"
	(
	echo "@gmail.com"
	echo "@yahoo.com"
	echo "@hotmail.com"
	echo "@outlook.com"
	echo "@aol.com"
	echo "@$hostname"
	) > "$DESTDIR"$CONTROLDIR/nodnscheck
else
	grep "$hostname" "$DESTDIR"$CONTROLDIR/nodnscheck >/dev/null
	if [ $? -ne 0 ]; then
		echo "@$hostname" >> "$DESTDIR"$CONTROLDIR/nodnscheck
	fi
fi

"$DESTDIR"$libexecdir/ipmeprint | \
	egrep -vw "::|::1|0\.0\.0\.0|127\.0\.0\.1|172.17.0|0000:0000:0000:0000:0000:0000:0000:0000" | \
	head -1|awk '{print $3}'> /tmp/localiphost.$$
if [ -s /tmp/localiphost.$$ ] ; then
	echo "localiphost"
	/bin/mv /tmp/localiphost.$$ "$DESTDIR"$CONTROLDIR/localiphost
else
	echo "localiphost"
	echo 127.0.0.1 > "$DESTDIR"$CONTROLDIR/localiphost
fi
if [ ! -f "$DESTDIR"$CONTROLDIR/hostip ] ; then
	echo "hostip"
	/bin/ln -sr "$DESTDIR"$CONTROLDIR/localiphost \
		"$DESTDIR"$CONTROLDIR/hostip 2>/dev/null
	if [ $? -ne 0 ] ; then
		cd "$DESTDIR"$CONTROLDIR
		/bin/ln -s localiphost hostip
	fi
fi

if [ ! -f "$DESTDIR"$CONTROLDIR/smtpgreeting ] ; then
	echo "smtpgreeting"
	echo "$hostname"            > "$DESTDIR"$CONTROLDIR/smtpgreeting
fi

if [ ! -f "$DESTDIR"$CONTROLDIR/databytes ] ; then
	echo "databytes"
	echo "$databytes"           > "$DESTDIR"$CONTROLDIR/databytes
fi

if [ ! -f "$DESTDIR"$CONTROLDIR/timeoutsmtpd ] ; then
	echo "timeoutsmtpd"
	echo 300                    > "$DESTDIR"$CONTROLDIR/timeoutsmtpd
fi

if [ ! -f "$DESTDIR"$CONTROLDIR/timeoutremote ] ; then
	echo "timeoutremote"
	echo 300                    > "$DESTDIR"$CONTROLDIR/timeoutremote
fi

echo "chkrcptdomains"
$touch "$DESTDIR"$CONTROLDIR/chkrcptdomains
if [ ! -f "$DESTDIR"$CONTROLDIR/greylist.white ] ; then
	echo "greylist.white"
	/bin/cat "$DESTDIR"$CONTROLDIR/localiphost > "$DESTDIR"$CONTROLDIR/greylist.white
fi

if [ " $wipe_option" = " 1" -o ! -f "$DESTDIR"/$sysconfdir/users/assign ] ; then
	echo "assign"
	echo "." > "$DESTDIR"$sysconfdir/users/assign
	if [ -f "$DESTDIR"$QmailBinPrefix/sbin/qmail-newu ] ; then
		"$DESTDIR"$QmailBinPrefix/sbin/qmail-newu "$DESTDIR"$sysconfdir/users
	fi
fi

if [ ! -f "$DESTDIR"$CONTROLDIR/dnsbllist ] ; then
	echo "dnsbllist"
	echo "dnsbl.njabl.org"      > "$DESTDIR"$CONTROLDIR/dnsbllist
fi

for i in smtp qmtp qmqp
do
	if [ ! -f "$DESTDIR"$sysconfdir/tcp/tcp.$i ] ; then
		echo "tcp.$i"
	fi
done
if [ ! -f "$DESTDIR"$sysconfdir/tcp/tcp.smtp ] ; then
	(
	echo "#127.:allow,RELAYCLIENT=\"\""
	echo "#::1:allow,RELAYCLIENT=\"\"" 
	echo "#=:allow,GREYIP=\"127.0.0.1:1999\""
	echo "#:allow,GREYIP=\"127.0.0.1:1999\",RBLSMTPD=\"-No DNS PTR Record - MTA Misconfigured.\""
	) > "$DESTDIR"$sysconfdir/tcp/tcp.smtp
fi
if [ ! -f "$DESTDIR"$sysconfdir/tcp/tcp.qmtp ] ; then
	(
	echo ":deny" 
	) > "$DESTDIR"$sysconfdir/tcp/tcp.qmtp
fi
if [ ! -f "$DESTDIR"$sysconfdir/tcp/tcp.qmqp ] ; then
	(
	echo ":deny" 
	) > "$DESTDIR"$sysconfdir/tcp/tcp.qmqp
fi
LIST="tcp.smtp tcp.qmtp tcp.qmqp"
if [ -f "$DESTDIR"$QmailBinPrefix/bin/tcprules ] ; then
	for i in $LIST
	do
		t1=0
		if [ -f "$DESTDIR"$sysconfdir/tcp/$i ] ; then
    		t1=`date -r "$DESTDIR"$sysconfdir/tcp/$i +'%s'`
		else
			continue
		fi
		if [ -f "$DESTDIR"$sysconfdir/tcp/$i.cdb ] ; then
    		t2=`date -r "$DESTDIR"$sysconfdir/tcp/$i.cdb +'%s'`
		else
			t2=0
		fi
    	if [ $t1 -gt $t2 ] ; then
			"$DESTDIR"$QmailBinPrefix/bin/tcprules \
			"$DESTDIR"$sysconfdir/tcp/"$i".cdb \
			"$DESTDIR"$sysconfdir/tcp/"$i".tmp \
				< "$DESTDIR"$sysconfdir/tcp/$i
		fi
	done
else
	for i in $LIST
	do
		echo "ucspi-tcp not installed: Run tcprules to build cdb for rules defined in "$DESTDIR"$sysconfdir/tcp/$i" 1>&2
	done
fi

for i in locals rcpthosts
do
	if [ ! -f "$DESTDIR"$CONTROLDIR/$i ] ; then
		echo $i
		echo "localhost" > "$DESTDIR"$CONTROLDIR/$i
		sort -u "$DESTDIR"$CONTROLDIR/$i -o "$DESTDIR"$CONTROLDIR/$i
	else
			grep "localhost" "$DESTDIR"$CONTROLDIR/$i >/dev/null
			if [ $? -ne 0 ]; then
				echo $i
				echo "localhost" >> "$DESTDIR"$CONTROLDIR/$i
				sort -u "$DESTDIR"$CONTROLDIR/$i -o "$DESTDIR"$CONTROLDIR/$i
			fi
	fi
	chmod 644 "$DESTDIR"$CONTROLDIR/$i
done

if [ ! -f "$DESTDIR"$CONTROLDIR/tlsserverciphers ] ; then
	echo "tlsserverciphers"
	(
	/bin/echo -n "ALL:!aNULL:!ADH:!eNULL:!LOW:!EXP:RC4+RSA:+HIGH:+MEDIUM:"
	/bin/echo -n "-EDH-RSA-DES-CBC3-SHA:-EDH-DSS-DES-CBC3-SHA:-DES-CBC3-SHA:"
	/bin/echo -n "-DES-CBC3-MD5:+SSLv3:+TLSv1:-SSLv2"
	echo
	) > "$DESTDIR"$CONTROLDIR/tlsserverciphers
fi
if [ ! -f "$DESTDIR"$CONTROLDIR/tlsservermethod ] ; then
	echo tlsservermethod
	echo TLSv1_2 > "$DESTDIR"$CONTROLDIR/tlsservermethod
fi
if [ ! -f "$DESTDIR"$CONTROLDIR/tlsclientciphers ] ; then
	echo "tlsclientciphers"
	echo "ALL:!aNULL:!ADH:!eNULL:!LOW:!DH:!EXP" > "$DESTDIR"$CONTROLDIR/tlsclientciphers
fi
if [ ! -f "$DESTDIR"$CONTROLDIR/tlsclientmethod ] ; then
	echo tlsclientmethod
	echo TLSv1_2 > "$DESTDIR"$CONTROLDIR/tlsclientmethod
fi

if [ ! -f "$DESTDIR"$sysconfdir/procmailrc ] ; then
	#
	# ensure call to procmail in .qmail-default
	# |preline procmail -p -m $sysconfdir/procmailrc || exit 111
	#
	echo "procmailrc"
	(
	echo :0w
	echo "|$QmailBinPrefix/sbin/vfilter '' bounce-no-mailbox"
	) > "$DESTDIR"$sysconfdir/procmailrc
fi

if [ -n "$DESTDIR" ] ; then
	indlib=`ls -d "$DESTDIR"$QmailBinPrefix/lib*/libindimail.so.*.*.* 2>/dev/null|sed -e "'s}$DESTDIR}}g'"`
else
	indlib=`ls -d $QmailBinPrefix/lib*/libindimail.so.*.*.* 2>/dev/null`
fi
if [ -n "$indlib" -a -f "$indlib" ] ; then
	check_update_if_diff "$DESTDIR"$CONTROLDIR/libindimail $indlib
	if [ $? -eq 0 ] ; then
		echo ""$DESTDIR"$CONTROLDIR/libindimail exists: No Change" 1>&2
	fi
elif [ -f "$DESTDIR"$CONTROLDIR/libindimail ] ; then
	echo "removing "$DESTDIR"$CONTROLDIR/libindimail"
	/bin/rm -f "$DESTDIR"$CONTROLDIR/libindimail
fi
check_libmysqlclient_lib
}

create_fifologger()
{
if [ $# -ne 2 ] ; then
	echo "USAGE: create_fifologger fifo_path servicedir" 1>&2
	return 1
fi
fifo_path=$1
SERVICEDIR=$2
if [ " $fifo_path" = " " ] ; then
	echo "fifo_path cannot be null" 1>&2
	return 1
fi
conf_dir="$DESTDIR"$SERVICEDIR/qmail-logfifo/variables
if [ $nooverwrite -eq 1 -a -d $conf_dir ] ; then
	return 0
fi
/bin/mkdir -p $conf_dir
$chown root:indimail $conf_dir
/bin/chmod 555 $conf_dir
echo  $fifo_path > $conf_dir/LOGFILTER

# qmail-logfifo logger
/bin/mkdir -p "$DESTDIR"$SERVICEDIR/qmail-logfifo/log
if [ $down_state -eq 1 ] ; then
	$TOUCH "$DESTDIR"$SERVICEDIR/qmail-logfifo/down
fi
(
echo "#!/bin/sh"
echo "# $RCSID"
echo "# $prog_args"
echo ""
echo "exec 2>&1"
echo "LOGFILTER=\`/bin/cat variables/LOGFILTER\`"
echo "FIFODIR=\`dirname \$LOGFILTER\`"
echo "if [ ! -d \$FIFODIR ] ; then"
echo "    mkdir -p \$FIFODIR"
echo "    chown indimail:indimail \$FIFODIR"
echo "    /bin/chmod 775 \$FIFODIR"
echo "fi"
echo "if [ ! -p \$LOGFILTER ] ; then"
echo "    /bin/rm -f \$LOGFILTER"
echo "    /usr/bin/mkfifo -m 666 \$LOGFILTER"
echo "fi"
echo "exec $QmailBinPrefix/bin/setuidgid indimail \\"
echo "$QmailBinPrefix/bin/qmail-cat \$LOGFILTER"
) > "$DESTDIR"$SERVICEDIR/qmail-logfifo/run
/bin/chmod +x "$DESTDIR"$SERVICEDIR/qmail-logfifo/run

if [ ! -d $LOGDIR ] ; then
	/bin/mkdir -p $LOGDIR
	$chown qmaill:nofiles $LOGDIR
fi
#qmail-logfifo log script
(
echo "#!/bin/sh"
echo "$RCSID"
echo "# generated on $host on `date`"
echo "# $prog_args"
echo ""
echo "exec $QmailBinPrefix/bin/setuidgid qmaill \\"
echo "$QmailBinPrefix/sbin/multilog t $LOGDIR/logfifo"
) > "$DESTDIR"$SERVICEDIR/qmail-logfifo/log/run
/bin/chmod +x "$DESTDIR"$SERVICEDIR/qmail-logfifo/log/run
echo "$prog_args" > $conf_dir/.options
}

create_smtp()
{
if [ $# -ne 11 ] ; then
	echo "USAGE: create_smtp qbase queue_count first_queue_no supervise_dir smtp_port check_user=0|1 check_relay=0|1 use_ssl=0|1 force_tls=0|1 infifo=fifo_path utf8=0|1" 1>&2
	return 1
fi
QUEUE_BASE=$1
NO_OF_QUEUES=$2
FIRST_QUEUE=$3
SERVICEDIR=$4
SMTP_PORT=$5
chkrecipient=$6
chkrelay=$7
smtp_ssl=$8
force_tls=$9
infifo=${10}
utf8=${11}

# qmail-smtpd script
if [ " $servicetag" = " " ] ; then
	tag=$SMTP_PORT
else
	tag=$servicetag
fi
if [ $nooverwrite -eq 1 -a -d "$DESTDIR"$SERVICEDIR/qmail-smtpd.$tag/variables ] ; then
	return 0
fi
if [ -n "$infifo" ] ; then
	base_fifo_name=`basename $infifo`
	fifo_dir=`dirname $infifo`
	if [ $fifo_dir = "." ] ; then
		fifo_dir=$QmailHOME/inquery
	fi
fi
conf_dir="$DESTDIR"$SERVICEDIR/qmail-smtpd.$tag/variables
if [ $run_file_only -eq 1 ] ; then
	if [ -d $conf_dir ] ; then
		mv $conf_dir "$conf_dir".bak
	fi
fi
/bin/mkdir -p "$DESTDIR"$SERVICEDIR/qmail-smtpd.$tag/log
if [ $down_state -eq 1 ] ; then
	$TOUCH "$DESTDIR"$SERVICEDIR/qmail-smtpd.$tag/down
fi
/bin/mkdir -p $conf_dir
$chown root:indimail $conf_dir
/bin/chmod 550 $conf_dir
if [ " $ipaddress" = " " ] ; then
	echo 0 > $conf_dir/LOCALIP
else
	echo $ipaddress > $conf_dir/LOCALIP
fi
echo $SMTP_PORT > $conf_dir/PORT
if [ ! " $maxdaemons" = " " ] ; then
	echo "$maxdaemons" > $conf_dir/MAXDAEMONS
else
	echo $CONCURRENCYINCOMING > $conf_dir/MAXDAEMONS
fi
if [ -n "$infifo" ] ; then
echo $base_fifo_name > $conf_dir/INFIFO
echo $fifo_dir > $conf_dir/FIFODIR
fi

if [ " $enable_smtp_plugin" = " " ] ; then
	echo > $conf_dir/DISABLE_PLUGIN
else
	> $conf_dir/DISABLE_PLUGIN
fi
if [ ! " $maxperip" = " " ] ; then
	echo "$maxperip" > $conf_dir/MAXPERIP
else
	echo 10 > $conf_dir/MAXPERIP
fi
if [ ! " $CONTROLDIR" = " " ] ; then
	echo "$CONTROLDIR" > $conf_dir/CONTROLDIR
else
	> $conf_dir/CONTROLDIR
fi
if [ " $helofqdn" = " " ] ; then
	> $conf_dir/ENFORCE_FQDN_HELO
else
	echo > $conf_dir/ENFORCE_FQDN_HELO
fi
if [ " $helocheck" = " " ] ; then
	> $conf_dir/BADHELOCHECK
else
	echo > $conf_dir/BADHELOCHECK
fi
if [ " $password_cache" = " " ] ; then
	> $conf_dir/PASSWD_CACHE
else
	echo > $conf_dir/PASSWD_CACHE
fi
if [ " $query_cache" = " " ] ; then
	> $conf_dir/QUERY_CACHE
else
	echo > $conf_dir/QUERY_CACHE
fi
if [ " $default_domain" = " " ] ; then
	if [ ! " $CONTROLDIR" = " " ] ; then
		if [ -f $CONTROLDIR/defaulthost ] ; then
			ln -sf $CONTROLDIR/defaulthost $conf_dir/DEFAULT_DOMAIN
		else
			> $conf_dir/DEFAULT_DOMAIN
		fi
	else
		> $conf_dir/DEFAULT_DOMAIN
	fi
else
	echo "$default_domain" > $conf_dir/DEFAULT_DOMAIN
fi
if [ ! " $memory" = " " ] ; then
	echo $memory > $conf_dir/SOFT_MEM
else
	echo 52428800 > $conf_dir/SOFT_MEM
fi
if [ " $smtp_ssl" = " 1" ] ; then
	echo > $conf_dir/SMTPS
else
	> $conf_dir/SMTPS
fi
if [ " $force_tls" = " 1" ] ; then
	echo > $conf_dir/FORCE_TLS
else
	> $conf_dir/FORCE_TLS
fi
if [ " $smtp_ssl" = " 1" -o " $force_tls" = " 1" ] ; then
	echo $sysconfdir/certs > $conf_dir/CERTDIR
fi
if [ " $odmr" = " " ] ; then
	echo $QUEUE_BASE > $conf_dir/QUEUE_BASE
	echo $NO_OF_QUEUES > $conf_dir/QUEUE_COUNT
	echo $FIRST_QUEUE > $conf_dir/QUEUE_START
	if [ $use_starttls -eq 0 ] ; then
		> $conf_dir/STARTTLS
	else
		echo > $conf_dir/STARTTLS
		echo $sysconfdir/certs > $conf_dir/CERTDIR
	fi
	if [ " $qregex" = " " ] ; then
		> $conf_dir/QREGEX
	else
		echo > $conf_dir/QREGEX
	fi
	if [ " $viruscheck" = " " ] ; then
		> $conf_dir/VIRUSCHECK
	else
		echo $viruscheck > $conf_dir/VIRUSCHECK
	fi
	if [ " $qhpsi" = " " ] ; then
		> $conf_dir/QHPSI
	else
		echo $qhpsi > $conf_dir/QHPSI
	fi
	if [ " $bodycheck" = " " ] ; then
		> $conf_dir/BODYCHECK
	else
		if [ " $bodycheck" = " 1" ] ; then
			echo > $conf_dir/BODYCHECK
		else
			echo $bodycheck > $conf_dir/BODYCHECK
		fi
	fi
	if [ " $usefsync" = " " ] ; then
		> $conf_dir/USE_FSYNC
	else
		echo > $conf_dir/USE_FSYNC
	fi
	if [ " $usesyncdir" = " " ] ; then
		> $conf_dir/USE_SYNCDIR
	else
		echo > $conf_dir/USE_SYNCDIR
	fi
	if [ " $min_free" = " " ] ; then
		echo 52428800 > $conf_dir/MIN_FREE
	else
		echo $min_free > $conf_dir/MIN_FREE
	fi
	if [ " $QmailBinPrefix" = " /usr" ] ; then
		echo "/bin:/usr/bin:/usr/sbin:/sbin" > $conf_dir/PATH
	else
		echo "/bin:/usr/bin:$QmailBinPrefix/bin:$QmailBinPrefix/sbin" > $conf_dir/PATH
	fi
	if [ ! " $spamfilter" = " " ] ; then
		echo "$spamfilter" > $conf_dir/SPAMFILTER
		echo "1" > $conf_dir/MAKE_SEEKABLE
		if [ ! " $spamexitcode" = " " ] ; then
			echo "$spamexitcode" > $conf_dir/SPAMEXITCODE
			if [ ! " $rejectspam" = " " ] ; then
				echo "$rejectspam" > $conf_dir/REJECTSPAM
			else
				> $conf_dir/REJECTSPAM
			fi
		else
			> $conf_dir/SPAMEXITCODE
		fi
	else
		> $conf_dir/SPAMFILTER
	fi
	if [ ! " $masquerade" = " " ] ; then
		echo  > $conf_dir/MASQUERADE
	else
		> $conf_dir/MASQUERADE
	fi
	if [ ! " $domainlimits" = " " ] ; then
		echo  > $conf_dir/DOMAIN_LIMITS
	else
		> $conf_dir/DOMAIN_LIMITS
	fi
	if [ ! " $chkrecipient" = " " ] ; then
		echo 1 > $conf_dir/CHECKRECIPIENT
	else
		> $conf_dir/CHECKRECIPIENT
	fi
	if [ ! " $antispoof" = " " ] ; then
		echo  > $conf_dir/ANTISPOOFING
	else
		> $conf_dir/ANTISPOOFING
	fi
	if [ ! " $cugmail" = " " ] ; then
		echo  > $conf_dir/CUGMAIL
	else
		> $conf_dir/CUGMAIL
	fi
	if [ ! " $dnscheck" = " " ] ; then
		> $conf_dir/NODNSCHECK
	else
		echo > $conf_dir/NODNSCHECK
	fi
	if [ -f $CONTROLDIR/hostaccess ] ; then
		if [ " $paranoid" =  " 1" ] ; then
			echo > $conf_dir/PARANOID
		else
			> $conf_dir/PARANOID
		fi
		if [ " $dmasquerade" = " 1" ] ; then
			echo > $conf_dir/DOMAIN_MASQUERADE
		else
			> $conf_dir/DOMAIN_MASQUERADE
		fi
	else
		> $conf_dir/PARANOID
		> $conf_dir/DOMAIN_MASQUERADE
	fi
	if [ ! " $forceauthsmtp" = " " ] ; then
		echo > $conf_dir/REQUIREAUTH
		> $conf_dir/AUTH_ALL
		> $conf_dir/CHECKRELAY
	else
		> $conf_dir/REQUIREAUTH
		if [ ! " $authall" = " " ] ; then
			echo > $conf_dir/AUTH_ALL
			> $conf_dir/CHECKRELAY
		else
			> $conf_dir/AUTH_ALL
			if [ ! " $chkrelay" = " " ] ; then
				echo  > $conf_dir/CHECKRELAY
			else
				> $conf_dir/CHECKRELAY
			fi
		fi
	fi
	if [ $utf -eq 1 ] ; then
		echo > $conf_dir/UTF8
	else
		> $conf_dir/UTF8
	fi
fi # odmr
if [ $shared_objects -eq 1 ] ; then
	plugin_count=0
	if [ -f "$DESTDIR"/usr/lib/indimail/plugins/qmail_smtpd.so ] ; then
	if [ $use_dlmopen -eq 1 ] ; then
	echo "1" > $conf_dir/USE_DLMOPEN
	fi
	echo "/usr/lib/indimail/plugins/qmail_smtpd.so" > $conf_dir/PLUGIN"$plugin_count"
	echo "smtp_init" > $conf_dir/PLUGIN"$plugin_count"_init
	echo "$QmailHOME" > $conf_dir/PLUGIN"$plugin_count"_dir
	plugin_count=`expr $plugin_count + 1`
	fi
	if [ -f "$DESTDIR"/usr/lib/indimail/plugins/rblsmtpd.so ] ; then
	echo "/usr/lib/indimail/plugins/rblsmtpd.so" > $conf_dir/PLUGIN"$plugin_count"
	plugin_count=`expr $plugin_count + 1`
	fi
fi
case "$dkverify_option" in
	dkimstrict)
	/bin/rm -f $conf_dir/DKSIGN $conf_dir/DKIMSIGN $conf_dir/DKVERIFY $conf_dir/DKIMVERIFY $conf_dir/DKQUEUE $conf_dir/DKIMQUEUE
	echo FGHIKLMNOQRTUVWjp > $conf_dir/DKIMVERIFY
	> $conf_dir/UNSIGNED_SUBJECT
	> $conf_dir/UNSIGNED_FROM
	echo "$QmailBinPrefix/sbin/qmail-dkim" > $conf_dir/QMAILQUEUE
	if [ $no_multi -eq 1 ] ; then
		echo "$QUEUE_BASE"/queue1 > $conf_dir/QUEUEDIR
		echo "$QmailBinPrefix/sbin/qmail-queue" > $conf_dir/DKIMQUEUE
	fi
	;;
	dkim)
	/bin/rm -f $conf_dir/DKSIGN $conf_dir/DKIMSIGN $conf_dir/DKVERIFY $conf_dir/DKIMVERIFY $conf_dir/DKQUEUE $conf_dir/DKIMQUEUE
	echo > $conf_dir/DKIMVERIFY
	echo > $conf_dir/UNSIGNED_SUBJECT
	> $conf_dir/UNSIGNED_FROM
	echo "$QmailBinPrefix/sbin/qmail-dkim" > $conf_dir/QMAILQUEUE
	if [ $no_multi -eq 1 ] ; then
		echo "$QUEUE_BASE"/queue1 > $conf_dir/QUEUEDIR
		echo "$QmailBinPrefix/sbin/qmail-queue" > $conf_dir/DKIMQUEUE
	fi
	;;
	dkstrict)
	echo BDEGIJKfh > $conf_dir/DKVERIFY
	/bin/rm -f $conf_dir/DKSIGN $conf_dir/DKIMSIGN $conf_dir/DKVERIFY $conf_dir/DKIMVERIFY $conf_dir/DKQUEUE $conf_dir/DKIMQUEUE
	echo "$QmailBinPrefix/sbin/qmail-dk" > $conf_dir/QMAILQUEUE
	if [ $no_multi -eq 1 ] ; then
		echo "$QUEUE_BASE"/queue1 > $conf_dir/QUEUEDIR
		echo "$QmailBinPrefix/sbin/qmail-queue" > $conf_dir/DKQUEUE
	fi
	;;
	dk)
	echo > $conf_dir/DKVERIFY
	/bin/rm -f $conf_dir/DKSIGN $conf_dir/DKIMSIGN $conf_dir/DKVERIFY $conf_dir/DKIMVERIFY $conf_dir/DKQUEUE $conf_dir/DKIMQUEUE
	echo "$QmailBinPrefix/sbin/qmail-dk" > $conf_dir/QMAILQUEUE
	if [ $no_multi -eq 1 ] ; then
		echo "$QUEUE_BASE"/queue1 > $conf_dir/QUEUEDIR
		echo "$QmailBinPrefix/sbin/qmail-queue" > $conf_dir/DKQUEUE
	fi
	;;
	bothstrict)
	/bin/rm -f $conf_dir/DKSIGN $conf_dir/DKIMSIGN $conf_dir/DKVERIFY $conf_dir/DKIMVERIFY $conf_dir/DKQUEUE $conf_dir/DKIMQUEUE
	echo FGHIKLMNOQRTUVWjp > $conf_dir/DKIMVERIFY
	echo BDEGIJKfh > $conf_dir/DKVERIFY
	> $conf_dir/UNSIGNED_SUBJECT
	> $conf_dir/UNSIGNED_FROM
	echo "$QmailBinPrefix/sbin/qmail-dk" > $conf_dir/QMAILQUEUE
	echo "$QmailBinPrefix/sbin/qmail-dkim" > $conf_dir/DKQUEUE
	if [ $no_multi -eq 1 ] ; then
		echo "$QUEUE_BASE"/queue1 > $conf_dir/QUEUEDIR
		echo "$QmailBinPrefix/sbin/qmail-queue" > $conf_dir/DKIMQUEUE
	fi
	;;
	both)
	/bin/rm -f $conf_dir/DKSIGN $conf_dir/DKIMSIGN $conf_dir/DKVERIFY $conf_dir/DKIMVERIFY $conf_dir/DKQUEUE $conf_dir/DKIMQUEUE
	echo > $conf_dir/DKIMVERIFY
	echo > $conf_dir/DKVERIFY
	echo > $conf_dir/UNSIGNED_SUBJECT
	> $conf_dir/UNSIGNED_FROM
	echo "$QmailBinPrefix/sbin/qmail-dk" > $conf_dir/QMAILQUEUE
	echo "$QmailBinPrefix/sbin/qmail-dkim" > $conf_dir/DKQUEUE
	if [ $no_multi -eq 1 ] ; then
		echo "$QUEUE_BASE"/queue1 > $conf_dir/QUEUEDIR
		echo "$QmailBinPrefix/sbin/qmail-queue" > $conf_dir/DKIMQUEUE
	fi
	;;
	none|*)
	/bin/rm -f $conf_dir/DKSIGN $conf_dir/DKIMSIGN $conf_dir/DKVERIFY $conf_dir/DKIMVERIFY $conf_dir/DKQUEUE $conf_dir/DKIMQUEUE
	if [ $no_multi -eq 1 ] ; then
		> $conf_dir/QMAILQUEUE
		echo "$QUEUE_BASE"/queue1 > $conf_dir/QUEUEDIR
	else
		echo "$QmailBinPrefix/sbin/qmail-multi" > $conf_dir/QMAILQUEUE
		> $conf_dir/QUEUEDIR
	fi
	;;
esac
AUTHM=""
if [ -f $QmailBinPrefix/sbin/sys-checkpwd ] ; then
	if [ -n "$AUTHM" ] ; then
		AUTHM="$AUTHM $QmailBinPrefix/sbin/sys-checkpwd"
	else
		AUTHM="$QmailBinPrefix/sbin/sys-checkpwd"
	fi
fi
if [ -f $QmailBinPrefix/sbin/vchkpass ] ; then
	if [ -n "$AUTHM" ] ; then
		AUTHM="$AUTHM $QmailBinPrefix/sbin/vchkpass"
	else
		AUTHM="$QmailBinPrefix/sbin/vchkpass"
	fi
fi
if [ -n "$authsmtp" -o "$forceauthsmtp" ] ; then
echo "$AUTHM" > $conf_dir/AUTHMODULES
else
> $conf_dir/AUTHMODULES
fi
(
echo "#!/bin/sh"
echo "$RCSID"
echo "# generated on $host on `date`"
echo "# $prog_args"
echo ""
echo "QMAILDUID=\`/usr/bin/id -u indimail\`"
echo "NOFILESGID=\`/usr/bin/id -g indimail\`"
echo "ME=\`head -1 $CONTROLDIR/me\`"
echo "HOSTNAME=\`uname -n\`"
echo
echo "if [ -z \"\$QMAILDUID\" -o -z \"\$NOFILESGID\" -o -z \"\$ME\" ]; then"
echo "    echo QMAILDUID, NOFILESGID, or ME is unset in"
echo "    echo \`pwd\`/run"
echo "    sleep 5"
echo "    exit 1"
echo "fi"
echo "if [ ! -f $CONTROLDIR/rcpthosts ]; then"
echo "    echo \"No $CONTROLDIR/rcpthosts!\""
echo "    echo \"Refusing to start SMTP listener because it'll create an open relay\""
echo "    sleep 5"
echo "    exit 1"
echo "fi"
echo
echo "exec 2>&1"
echo "exec $QmailBinPrefix/bin/envdir variables sh -c \""
echo "exec $QmailBinPrefix/bin/softlimit -m \\\$SOFT_MEM -o 1024 \\"
if [ " $rbl" = " " ] ; then
	echo "$QmailBinPrefix/bin/tcpserver -v -H -R -l \$HOSTNAME \\"
	> $conf_dir/RBLCOMMAND
else
	echo "$QmailBinPrefix/bin/tcpserver -v -h -R -l \$HOSTNAME \\"
	(
	if [ " $rbl_list" = " " ] ; then
		if [ $shared_objects -eq 1 -a -f "$DESTDIR"/usr/lib/indimail/plugins/rblsmtpd.so ] ; then
		echo "/usr/lib/indimail/plugins/rblsmtpd.so -rzen.spamhaus.org -rdnsbl-1.uceprotect.net -rdnsbl.sorbs.net -rbl.spamcop.net"
		else
		echo "$QmailBinPrefix/bin/rblsmtpd -rzen.spamhaus.org -rdnsbl-1.uceprotect.net -rdnsbl.sorbs.net -rbl.spamcop.net"
		fi
	else
		if [ $shared_objects -eq 1 -a -f "$DESTDIR"/usr/lib/indimail/plugins/rblsmtpd.so ] ; then
		echo "/usr/lib/indimail/plugins/rblsmtpd.so $rbl_list"
		else
		echo "$QmailBinPrefix/bin/rblsmtpd $rbl_list"
		fi
	fi
	) > $conf_dir/RBLCOMMAND
fi
echo "-x $sysconfdir/tcp/tcp.smtp.cdb \\"
echo "-c variables/MAXDAEMONS -o -b \\\$MAXDAEMONS \\"
echo "-u \$QMAILDUID -g \$NOFILESGID \\\$LOCALIP \\\$PORT \\\$RBLCOMMAND \\"
if [ -f /bin/false ] ; then
	false="/bin/false"
else
	false="/usr/bin/false"
fi
if [ $shared_objects -eq 1 -a -f "$DESTDIR"/usr/lib/indimail/plugins/qmail_smtpd.so ] ; then
	if [ -n "$authsmtp" -o -n "$forceauthsmtp" ] ; then
		echo "/usr/lib/indimail/plugins/qmail_smtpd.so \$HOSTNAME \\\$AUTHMODULES $false\""
	else
		echo "/usr/lib/indimail/plugins/qmail_smtpd.so\""
	fi
else
	if [ -n "$authsmtp" -o -n "$forceauthsmtp" ] ; then
		echo "$QmailBinPrefix/sbin/qmail-smtpd \$HOSTNAME \\\$AUTHMODULES $false\""
	else
		echo "$QmailBinPrefix/sbin/qmail-smtpd\""
	fi
fi
) > "$DESTDIR"$SERVICEDIR/qmail-smtpd.$tag/run
/bin/chmod +x "$DESTDIR"$SERVICEDIR/qmail-smtpd.$tag/run

# qmail-smtpd log script
if [ ! -d $LOGDIR ] ; then
	/bin/mkdir -p $LOGDIR
	$chown qmaill:nofiles $LOGDIR
fi
(
echo "#!/bin/sh"
echo "$RCSID"
echo "# generated on $host on `date`"
echo "# $prog_args"
echo ""
echo "exec $QmailBinPrefix/bin/setuidgid qmaill \\"
echo "$QmailBinPrefix/sbin/multilog t $LOGDIR/smtpd.$tag"
) > "$DESTDIR"$SERVICEDIR/qmail-smtpd.$tag/log/run
/bin/chmod +x "$DESTDIR"$SERVICEDIR/qmail-smtpd.$tag/log/run
echo "$prog_args" > $conf_dir/.options

if [ $run_file_only -eq 1 ] ; then
	if [ -d "$conf_dir".bak ] ; then
		/bin/rm -rf $conf_dir
		/bin/mv "$conf_dir".bak $conf_dir
	fi
fi

# finally create fifologger as it modifies conf_dir
if [ ! " $logfilter" = " " ] ; then
	echo  $logfilter > $conf_dir/LOGFILTER
	if [ ! -f $SERVICEDIR/qmail-logfifo/run ] ; then
		prog_args="$QmailBinPrefix/sbin/svctool --fifologger=\"$logfilter\" --servicedir=\"$SERVICEDIR\""
		create_fifologger $logfilter $SERVICEDIR
	fi
else
	> $conf_dir/LOGFILTER
fi
}

create_queuedef()
{
if [ $# -ne 4 ] ; then
	echo "USAGE: create_queuedef qbase queue_count first_queue_no queue_def" 1>&2
	return 1
fi
QUEUE_BASE=$1
NO_OF_QUEUES=$2
FIRST_QUEUE=$3
QUEUE_DEF=$4

if [ " $CONTROLDIR" = " " ] ; then
	cntrldir=$sysconfdir/control
else
	cntrldir=$CONTROLDIR
fi
conf_dir="$DESTDIR"$CONTROLDIR/$QUEUE_DEF
if [ $nooverwrite -eq 1 -a -d "$DESTDIR"$CONTROLDIR/$QUEUE_DEF ] ; then
	return 0
fi
/bin/mkdir -p $conf_dir
#/bin/chmod 500 $conf_dir
echo $QUEUE_BASE > $conf_dir/QUEUE_BASE
echo $NO_OF_QUEUES > $conf_dir/QUEUE_COUNT
echo $FIRST_QUEUE > $conf_dir/QUEUE_START
if [ " $qregex" = " " ] ; then
	> $conf_dir/QREGEX
else
	echo > $conf_dir/QREGEX
fi
if [ " $query_cache" = " " ] ; then
	> $conf_dir/QUERY_CACHE
else
	echo > $conf_dir/QUERY_CACHE
fi
if [ " $viruscheck" = " " ] ; then
	> $conf_dir/VIRUSCHECK
else
	echo $viruscheck > $conf_dir/VIRUSCHECK
fi
if [ " $qhpsi" = " " ] ; then
	> $conf_dir/QHPSI
else
	echo $qhpsi > $conf_dir/QHPSI
fi
if [ " $usefsync" = " " ] ; then
	> $conf_dir/USE_FSYNC
else
	echo > $conf_dir/USE_FSYNC
fi
if [ " $usesyncdir" = " " ] ; then
	> $conf_dir/USE_SYNCDIR
else
	echo > $conf_dir/USE_SYNCDIR
fi
if [ ! " $spamfilter" = " " ] ; then
	echo "$spamfilter" > $conf_dir/SPAMFILTER
	echo "1" > $conf_dir/MAKE_SEEKABLE
	if [ ! " $spamexitcode" = " " ] ; then
		echo "$spamexitcode" > $conf_dir/SPAMEXITCODE
		if [ ! " $rejectspam" = " " ] ; then
			echo "$rejectspam" > $conf_dir/REJECTSPAM
		else
			> $conf_dir/REJECTSPAM
		fi
	else
		> $conf_dir/SPAMEXITCODE
	fi
else
	> $conf_dir/SPAMFILTER
fi
if [ " $min_free" = " " ] ; then
	echo 52428800 > $conf_dir/MIN_FREE
else
	echo $min_free > $conf_dir/MIN_FREE
fi
/bin/rm -f $conf_dir/QUEUEDIR
case "$dksign_option" in
	dkim)
	/bin/rm -f $conf_dir/DKSIGN $conf_dir/DKIMSIGN $conf_dir/DKQUEUE $conf_dir/DKIMQUEUE
	echo "$private_key" > $conf_dir/DKIMSIGN
	echo "$QmailBinPrefix/sbin/qmail-dkim" > $conf_dir/QMAILQUEUE
	;;
	dk)
	/bin/rm -f $conf_dir/DKSIGN $conf_dir/DKIMSIGN $conf_dir/DKQUEUE $conf_dir/DKIMQUEUE
	echo "$private_key" > $conf_dir/DKSIGN
	echo "$QmailBinPrefix/sbin/qmail-dk" > $conf_dir/QMAILQUEUE
	;;
	both)
	/bin/rm -f $conf_dir/DKSIGN $conf_dir/DKIMSIGN $conf_dir/DKQUEUE $conf_dir/DKIMQUEUE
	echo "$private_key" > $conf_dir/DKSIGN
	echo "$private_key" > $conf_dir/DKIMSIGN
	echo "$QmailBinPrefix/sbin/qmail-dk" > $conf_dir/QMAILQUEUE
	echo "$QmailBinPrefix/sbin/qmail-dkim" > $conf_dir/DKQUEUE
	;;
	none|*)
	/bin/rm -f $conf_dir/DKSIGN $conf_dir/DKIMSIGN $conf_dir/DKQUEUE $conf_dir/DKIMQUEUE
	if [ $no_multi -eq 1 ] ; then
		> $conf_dir/QMAILQUEUE
		echo "$QUEUE_BASE"/queue1 > $conf_dir/QUEUEDIR
	else
		echo "$QmailBinPrefix/sbin/qmail-multi" > $conf_dir/QMAILQUEUE
		> $conf_dir/QUEUEDIR
	fi
	;;
esac
echo "$prog_args" > $conf_dir/.options
if [ ! " $logfilter" = " " ] ; then
	echo  $logfilter > $conf_dir/LOGFILTER
	if [ ! -f $SERVICEDIR/qmail-logfifo/run ] ; then
		prog_args="$QmailBinPrefix/sbin/svctool --fifologger=\"$logfilter\" --servicedir=\"$SERVICEDIR\""
		create_fifologger $logfilter $SERVICEDIR
	fi
else
	> $conf_dir/LOGFILTER
fi
}

create_qmtp_or_qmqp()
{
if [ $# -ne 6 ] ; then
	echo "USAGE: create_qmtp_or_qmqp qmtpd|qmqpd qbase queue_count first_queue_no supervise_dir port" 1>&2
	return 1
elif [ " $1" != " qmtpd" -a " $1" != " qmqpd" ] ; then
	echo "USAGE: create_qmtp_or_qmqp qmtpd|qmqpd qbase queue_count first_queue_no supervise_dir port" 1>&2
	return 1
fi
type=$1
QUEUE_BASE=$2
NO_OF_QUEUES=$3
FIRST_QUEUE=$4
SERVICEDIR=$5
QMTP_PORT=$6

# qmail-qm[t|q]pd script
if [ " $servicetag" = " " ] ; then
	tag=$QMTP_PORT
else
	tag=$servicetag
fi
if [ $nooverwrite -eq 1 -a -d "$DESTDIR"$SERVICEDIR/qmail-$type.$tag/variables ] ; then
	return 0
fi
conf_dir="$DESTDIR"$SERVICEDIR/qmail-$type.$tag/variables
if [ $run_file_only -eq 1 ] ; then
	if [ -d $conf_dir ] ; then
		/bin/mv $conf_dir "$conf_dir".bak
	fi
fi
/bin/mkdir -p $conf_dir
$chown root:indimail $conf_dir
/bin/chmod 550 $conf_dir
if [ " $ipaddress" = " " ] ; then
	echo 0 > $conf_dir/LOCALIP
else
	echo $ipaddress > $conf_dir/LOCALIP
fi
echo $QMTP_PORT > $conf_dir/PORT
if [ ! " $maxdaemons" = " " ] ; then
	echo "$maxdaemons" > $conf_dir/MAXDAEMONS
else
	echo $CONCURRENCYINCOMING > $conf_dir/MAXDAEMONS
fi
if [ ! " $maxperip" = " " ] ; then
	echo "$maxperip" > $conf_dir/MAXPERIP
else
	echo 10 > $conf_dir/MAXPERIP
fi
if [ ! " $CONTROLDIR" = " " ] ; then
	echo "$CONTROLDIR" > $conf_dir/CONTROLDIR
else
	> $conf_dir/CONTROLDIR
fi
if [ ! " $memory" = " " ] ; then
	echo $memory > $conf_dir/SOFT_MEM
else
	echo 52428800 > $conf_dir/SOFT_MEM
fi
echo $QUEUE_BASE > $conf_dir/QUEUE_BASE
echo $NO_OF_QUEUES > $conf_dir/QUEUE_COUNT
echo $FIRST_QUEUE > $conf_dir/QUEUE_START
case "$dkverify_option" in
	dkimstrict)
	/bin/rm -f $conf_dir/DKSIGN $conf_dir/DKIMSIGN $conf_dir/DKVERIFY $conf_dir/DKIMVERIFY $conf_dir/DKQUEUE $conf_dir/DKIMQUEUE
	echo FGHIKLMNOQRTUVWjp > $conf_dir/DKIMVERIFY
	> $conf_dir/UNSIGNED_SUBJECT
	> $conf_dir/UNSIGNED_FROM
	echo "$QmailBinPrefix/sbin/qmail-dkim" > $conf_dir/QMAILQUEUE
	;;
	dkim)
	/bin/rm -f $conf_dir/DKSIGN $conf_dir/DKIMSIGN $conf_dir/DKVERIFY $conf_dir/DKIMVERIFY $conf_dir/DKQUEUE $conf_dir/DKIMQUEUE
	echo > $conf_dir/UNSIGNED_SUBJECT
	> $conf_dir/UNSIGNED_FROM
	echo > $conf_dir/DKIMVERIFY
	echo "$QmailBinPrefix/sbin/qmail-dkim" > $conf_dir/QMAILQUEUE
	;;
	dkstrict)
	echo BDEGIJKfh > $conf_dir/DKVERIFY
	/bin/rm -f $conf_dir/DKSIGN $conf_dir/DKIMSIGN $conf_dir/DKVERIFY $conf_dir/DKIMVERIFY $conf_dir/DKQUEUE $conf_dir/DKIMQUEUE
	echo "$QmailBinPrefix/sbin/qmail-dk" > $conf_dir/QMAILQUEUE
	;;
	dk)
	echo > $conf_dir/DKVERIFY
	/bin/rm -f $conf_dir/DKSIGN $conf_dir/DKIMSIGN $conf_dir/DKVERIFY $conf_dir/DKIMVERIFY $conf_dir/DKQUEUE $conf_dir/DKIMQUEUE
	echo "$QmailBinPrefix/sbin/qmail-dk" > $conf_dir/QMAILQUEUE
	;;
	bothstrict)
	/bin/rm -f $conf_dir/DKSIGN $conf_dir/DKIMSIGN $conf_dir/DKVERIFY $conf_dir/DKIMVERIFY $conf_dir/DKQUEUE $conf_dir/DKIMQUEUE
	echo FGHIKLMNOQRTUVWjp > $conf_dir/DKIMVERIFY
	echo BDEGIJKfh > $conf_dir/DKVERIFY
	echo "$QmailBinPrefix/sbin/qmail-dk" > $conf_dir/QMAILQUEUE
	echo "$QmailBinPrefix/sbin/qmail-dkim" > $conf_dir/DKQUEUE
	> $conf_dir/UNSIGNED_SUBJECT
	> $conf_dir/UNSIGNED_FROM
	;;
	both)
	/bin/rm -f $conf_dir/DKSIGN $conf_dir/DKIMSIGN $conf_dir/DKVERIFY $conf_dir/DKIMVERIFY $conf_dir/DKQUEUE $conf_dir/DKIMQUEUE
	echo > $conf_dir/DKIMVERIFY
	echo > $conf_dir/DKVERIFY
	echo > $conf_dir/UNSIGNED_SUBJECT
	> $conf_dir/UNSIGNED_FROM
	echo "$QmailBinPrefix/sbin/qmail-dk" > $conf_dir/QMAILQUEUE
	echo "$QmailBinPrefix/sbin/qmail-dkim" > $conf_dir/DKQUEUE
	;;
	none|*)
	/bin/rm -f $conf_dir/DKSIGN $conf_dir/DKIMSIGN $conf_dir/DKVERIFY $conf_dir/DKIMVERIFY $conf_dir/DKQUEUE $conf_dir/DKIMQUEUE
	if [ $no_multi -eq 1 ] ; then
		> $conf_dir/QMAILQUEUE
		echo "$QUEUE_BASE"/queue1 > $conf_dir/QUEUEDIR
	else
		echo "$QmailBinPrefix/sbin/qmail-multi" > $conf_dir/QMAILQUEUE
		> $conf_dir/QUEUEDIR
	fi
	;;
esac
if [ " $usefsync" = " " ] ; then
	> $conf_dir/USE_FSYNC
else
	echo > $conf_dir/USE_FSYNC
fi
if [ " $usesyncdir" = " " ] ; then
	> $conf_dir/USE_SYNCDIR
else
	echo > $conf_dir/USE_SYNCDIR
fi
if [ " $min_free" = " " ] ; then
	echo 52428800 > $conf_dir/MIN_FREE
else
	echo $min_free > $conf_dir/MIN_FREE
fi
if [ " $min_free" = " " ] ; then
	echo 52428800 > $conf_dir/MIN_FREE
else
	echo $min_free > $conf_dir/MIN_FREE
fi
if [ " $qhpsi" = " " ] ; then
	> $conf_dir/QHPSI
else
	echo $qhpsi > $conf_dir/QHPSI
fi
if [ ! " $spamfilter" = " " ] ; then
	echo "$spamfilter" > $conf_dir/SPAMFILTER
	echo "1" > $conf_dir/MAKE_SEEKABLE
	if [ ! " $spamexitcode" = " " ] ; then
		echo "$spamexitcode" > $conf_dir/SPAMEXITCODE
		if [ ! " $rejectspam" = " " ] ; then
			echo "$rejectspam" > $conf_dir/REJECTSPAM
		else
			> $conf_dir/REJECTSPAM
		fi
	else
		> $conf_dir/SPAMEXITCODE
	fi
else
	> $conf_dir/SPAMFILTER
fi
if [ " $QmailBinPrefix" = " /usr" ] ; then
	echo "/bin:/usr/bin:/usr/sbin:/sbin" > $conf_dir/PATH
else
	echo "/bin:/usr/bin:$QmailBinPrefix/bin:$QmailBinPrefix/sbin" > $conf_dir/PATH
fi
(
echo "#!/bin/sh"
echo "$RCSID"
echo "# generated on $host on `date`"
echo "# $prog_args"
echo ""
echo "QMAILDUID=\`/usr/bin/id -u indimail\`"
echo "NOFILESGID=\`/usr/bin/id -g indimail\`"
echo "ME=\`head -1 $CONTROLDIR/me\`"
echo "HOSTNAME=\`uname -n\`"
echo
echo "if [ -z \"\$QMAILDUID\" -o -z \"\$NOFILESGID\" -o -z \"\$ME\" ]; then"
echo "    echo QMAILDUID, NOFILESGID, or ME is unset in"
echo "    echo \`pwd\`/run"
echo "    sleep 5"
echo "    exit 1"
echo "fi"
echo
echo "exec 2>&1"
echo "exec $QmailBinPrefix/bin/envdir variables sh -c \""
echo "exec $QmailBinPrefix/bin/softlimit -m \\\$SOFT_MEM -o 1024 \\"
echo "$QmailBinPrefix/bin/tcpserver -v -H -R -l \$HOSTNAME \\"
case $type in
	qmtpd)
	echo "-x $sysconfdir/tcp/tcp.qmtp.cdb \\"
	;;
	qmqpd)
	echo "-x $sysconfdir/tcp/tcp.qmqp.cdb \\"
	;;
esac
echo "-c variables/MAXDAEMONS -o -b \\\$MAXDAEMONS \\"
echo "-u \$QMAILDUID -g \$NOFILESGID \\\$LOCALIP \\\$PORT \\"
echo "$QmailBinPrefix/sbin/qmail-$type\""
) > "$DESTDIR"$SERVICEDIR/qmail-$type.$tag/run
/bin/chmod +x "$DESTDIR"$SERVICEDIR/qmail-$type.$tag/run

/bin/mkdir -p "$DESTDIR"$SERVICEDIR/qmail-$type.$tag/log
if [ $down_state -eq 1 ] ; then
	$TOUCH "$DESTDIR"$SERVICEDIR/qmail-$type.$tag/down
fi
# qmail-qm[t|q]pd log script
if [ ! -d $LOGDIR ] ; then
	/bin/mkdir -p $LOGDIR
	$chown qmaill:nofiles $LOGDIR
fi
(
echo "#!/bin/sh"
echo "$RCSID"
echo "# generated on $host on `date`"
echo "# $prog_args"
echo ""
echo "exec $QmailBinPrefix/bin/setuidgid qmaill \\"
echo "$QmailBinPrefix/sbin/multilog t $LOGDIR/$type.$tag"
) > "$DESTDIR"$SERVICEDIR/qmail-$type.$tag/log/run
/bin/chmod +x "$DESTDIR"$SERVICEDIR/qmail-$type.$tag/log/run
echo "$prog_args" > $conf_dir/.options

if [ $run_file_only -eq 1 ] ; then
	if [ -d "$conf_dir".bak ] ; then
		/bin/rm -rf $conf_dir
		/bin/mv "$conf_dir".bak $conf_dir
	fi
fi

if [ ! " $logfilter" = " " ] ; then
	echo  $logfilter > $conf_dir/LOGFILTER
	if [ ! -f $SERVICEDIR/qmail-logfifo/run ] ; then
		prog_args="$QmailBinPrefix/sbin/svctool --fifologger=\"$logfilter\" --servicedir=\"$SERVICEDIR\""
		create_fifologger $logfilter $SERVICEDIR
	fi
else
	> $conf_dir/LOGFILTER
fi
}

create_udplogger()
{
if [ $# -ne 2 ] ; then
	echo "USAGE: create_udplogger udplogger_port supervise_dir" 1>&2
	return 1
fi
UDP_PORT=$1
SERVICEDIR=$2
if [ " $servicetag" = " " ] ; then
	tag=$UDP_PORT
else
	tag=$servicetag
fi
if [ $nooverwrite -eq 1 -a -d "$DESTDIR"$SERVICEDIR/udplogger.$tag/variables ] ; then
	return 0
fi
conf_dir="$DESTDIR"$SERVICEDIR/udplogger.$tag/variables
if [ $run_file_only -eq 1 ] ; then
	if [ -d $conf_dir ] ; then
		/bin/mv $conf_dir "$conf_dir".bak
	fi
fi
/bin/mkdir -p "$DESTDIR"$SERVICEDIR/udplogger.$tag/log
if [ $down_state -eq 1 ] ; then
	$TOUCH "$DESTDIR"$SERVICEDIR/udplogger.$tag/down
fi
/bin/mkdir -p $conf_dir
/bin/chmod 500 $conf_dir
if [ " $ipaddress" = " " ] ; then
	echo 127.0.0.1 > $conf_dir/LOCALIP
else
	echo $ipaddress > $conf_dir/LOCALIP
fi
if [ " $timeout" = " " ] ; then
	echo "60" > $conf_dir/TIMEOUT
else
	echo $timeout > $conf_dir/TIMEOUT
fi
echo $UDP_PORT > $conf_dir/PORT
if [ ! " $CONTROLDIR" = " " ] ; then
	echo "$CONTROLDIR" > $conf_dir/CONTROLDIR
else
	> $conf_dir/CONTROLDIR
fi
if [ ! " $memory" = " " ] ; then
	echo $memory > $conf_dir/SOFT_MEM
else
	echo 52428800 > $conf_dir/SOFT_MEM
fi

(
echo "#!/bin/sh"
echo "$RCSID"
echo "# generated on $host on `date`"
echo "# $prog_args"
echo ""
echo "exec 2>&1"
echo "exec $QmailBinPrefix/bin/envdir variables sh -c \""
echo "exec $QmailBinPrefix/bin/setuidgid indimail \\"
echo "$QmailBinPrefix/bin/softlimit -m \\\$SOFT_MEM -o 1024 \\"
echo " $QmailBinPrefix/sbin/udplogger -p \\\$PORT -t \\\$TIMEOUT \\\$LOCALIP\""
) > "$DESTDIR"$SERVICEDIR/udplogger.$tag/run
/bin/chmod +x "$DESTDIR"$SERVICEDIR/udplogger.$tag/run

# udplogger log script
if [ ! -d $LOGDIR ] ; then
	/bin/mkdir -p $LOGDIR
	$chown qmaill:nofiles $LOGDIR
fi
(
echo "#!/bin/sh"
echo "$RCSID"
echo "# generated on $host on `date`"
echo "# $prog_args"
echo ""
echo "exec $QmailBinPrefix/bin/setuidgid qmaill \\"
echo "$QmailBinPrefix/sbin/multilog t $LOGDIR/udplogger.$tag"
) > "$DESTDIR"$SERVICEDIR/udplogger.$tag/log/run
/bin/chmod +x "$DESTDIR"$SERVICEDIR/udplogger.$tag/log/run
echo "$prog_args" > $conf_dir/.options

if [ $run_file_only -eq 1 ] ; then
	if [ -d "$conf_dir".bak ] ; then
		/bin/rm -rf $conf_dir
		/bin/mv "$conf_dir".bak $conf_dir
	fi
fi
}

create_dane()
{
if [ $# -ne 7 ] ; then
	echo "USAGE: create_dane supervise_dir port timeout_days context_file save_interval hash_size whitelist" 1>&2
	return 1
fi
SERVICEDIR=$1
DANE_PORT=$2
TIMEOUT_DAYS=$3
CONTEXT_FILE=$4
SAVE_INTERVAL=$5
HASH_SIZE=$6
WHITELIST=$7
if [ " $DANE_PORT" = " " ] ; then
	GREY_PORT=1998
fi
if [ " $servicetag" = " " ] ; then
	tag=$DANE_PORT
else
	tag=$servicetag
fi
if [ $nooverwrite -eq 1 -a -d "$DESTDIR"$SERVICEDIR/qmail-daned.$tag/variables ] ; then
	return 0
fi
conf_dir="$DESTDIR"$SERVICEDIR/qmail-daned.$tag/variables
if [ $run_file_only -eq 1 ] ; then
	if [ -d $conf_dir ] ; then
		/bin/mv $conf_dir "$conf_dir".bak
	fi
fi
/bin/mkdir -p "$DESTDIR"$SERVICEDIR/qmail-daned.$tag/log
if [ $down_state -eq 1 ] ; then
	$TOUCH "$DESTDIR"$SERVICEDIR/qmail-daned.$tag/down
fi
/bin/mkdir -p $conf_dir
/bin/chmod 500 $conf_dir
if [ " $ipaddress" = " " ] ; then
	echo 127.0.0.1 > $conf_dir/LOCALIP
else
	echo $ipaddress > $conf_dir/LOCALIP
fi
echo $DANE_PORT > $conf_dir/PORT
if [ ! " $CONTROLDIR" = " " ] ; then
	echo "$CONTROLDIR" > $conf_dir/CONTROLDIR
else
	> $conf_dir/CONTROLDIR
fi
if [ ! " $memory" = " " ] ; then
	echo $memory > $conf_dir/SOFT_MEM
else
	echo 52428800 > $conf_dir/SOFT_MEM
fi
echo "$libexecdir/daneprog" > $conf_dir/DANEPROG
WHITELIST=$CONTROLDIR/$WHITELIST
CONTEXT_FILE=$CONTROLDIR/$CONTEXT_FILE

(
echo "#!/bin/sh"
echo "$RCSID"
echo "# generated on $host on `date`"
echo "# $prog_args"
echo ""
echo "exec 2>&1"
echo "exec $QmailBinPrefix/bin/envdir variables sh -c \""
echo "exec $QmailBinPrefix/bin/setuidgid indimail \\"
echo "  $QmailBinPrefix/sbin/qmail-daned -w $WHITELIST -t $TIMEOUT_DAYS \\"
echo "  -s $SAVE_INTERVAL -h $HASH_SIZE \\\$LOCALIP $CONTEXT_FILE\""
) > "$DESTDIR"$SERVICEDIR/qmail-daned.$tag/run
/bin/chmod +x "$DESTDIR"$SERVICEDIR/qmail-daned.$tag/run

# qmail-daned log script
if [ ! -d $LOGDIR ] ; then
	/bin/mkdir -p $LOGDIR
	$chown qmaill:nofiles $LOGDIR
fi
(
echo "#!/bin/sh"
echo "$RCSID"
echo "# generated on $host on `date`"
echo "# $prog_args"
echo ""
echo "exec $QmailBinPrefix/bin/setuidgid qmaill \\"
echo "$QmailBinPrefix/sbin/multilog t $LOGDIR/daned.$tag"
) > "$DESTDIR"$SERVICEDIR/qmail-daned.$tag/log/run
/bin/chmod +x "$DESTDIR"$SERVICEDIR/qmail-daned.$tag/log/run
echo "$prog_args" > $conf_dir/.options

if [ $run_file_only -eq 1 ] ; then
	if [ -d "$conf_dir".bak ] ; then
		/bin/rm -rf $conf_dir
		/bin/mv "$conf_dir".bak $conf_dir
	fi
fi
}

create_greylist()
{
if [ $# -ne 10 ] ; then
	echo "USAGE: create_greylist supervise_dir port min_resend_min resend_win_hr timeout_days context_file save_interval hash_size whitelist use-greydaemon" 1>&2
	return 1
fi
SERVICEDIR=$1
GREY_PORT=$2
MIN_RESEND_MIN=$3
RESEND_WIN_HR=$4
TIMEOUT_DAYS=$5
CONTEXT_FILE=$6
SAVE_INTERVAL=$7
HASH_SIZE=$8
WHITELIST=$9
shift
GREYDAEMON="$9"
if [ " $GREY_PORT" = " " ] ; then
	GREY_PORT=1999
fi
if [ " $servicetag" = " " ] ; then
	tag=$GREY_PORT
else
	tag=$servicetag
fi
if [ $nooverwrite -eq 1 -a -d "$DESTDIR"$SERVICEDIR/greylist.$tag/variables ] ; then
	return 0
fi
conf_dir="$DESTDIR"$SERVICEDIR/greylist.$tag/variables
if [ $run_file_only -eq 1 ] ; then
	if [ -d $conf_dir ] ; then
		/bin/mv $conf_dir "$conf_dir".bak
	fi
fi
/bin/mkdir -p "$DESTDIR"$SERVICEDIR/greylist.$tag/log
if [ $down_state -eq 1 ] ; then
	$TOUCH "$DESTDIR"$SERVICEDIR/greylist.$tag/down
fi
/bin/mkdir -p $conf_dir
/bin/chmod 500 $conf_dir
if [ " $ipaddress" = " " ] ; then
	echo 127.0.0.1 > $conf_dir/LOCALIP
else
	echo $ipaddress > $conf_dir/LOCALIP
fi
echo $GREY_PORT > $conf_dir/PORT
if [ ! " $CONTROLDIR" = " " ] ; then
	echo "$CONTROLDIR" > $conf_dir/CONTROLDIR
else
	> $conf_dir/CONTROLDIR
fi
if [ ! " $memory" = " " ] ; then
	echo $memory > $conf_dir/SOFT_MEM
else
	echo 52428800 > $conf_dir/SOFT_MEM
fi
if [ " $GREYDAEMON" = " " ] ; then
	GREYPROG=$QmailBinPrefix/sbin/qmail-greyd
else
	GREYPROG=$QmailBinPrefix/sbin/greydaemon
fi
WHITELIST=$CONTROLDIR/$WHITELIST
CONTEXT_FILE=$CONTROLDIR/$CONTEXT_FILE

(
echo "#!/bin/sh"
echo "$RCSID"
echo "# generated on $host on `date`"
echo "# $prog_args"
echo ""
echo "exec 2>&1"
echo "exec $QmailBinPrefix/bin/envdir variables sh -c \""
echo "exec $QmailBinPrefix/bin/setuidgid indimail \\"
echo "$QmailBinPrefix/bin/softlimit -m \\\$SOFT_MEM -o 1024 \\"
echo " $GREYPROG -w $WHITELIST -t $TIMEOUT_DAYS -g $RESEND_WIN_HR \\"
if [ " $GREYDAEMON" = " " ] ; then
echo "	-m $MIN_RESEND_MIN -s $SAVE_INTERVAL -h $HASH_SIZE \\\$LOCALIP $CONTEXT_FILE\""
else
echo "	-m $MIN_RESEND_MIN -s $SAVE_INTERVAL \\\$LOCALIP $CONTEXT_FILE\""
fi
) > "$DESTDIR"$SERVICEDIR/greylist.$tag/run
/bin/chmod +x "$DESTDIR"$SERVICEDIR/greylist.$tag/run

# greylist log script
if [ ! -d $LOGDIR ] ; then
	/bin/mkdir -p $LOGDIR
	$chown qmaill:nofiles $LOGDIR
fi
(
echo "#!/bin/sh"
echo "$RCSID"
echo "# generated on $host on `date`"
echo "# $prog_args"
echo ""
echo "exec $QmailBinPrefix/bin/setuidgid qmaill \\"
echo "$QmailBinPrefix/sbin/multilog t $LOGDIR/greylist.$tag"
) > "$DESTDIR"$SERVICEDIR/greylist.$tag/log/run
/bin/chmod +x "$DESTDIR"$SERVICEDIR/greylist.$tag/log/run
echo "$prog_args" > $conf_dir/.options

if [ $run_file_only -eq 1 ] ; then
	if [ -d "$conf_dir".bak ] ; then
		/bin/rm -rf $conf_dir
		/bin/mv "$conf_dir".bak $conf_dir
	fi
fi
}

create_courier()
{
if [ $# -ne 7 ] ; then
	echo "USAGE: create_courier supervise_dir type port nolastauth=0|1 legacyserver=0|1 use_ssl=0|1 infifo=fifo_path" 1>&2
	return 1
fi
SERVICEDIR=$1
stype=$2
COURIER_PORT=$3
nolastauth=$4
legacyserver=$5
imap_ssl=$6
infifo=$7

if [ " $servicetag" = " " ] ; then
	tag=$COURIER_PORT
else
	tag=$servicetag
fi
if [ " $stype" = " pop3d" ] ; then
	cdb_f="pop3"
elif [ " $stype" = " imapd" ] ; then
	cdb_f="imap"
else
	echo "USAGE: create_courier supervise_dir type port nolastauth=0|1 legacyserver=0|1 use_ssl=0|1 infifo=fifo_path" 1>&2
	return 1
fi
if [ " $proxy_port" = " " ] ;then
	proxy_type="qmail"
else
	proxy_type="proxy"
fi
if [ " $imap_ssl" = " 1" ] ; then
	if [ $nooverwrite -eq 1 -a -d "$DESTDIR"$SERVICEDIR/"$proxy_type"-$stype-ssl.$tag/variables ] ; then
		return 0
	fi
	/bin/mkdir -p "$DESTDIR"$SERVICEDIR/"$proxy_type"-$stype-ssl.$tag/log
	conf_dir="$DESTDIR"$SERVICEDIR/"$proxy_type"-$stype-ssl.$tag/variables
else
	if [ $nooverwrite -eq 1 -a -d "$DESTDIR"$SERVICEDIR/"$proxy_type"-$stype.$tag/variables ] ; then
		return 0
	fi
	/bin/mkdir -p "$DESTDIR"$SERVICEDIR/"$proxy_type"-$stype.$tag/log
	conf_dir="$DESTDIR"$SERVICEDIR/"$proxy_type"-$stype.$tag/variables
fi
if [ $down_state -eq 1 ] ; then
	$TOUCH "$DESTDIR"$SERVICEDIR/"$proxy_type"-$stype.$tag/down
fi
if [ $run_file_only -eq 1 ] ; then
	if [ -d $conf_dir ] ; then
		/bin/mv $conf_dir "$conf_dir".bak
	fi
fi
if [ -d $conf_dir ] ; then
	echo "moving $conf_dir/.variables to $conf_dir.$ext"
	/bin/mv $conf_dir/.variables $conf_dir.vsafe
	/bin/mv $conf_dir $conf_dir.safe
fi
if [ " $imap_ssl" = " 1" ] ; then
	# /service/[qmail|proxy]-[pop3d|imapd]-ssl.nnn/variables
	(
	create_"$cdb_f"_config $COURIER_PORT $infifo
	create_"$cdb_f"_config_ssl
	) > $conf_dir
else
	# /service/[qmail|proxy]-[pop3d|imapd].nnn/variables
	# this will have all variables of "$cdb_f"_config_ssl also
	create_"$cdb_f"_config $COURIER_PORT $infifo > $conf_dir
fi
# read all variables in $conf_dir file.
# delete $conf_dir file
# create $conf_dir directory
# create $conf_dir variables for supervise
if [ -x "$DESTDIR"$libexecdir/envmigrate ] ; then
	"$DESTDIR"$libexecdir/envmigrate $conf_dir root indimail 550
else
	echo "Unable to execute envmigrate" 1>&2
	return 1
fi
if [ ! -d $conf_dir ] ; then
	echo "$conf_dir: No such file or directory" 1>&2
	if [ -d $conf_dir.safe ] ; then
		/bin/mv $conf_dir.safe $conf_dir
	fi
	if [ -f $conf_dir.vsafe ] ; then
		/bin/mv $conf_dir.vsafe $conf_dir/.variables
	fi
	return 1
else
	/bin/rm -rf $conf_dir.safe $conf_dir.vsafe
fi
if [ ! " $memory" = " " ] ; then
	echo $memory > $conf_dir/SOFT_MEM
else
	echo 5242880 > $conf_dir/SOFT_MEM
fi
if [ ! " $domainlimits" = " " ] ; then
	echo  > $conf_dir/DOMAIN_LIMITS
else
	> $conf_dir/DOMAIN_LIMITS
fi
if [ " $query_cache" = " " ] ; then
	> $conf_dir/QUERY_CACHE
else
	echo > $conf_dir/QUERY_CACHE
fi
(
echo "#!/bin/sh"
echo "$RCSID"
echo "# generated on $host on `date`"
echo "# $prog_args"
echo ""
echo "INDIUID=\`/usr/bin/id -u indimail\`"
echo "INDIGID=\`/usr/bin/id -g indimail\`"
echo "HOSTNAME=\`uname -n\`"
echo ""
echo "prefix=$QmailBinPrefix"
echo "bindir=\${prefix}/bin"
echo "libexecdir=${libexecdir}"
echo ""
echo "exec 2>&1"
echo "exec $QmailBinPrefix/bin/envdir variables sh -c \""
echo "IMAPAUTHMODULES=\\\"\\\""
echo "for f in \\\`echo \\\$IMAPMODULES\\\`"
echo "do"
echo "	IMAPAUTHMODULES=\\\"\\\$IMAPAUTHMODULES \$libexecdir/imapmodules/\\\$f\\\""
echo "done"
echo "exec $QmailBinPrefix/bin/softlimit -m \\\$SOFT_MEM -o 1024 \\"
echo "$QmailBinPrefix/bin/tcpserver -v -c variables/MAXDAEMONS -C \\\$MAXPERIP \\"
echo "-x $sysconfdir/tcp/tcp.$cdb_f.cdb -X \\"
if [ " $imap_ssl" = " 1" ] ; then
	echo "-o -b \\\$MAXDAEMONS -H -l \$HOSTNAME -R -u \$INDIUID -g \$INDIGID \\\$SSLADDRESS \\\$SSLPORT \\"
	echo "\$prefix/bin/couriertls -server -tcpd \\"
else
	echo "-o -b \\\$MAXDAEMONS -H -l \$HOSTNAME -R -u \$INDIUID -g \$INDIGID \\\$LOCALIP \\\$PORT \\"
fi
if [ " $proxy_port" = " " ] ;then
	echo "\$prefix/sbin/"$cdb_f"login \\\$IMAPAUTHMODULES \$bindir/$stype Maildir\""
else
	echo "$QmailBinPrefix/bin/proxy"$cdb_f" \$bindir/$stype Maildir\""
fi
) > /tmp/courier-run.$$

if [ " $imap_ssl" = " 1" ] ; then
	/bin/mv /tmp/courier-run.$$ "$DESTDIR"$SERVICEDIR/"$proxy_type"-$stype-ssl.$tag/run
	/bin/chmod +x "$DESTDIR"$SERVICEDIR/"$proxy_type"-$stype-ssl.$tag/run
else
	/bin/mv /tmp/courier-run.$$ "$DESTDIR"$SERVICEDIR/"$proxy_type"-$stype.$tag/run
	/bin/chmod +x "$DESTDIR"$SERVICEDIR/"$proxy_type"-$stype.$tag/run
fi

if [ ! -d $LOGDIR ] ; then
	/bin/mkdir -p $LOGDIR
	$chown qmaill:nofiles $LOGDIR
fi
# qmail-[imapd|pop3d] log script
(
echo "#!/bin/sh"
echo "$RCSID"
echo "# generated on $host on `date`"
echo "# $prog_args"
echo ""
echo "exec $QmailBinPrefix/bin/setuidgid qmaill \\"
if [ " $proxy_port" = " " ] ;then
	if [ " $imap_ssl" = " 1" ] ; then
		echo "$QmailBinPrefix/sbin/multilog t $LOGDIR/$stype-ssl.$tag"
	else
		echo "$QmailBinPrefix/sbin/multilog t $LOGDIR/$stype.$tag"
	fi
else
	echo "$QmailBinPrefix/sbin/multilog t $LOGDIR/proxy"`echo $cdb_f|tr '[:lower:]' '[:upper:]'`".$tag"
fi
) > /tmp/courierlog-run.$$
if [ " $imap_ssl" = " 1" ] ; then
	/bin/mv /tmp/courierlog-run.$$ "$DESTDIR"$SERVICEDIR/"$proxy_type"-$stype-ssl.$tag/log/run
	/bin/chmod +x "$DESTDIR"$SERVICEDIR/"$proxy_type"-$stype-ssl.$tag/log/run
else
	/bin/mv /tmp/courierlog-run.$$ "$DESTDIR"$SERVICEDIR/"$proxy_type"-$stype.$tag/log/run
	/bin/chmod +x "$DESTDIR"$SERVICEDIR/"$proxy_type"-$stype.$tag/log/run
fi
echo "$prog_args" > $conf_dir/.options

if [ $run_file_only -eq 1 ] ; then
	if [ -d "$conf_dir".bak ] ; then
		/bin/rm -rf $conf_dir
		/bin/mv "$conf_dir".bak $conf_dir
	fi
fi
}

create_imap_config()
{
echo "#--------- IndiMail ---------------------------"
echo "DEFAULT_DOMAIN=$default_domain"
echo "MIGRATEUSER=$QmailBinPrefix/bin/migrateuser"
echo "MIGRATEFLAG=indi.txt"
echo "TCP_FILE=$sysconfdir/tcp/tcp.imap"
echo "OPEN_SMTP=$sysconfdir/tcp/open-smtp"
echo "RELAY_TABLE=relay"
echo "MCDFILE=mcdinfo"
IMAP_PORT=$1
if [ " $IMAP_PORT" = " " ] ; then
	echo "PORT=143"
else
	echo "PORT=$IMAP_PORT"
fi
base_fifo_name=`basename $2`
fifo_dir=`dirname $2`
if [ $fifo_dir = "." ] ; then
	fifo_dir=$QmailHOME/inquery
fi
echo "INFIFO=$base_fifo_name"
echo "FIFODIR=$fifo_dir"

if [ " $ipaddress" = " " ] ; then
	echo "LOCALIP=0"
	echo "SSLADDRESS=0"
else
	echo "LOCALIP=$ipaddress"
	echo "SSLADDRESS=$ipaddress"
fi
if [ ! " $nolastauth" = " " ] ; then
	echo "NOLASTAUTHLOGGING=1"
else
	echo "NOLASTAUTHLOGGING="
fi
echo "QMAILDEFAULTHOST=$default_domain" # Used if mail is stored in outbox
if [ ! " $proxy_port" = " " ] ;then
	echo "#--------- ADDED FOR Proxy IMAP ---------------"
	echo "ADMIN_HOST=localhost"
	echo "ADMIN_PORT=4000"
	echo "ADMIN_USER=admin"
	echo "ADMIN_PASS=$ADMIN_PASS"
	echo "HARD_QUOTA=$hard_quota"
	echo "DATA_TIMEOUT=1"
	echo "DESTPORT=imap:$proxy_port"
	if [ ! " $legacyserver" = " " ] ; then
		echo "LEGACY_SERVER=1"
	else
		echo "LEGACY_SERVER="
	fi
else
	echo "DESTPORT="
fi
echo "#----------------------------------------------"
echo "MIN_LOGIN_INTERVAL=0"
if [ ! " $maxdaemons" = " " ] ; then
	echo "MAXDAEMONS=$maxdaemons"
else
	echo "MAXDAEMONS=$CONCURRENCYINCOMING"
fi
if [ ! " $maxperip" = " " ] ; then
	echo "MAXPERIP=$maxperip"
else
	echo "MAXPERIP=25"
fi
MODULES=""
for i in `ls $DESTDIR"$libexecdir"/imapmodules`
do
	if [ " $i" = " authgeneric" -o " $i" = " authtest" -o " $i" = " authpam" ] ; then
		continue
	fi
	if [ -n "$MODULES" ] ; then
		MODULES="$MODULES $i"
	else
		MODULES="$i"
	fi
done
if [ -f $DESTDIR"$libexecdir"/imapmodules/authpam ] ; then
	MODULES="$MODULES authpam"
fi
echo "IMAPMODULES=\"$MODULES\""
echo "DEBUG_LOGIN=0"
IMAP_CAPABILITY="IMAP4rev1 UIDPLUS CHILDREN NAMESPACE THREAD=ORDEREDSUBJECT THREAD=REFERENCES SORT QUOTA IDLE"
echo "#SMAP_CAPABILITY=SMAP1"
echo "IMAP_KEYWORDS=1"
echo "IMAP_DISABLETHREADSORT=0"
echo "IMAP_CHECK_ALL_FOLDERS=0"
echo "IMAP_OBSOLETE_CLIENT=0"
echo "IMAP_UMASK=022"
echo "IMAP_USELOCKS=0"
echo "IMAP_ENHANCEDIDLE=1"
echo "IMAP_IDLE_TIMEOUT=60"
echo "IMAP_TRASHFOLDERNAME=Trash"
echo "IMAP_EMPTYTRASH=Trash:7"
echo "IMAP_MOVE_EXPUNGE_TO_TRASH=0"
echo "IMAP_LOG_DELETIONS=0"
echo "IMAPDEBUGFILE=imap-debug.txt"
echo "OUTBOX=.Outbox"
echo "SENDMAIL=$QmailBinPrefix/bin/sendmail"
echo "HEADERFROM=X-IMAP-Sender"
echo "IMAP_SHAREDINDEXFILE=$sysconfdir/shared/index"
echo "MAILDIRPATH=Maildir"
echo "IMAP_CAPABILITY=\"$IMAP_CAPABILITY AUTH=LOGIN AUTH=PLAIN AUTH=CRAM-MD5 AUTH=CRAM-SHA1 AUTH=CRAM-SHA256\""

# IMAP_STARTTLS, IMAP_TLS_REQUIRED, COURIERTLS required for advertising STARTTLS
if [ $use_starttls -eq 1 ] ; then
	echo "IMAP_STARTTLS=YES"
	echo "IMAP_TLS_REQUIRED=0"
	if [ " $tlsprog" = " " ] ; then
		echo "COURIERTLS=$QmailBinPrefix/bin/couriertls"
	else
		echo "COURIERTLS=$tlsprog"
	fi
	create_imap_config_ssl
fi
}

create_imap_config_ssl()
{
if [ " $IMAP_PORT" = " " ] ; then
	echo "SSLPORT=993"
else
	echo "SSLPORT=$IMAP_PORT"
fi
if [ " $ipaddress" = " " ] ; then
	echo "SSLADDRESS=0"
else
	echo "SSLADDRESS=$ipaddress"
fi
echo "IMAP_CAPABILITY_TLS=\"$IMAP_CAPABILITY\""
echo "TLS_PROTOCOL=SSL23"
echo "TLS_STARTTLS_PROTOCOL=TLS1"
echo "# TLS_CIPHER_LIST=\"TLSv1:HIGH:!LOW:!MEDIUM:!EXP:!NULL:!aNULL@STRENGTH\""
echo "##NAME: TLS_TIMEOUT:0"
echo "# TLS_TIMEOUT is currently not implemented, and reserved for future use."
echo "# This is supposed to be an inactivity timeout, but its not yet implemented."
echo "#"
echo "TLS_CERTFILE=$sysconfdir/certs/servercert.pem"
echo "TLS_DHPARAMS=$sysconfdir/certs/dhparams.pem"
echo "# TLS_TRUSTCERTS="
echo "TLS_VERIFYPEER=NONE"
echo "TLS_CACHEFILE=$sysconfdir/certs/couriersslcache"
echo "TLS_CACHESIZE=524288"
}

create_ssl_cnf()
{
if [ $# -ne 2 ] ; then
	echo "USAGE: create_ssl_cnf postmaster IMAP|POP3" 1>&2
	return 1
fi
postmaster=$1
cn=$2
echo
echo "RANDFILE = $sysconfdir/certs/servercert.rand"
echo
echo "[ req ]"
echo "default_bits = 4096"
echo "encrypt_key = yes"
echo "distinguished_name = req_dn"
echo "x509_extensions = cert_type"
echo "prompt = no"
echo "default_md = sha256"
echo
echo "[v3_req]"
echo "subjectAltName = DNS:$cn"
echo
echo "[ req_dn ]"
echo "C=IN"
echo "ST=GOA"
echo "L=Porvorim"
echo "O=IndiMail Server"
echo "OU=Automatically-generated SSL key"
echo "CN=$cn"
echo "emailAddress=$postmaster"
echo
echo "[ cert_type ]"
echo "nsCertType = server"
}

create_imap_stunnel()
{
if [ " $ipaddress" = " " ] ; then
	SSLADDRESS=0
else
	SSLADDRESS=$ipaddress
fi
echo "[imapd]"
echo "accept = $SSLADDRESS:993"
echo "protocol = imap"
echo "connect = $SSLADDRESS:143"
echo "cert = $sysconfdir/certs/servercert.pem"
}

create_pop3_stunnel()
{
if [ " $ipaddress" = " " ] ; then
	SSLADDRESS=0
else
	SSLADDRESS=$ipaddress
fi
echo "[pop3d]"
echo "accept = $SSLADDRESS:995"
echo "protocol = pop3"
echo "connect = $SSLADDRESS:110"
echo "cert = $sysconfdir/certs/servercert.pem"
}

create_pop3_config()
{
echo "#--------- IndiMail ---------------------------"
echo "DEFAULT_DOMAIN=$default_domain"
echo "MIGRATEUSER=$QmailBinPrefix/bin/migrateuser"
echo "MIGRATEFLAG=indi.txt"
echo "TCP_FILE=$sysconfdir/tcp/tcp.pop3"
echo "OPEN_SMTP=$sysconfdir/tcp/open-smtp"
echo "RELAY_TABLE=relay"
echo "MCDFILE=mcdinfo"
POP3_PORT=$1
if [ " $POP3_PORT" = " " ] ; then
	echo "PORT=110"
else
	echo "PORT=$POP3_PORT"
fi
base_fifo_name=`basename $2`
fifo_dir=`dirname $2`
if [ $fifo_dir = "." ] ; then
	fifo_dir=$QmailHOME/inquery
fi
echo "INFIFO=$base_fifo_name"
echo "FIFODIR=$fifo_dir"

if [ " $ipaddress" = " " ] ; then
	echo "LOCALIP=0"
else
	echo "LOCALIP=$ipaddress"
fi
if [ ! " $nolastauth" = " " ] ; then
	echo "NOLASTAUTHLOGGING=\"\""
else
	echo "NOLASTAUTHLOGGING="
fi
if [ ! " $proxy_port" = " " ] ;then
	echo "#--------- ADDED FOR Proxy POP3 ----------------"
	echo "ADMIN_HOST=localhost"
	echo "ADMIN_PORT=4000"
	echo "ADMIN_USER=admin"
	echo "ADMIN_PASS=$ADMIN_PASS"
	echo "HARD_QUOTA=$hardquota"
	echo "DATA_TIMEOUT=1"
	echo "DESTPORT=pop3:$proxy_port"
	if [ ! " $legacyserver" = " " ] ; then
		echo "LEGACY_SERVER=1"
	else
		echo "LEGACY_SERVER="
	fi
else
	echo "DESTPORT="
fi
echo "#-----------------------------------------------"
echo "MIN_LOGIN_INTERVAL=0"
if [ ! " $maxdaemons" = " " ] ; then
	echo "MAXDAEMONS=$maxdaemons"
else
	echo "MAXDAEMONS=$CONCURRENCYINCOMING"
fi
if [ ! " $maxperip" = " " ] ; then
	echo "MAXPERIP=$maxperip"
else
	echo "MAXPERIP=25"
fi
MODULES=""
for i in `ls $DESTDIR"$libexecdir"/imapmodules`
do
	if [ " $i" = " authgeneric" -o " $i" = " authtest" -o " $i" = " authpam" ] ; then
		continue
	fi
	if [ -n "$MODULES" ] ; then
		MODULES="$MODULES $i"
	else
		MODULES="$i"
	fi
done
if [ -f $DESTDIR"$libexecdir"/imapmodules/authpam ] ; then
	MODULES="$MODULES authpam"
fi
echo "IMAPMODULES=\"$MODULES\""
echo "DEBUG_LOGIN=0"
echo "POP3AUTH=\"LOGIN PLAIN CRAM-MD5 CRAM-SHA1 CRAM-SHA256\""

# POP3_STARTTLS, POP3_TLS_REQUIRED, COURIERTLS required for advertising STARTTLS
if [ $use_starttls -eq 1 ] ; then
	echo "POP3_STARTTLS=YES"
	echo "POP3_TLS_REQUIRED=0"
	if [ " $tlsprog" = " " ] ; then
		echo "COURIERTLS=$QmailBinPrefix/bin/couriertls"
	else
		echo "COURIERTLS=$tlsprog"
	fi
	create_pop3_config_ssl
fi
}

create_pop3_config_ssl()
{
if [ " $POP3_PORT" = " " ] ; then
	echo "SSLPORT=995"
else
	echo "SSLPORT=$POP3_PORT"
fi
if [ " $ipaddress" = " " ] ; then
	echo "SSLADDRESS=0"
else
	echo "SSLADDRESS=$ipaddress"
fi
echo "POP3AUTH_TLS=\"$POP3AUTH\""
echo "TLS_PROTOCOL=SSL23"
echo "TLS_STARTTLS_PROTOCOL=TLS1"
echo "# TLS_CIPHER_LIST=\"TLSv1:HIGH:!LOW:!MEDIUM:!EXP:!NULL:!aNULL@STRENGTH\""
echo "##NAME: TLS_TIMEOUT:0"
echo "# TLS_TIMEOUT is currently not implemented, and reserved for future use."
echo "# This is supposed to be an inactivity timeout, but its not yet implemented."
echo "#"
echo "TLS_CERTFILE=$sysconfdir/certs/servercert.pem"
echo "TLS_DHPARAMS=$sysconfdir/certs/dhparams.pem"
echo "# TLS_TRUSTCERTS="
echo "TLS_VERIFYPEER=NONE"
echo "TLS_CACHEFILE=$sysconfdir/certs/couriersslcache"
echo "TLS_CACHESIZE=524288"
}

create_indisrvr()
{
if [ $# -ne 9 ] ; then
	echo "create_indisrvr bind_port [mysql_host mysql_user mysql_pass] avg_user_quota hard_quota base_path servicedir use_ssl=0|1" 1>&2
	return 1
fi
BIND_PORT=$1
CNTRL_HOST=$2
CNTRL_USER=$3
CNTRL_PASS=$4
AVG_USER_QUOTA=$5
HARD_QUOTA=$6
BASE_PATH=$7
SERVICEDIR=$8
indisrvr_ssl=$9
if [ " $indisrvr_ssl" = " 1" -a " $certfile" = " " ] ; then
	echo "Certificate not specfied" 1>&2
	return 1
fi

if [ " $servicetag" = " " ] ; then
	tag=$BIND_PORT
else
	tag=$servicetag
fi
if [ $nooverwrite -eq 1 -a -d "$DESTDIR"$SERVICEDIR/indisrvr.$tag/variables ] ; then
	return 0
fi
conf_dir="$DESTDIR"$SERVICEDIR/indisrvr.$tag/variables
if [ $run_file_only -eq 1 ] ; then
	if [ -d $conf_dir ] ; then
		/bin/mv $conf_dir "$conf_dir".bak
	fi
fi
/bin/mkdir -p "$DESTDIR"$SERVICEDIR/indisrvr.$tag/log
if [ $down_state -eq 1 ] ; then
	$TOUCH "$DESTDIR"$SERVICEDIR/indisrvr.$tag/down
fi
/bin/mkdir -p $conf_dir
$chown root:indimail $conf_dir
/bin/chmod 550 $conf_dir
if [ " $ipaddress" = " " ] ; then
	echo "0" > $conf_dir/LOCALIP
else
	echo "$ipaddress" > $conf_dir/LOCALIP
fi
if [ ! " $maxdaemons" = " " ] ; then
	echo "$maxdaemons" > $conf_dir/MAXDAEMONS
else
	echo "$CONCURRENCYINCOMING" > $conf_dir/MAXDAEMONS
fi
if [ ! " $maxperip" = " " ] ; then
	echo "$maxperip" > $conf_dir/MAXPERIP
else
	echo "10" > $conf_dir/MAXPERIP
fi
echo $sysconfdir/indimail.cnf > $conf_dir/MYSQL_READ_DEFAULT_FILE
echo $BIND_PORT   > $conf_dir/PORT
if [ -n "$CNTRL_HOST" ] ; then
	echo $CNTRL_HOST  > $conf_dir/CNTRL_HOST
	if [ -n "$CNTRL_USER" ] ; then
		echo $CNTRL_USER  > $conf_dir/CNTRL_USER
	else
		> $conf_dir/CNTRL_USER
	fi
	if [ -n "$CNTRL_PASS" ] ; then
		echo $CNTRL_PASS  > $conf_dir/CNTRL_PASSWD
	else
		> $conf_dir/CNTRL_PASSWD
	fi
else
	> $conf_dir/CNTRL_HOST
	> $conf_dir/CNTRL_USER
	> $conf_dir/CNTRL_PASSWD
fi
echo $AVG_USER_QUOTA > $conf_dir/AVG_USER_QUOTA
echo $HARD_QUOTA > $conf_dir/HARD_QUOTA
echo $base_path > $conf_dir/BASE_PATH
if [ ! " $domainlimits" = " " ] ; then
	echo > $conf_dir/DOMAIN_LIMITS
else
	> $conf_dir/DOMAIN_LIMITS
fi
if [ " $indisrvr_ssl" = " 1" ] ; then
	echo $certfile > $conf_dir/CERTFILE
else
	> $conf_dir/CERTFILE
fi
echo 1 > $conf_dir/MYSQL_OPT_RECONNECT
(
echo "#!/bin/sh"
echo "$RCSID"
echo "# generated on $host on `date`"
echo "# $prog_args"
echo ""
echo "if [ ! -f \$CERTFILE ]; then"
echo "    echo Certificate not present"
echo "    sleep 5"
echo "    exit 1"
echo "fi"
echo ""
echo "exec 2>&1"
echo "exec $QmailBinPrefix/bin/envdir variables sh -c \""
echo "exec $QmailBinPrefix/bin/setuidgid indimail \\"
if [ " $indisrvr_ssl" = " 1" ] ; then
	echo "$QmailBinPrefix/sbin/indisrvr -i \\\$LOCALIP -p \\\$PORT -b \\\$MAXDAEMONS \\"
	echo "-n \\\$CERTFILE\""
else
	echo "$QmailBinPrefix/sbin/indisrvr -i \\\$LOCALIP -p \\\$PORT -b \\\$MAXDAEMONS\""
fi
) > "$DESTDIR"$SERVICEDIR/indisrvr.$tag/run
/bin/chmod +x "$DESTDIR"$SERVICEDIR/indisrvr.$tag/run

if [ ! -d $LOGDIR ] ; then
	/bin/mkdir -p $LOGDIR
	$chown qmaill:nofiles $LOGDIR
fi
# indisrvr log script
(
echo "#!/bin/sh"
echo "$RCSID"
echo "# generated on $host on `date`"
echo "# $prog_args"
echo ""
echo "exec $QmailBinPrefix/bin/setuidgid qmaill \\"
echo "$QmailBinPrefix/sbin/multilog t $LOGDIR/indisrvr.$tag"
) > "$DESTDIR"$SERVICEDIR/indisrvr.$tag/log/run
/bin/chmod +x "$DESTDIR"$SERVICEDIR/indisrvr.$tag/log/run
echo "$prog_args" > $conf_dir/.options

if [ $run_file_only -eq 1 ] ; then
	if [ -d "$conf_dir".bak ] ; then
		/bin/rm -rf $conf_dir
		/bin/mv "$conf_dir".bak $conf_dir
	fi
fi
}

create_qscanq()
{
if [ $# -ne 1 ] ; then
	echo "USAGE: create_qscanq supervise_dir"
	return 1
fi
SERVICEDIR=$1
conf_dir="$DESTDIR"$SERVICEDIR/qscanq/variables
if [ $nooverwrite -eq 1 -a -d $conf_dir ] ; then
	return 0
fi
if [ $run_file_only -eq 1 ] ; then
	if [ -d $conf_dir ] ; then
		/bin/mv $conf_dir "$conf_dir".bak
	fi
fi
# set permissions for qscand-stdin to allow svc -o /service/qscanq
/bin/mkdir -p  "$DESTDIR"$SERVICEDIR/qscanq/supervise
$chown qscand:root "$DESTDIR"$SERVICEDIR/qscanq/supervise
if [ ! -f "$DESTDIR"$SERVICEDIR/qscanq/supervise/control ] ; then
	/usr/bin/mkfifo "$DESTDIR"$SERVICEDIR/qscanq/supervise/control > /dev/null 2>&1
fi
/bin/chmod 660 "$DESTDIR"$SERVICEDIR/qscanq/supervise/control
$chown qscand:root "$DESTDIR"$SERVICEDIR/qscanq/supervise/control

/bin/mkdir -p "$DESTDIR"$SERVICEDIR/qscanq/log
if [ $down_state -eq 1 ] ; then
	$TOUCH "$DESTDIR"$SERVICEDIR/qscanq/down
fi
/bin/mkdir -p $conf_dir
/bin/chmod 500 $conf_dir
$chown qscand "$DESTDIR"$SERVICEDIR/qscanq

# qscanq script
(
echo "#!/bin/sh"
echo "$RCSID"
echo "# generated on $host on `date`"
echo "# $prog_args"
echo ""
echo "exec 2>&1"
if [ " $scan_interval" = " " ] ; then
	scan_interval=10
fi
echo "exec $QmailBinPrefix/bin/setuidgid qscand $QmailBinPrefix/sbin/cleanq \\"
echo "  -l -s $scan_interval $QmailHOME/qscanq/root/scanq"
) > "$DESTDIR"$SERVICEDIR/qscanq/run
/bin/chmod +x "$DESTDIR"$SERVICEDIR/qscanq/run

if [ ! -d $LOGDIR ] ; then
	/bin/mkdir -p $LOGDIR
	$chown qmaill:nofiles $LOGDIR
fi
# qscanq log script
(
echo "#!/bin/sh"
echo "$RCSID"
echo "# generated on $host on `date`"
echo "# $prog_args"
echo ""
echo "exec $QmailBinPrefix/bin/setuidgid qmaill \\"
echo "$QmailBinPrefix/sbin/multilog t \\"
#echo "	'-* cleanq starting' '-* deleting: *: not sticky' \\"
echo "$LOGDIR/qscanq"
) > "$DESTDIR"$SERVICEDIR/qscanq/log/run
/bin/chmod +x "$DESTDIR"$SERVICEDIR/qscanq/log/run
echo "$prog_args" > $conf_dir/.options

if [ $run_file_only -eq 1 ] ; then
	if [ -d "$conf_dir".bak ] ; then
		/bin/rm -rf $conf_dir
		/bin/mv "$conf_dir".bak $conf_dir
	fi
fi
}

create_clamd()
{
if [ $# -lt 2 ] ; then
	echo "USAGE: create_clamd clamdPrefix supervise_dir [sysconfdir]"
	return 1
fi
clamdPrefix=$1
SERVICEDIR=$2
if [ $# -gt 2 ] ; then
	mysysconfdir=$3
else
	mysysconfdir=$sysconfdir
fi
conf_dir="$DESTDIR"$SERVICEDIR/clamd/variables
if [ $nooverwrite -eq 1 -a -d $conf_dir ] ; then
	return 0
fi
if [ $run_file_only -eq 1 ] ; then
	if [ -d $conf_dir ] ; then
		/bin/mv $conf_dir "$conf_dir".bak
	fi
fi
/bin/mkdir -p "$DESTDIR"$SERVICEDIR/clamd/log
if [ $down_state -eq 1 ] ; then
	$TOUCH "$DESTDIR"$SERVICEDIR/clamd/down
fi
/bin/mkdir -p $conf_dir
/bin/chmod 500 $conf_dir
# clamd script
(
echo "#!/bin/sh"
echo "$RCSID"
echo "# generated on $host on `date`"
echo "# $prog_args"
echo ""
echo "exec 2>&1"
echo "CLAMD_SOCK=\`grep -w ^LocalSocket $mysysconfdir/scan.conf | awk '{print \$2}'\`"
echo "if [ -z \"\$CLAMD_SOCK\" ] ; then"
echo "	echo \"LocalSocket not defined in $mysysconfdir/scan.conf\" 1>&2"
echo "	sleep 10"
echo "	exit 1"
echo "fi"
echo "SOCKET_DIR=\`dirname \$CLAMD_SOCK\`"
echo "if [ ! -d \"\$SOCKET_DIR\" ] ; then"
echo "	/bin/mkdir -p \"\$SOCKET_DIR\""
echo "fi"
echo "if [ ! \"\$SOCKET_DIR\" = \"/tmp\" -a ! \"\$SOCKET_DIR\" = \"/\" ] ; then"
echo "  $chown qscand:qmail \"\$SOCKET_DIR\""
echo "  /bin/chmod 750 \"\$SOCKET_DIR\""
echo "fi"
echo ""
echo "# Check for a leftover socket."
echo "if [ -e \$CLAMD_SOCK ] ; then"
echo "	echo \"run: WARNING: file \$CLAMD_SOCK exists\""
echo "	SCAN_FILE=\$0"
echo "	if $clamdPrefix/bin/clamdscan \$SCAN_FILE --quiet --no-summary"
echo "	then"
echo "		echo \"run: FATAL: clamd is already running. quitting...\""
echo "		sleep 300"
echo "	else"
echo "		echo \"run: INFO: clamd is not running. Deleting \$CLAMD_SOCK\""
echo "		/bin/rm -f \$CLAMD_SOCK"
echo "	fi"
echo "fi"
echo ""
echo "dbd=\`grep -w \"^DatabaseDirectory\" $mysysconfdir/scan.conf | awk '{print \$2}'\`"
echo "if [ -z \"\$dbd\" ] ; then"
echo "	echo \"DatabaseDirectory not defined in $mysysconfdir/scan.conf\" 1>&2"
echo "	sleep 10"
echo "	exit 1"
echo "fi"
echo "if [ ! -f \$dbd/main.cvd -a ! -f \$dbd/main.cld ] ; then"
echo "	echo \"run: FATAL: no signatures found...\""
echo "	sleep 300"
echo "	exit 1"
echo "fi"
echo "fgd=\`grep -w \"^Foreground\" $mysysconfdir/scan.conf | awk '{print \$2}'\`"
echo "if [ -z \"\$fgd\" ] ; then"
echo "	echo \"Foreground not defined in $mysysconfdir/scan.conf\" 1>&2"
echo "	sleep 10"
echo "	exit 1"
echo "fi"
echo ""
echo "# Run the scanner daemon."
echo "exec $clamdPrefix/sbin/clamd \\"
echo "	--config-file=$mysysconfdir/scan.conf"
) > "$DESTDIR"$SERVICEDIR/clamd/run
/bin/chmod +x "$DESTDIR"$SERVICEDIR/clamd/run

if [ ! -d $LOGDIR ] ; then
	/bin/mkdir -p $LOGDIR
	$chown qmaill:nofiles $LOGDIR
fi
# clamd log script
(
echo "#!/bin/sh"
echo "$RCSID"
echo "# generated on $host on `date`"
echo "# $prog_args"
echo ""
echo "exec $QmailBinPrefix/bin/setuidgid qmaill \\"
echo "$QmailBinPrefix/sbin/multilog t $LOGDIR/clamd"
) > "$DESTDIR"$SERVICEDIR/clamd/log/run
/bin/chmod +x "$DESTDIR"$SERVICEDIR/clamd/log/run
echo "$prog_args" > $conf_dir/.options

if [ $run_file_only -eq 1 ] ; then
	if [ -d "$conf_dir".bak ] ; then
		/bin/rm -rf $conf_dir
		/bin/mv "$conf_dir".bak $conf_dir
	fi
fi

conf_dir="$DESTDIR"$SERVICEDIR/freshclam/variables
if [ $run_file_only -eq 1 ] ; then
	if [ -d $conf_dir ] ; then
		/bin/mv $conf_dir "$conf_dir".bak
	fi
fi
/bin/mkdir -p "$DESTDIR"$SERVICEDIR/freshclam/log
if [ $down_state -eq 1 ] ; then
	$TOUCH "$DESTDIR"$SERVICEDIR/freshclam/down
fi
/bin/mkdir -p $conf_dir
/bin/chmod 500 $conf_dir
qsysconfdir=/etc # weird tha clamd and freshclam do not share the same dir for config files
# freshclam script
(
echo "#!/bin/sh"
echo "$RCSID"
echo "# generated on $host on `date`"
echo "# $prog_args"
echo ""
echo "exec 2>&1"
echo "dbd=\`grep -w \"^DatabaseDirectory\" $qsysconfdir/freshclam.conf | awk '{print \$2}'\`"
echo "if [ -z \"\$dbd\" ] ; then"
echo "	echo \"DatabaseDirectory not defined in $qsysconfdir/freshclam.conf\" 1>&2"
echo "	sleep 10"
echo "	exit 1"
echo "fi"
echo "if [ ! -d \"\$dbd\" ] ; then"
echo "	/bin/mkdir \$dbd"
echo "	$chown qscand:qmail \$dbd"
echo "	/bin/chmod 775 \$dbd"
echo "fi"
echo "ans=\`grep -w \"^AllowSupplementaryGroups\" $qsysconfdir/freshclam.conf | awk '{print \$2}'\`"
echo "fgd=\`grep -w \"^Foreground\" $qsysconfdir/freshclam.conf | awk '{print \$2}'\`"
echo "if [ -z \"\$fgd\" ] ; then"
echo "	echo \"Foreground not defined in $qsysconfdir/freshclam.conf\" 1>&2"
echo "	sleep 10"
echo "	exit 1"
echo "fi"
echo ""
echo "cmp $sysconfdir/foxhole_all.cdb \$dbd/foxhole_all.cdb >/dev/null 2>&1"
echo "if [ \$? -ne 0 ] ; then"
echo "	echo \"Updating foxhole_all.cdb\""
echo "	/bin/cp $sysconfdir/foxhole_all.cdb \$dbd"
echo "	$chown qscand:qmail \$dbd/foxhole_all.cdb"
echo "fi"
echo ""
echo "if [ \" \$ans\" = \" yes\" -o \" \$ans\" = \" Yes\" ] ; then"
echo "  if [ \" \$fgd\" = \" yes\" -o \" \$fgd\" = \" Yes\" ] ; then"
echo "    exec $clamdPrefix/bin/freshclam -v --stdout --datadir=\$dbd -d -c 2 \\"
echo "      --config-file=$qsysconfdir/freshclam.conf"
echo "  else"
echo "    exec $clamdPrefix/bin/freshclam -v --stdout --datadir=\$dbd -f -d -c 2 \\"
echo "      --config-file=$qsysconfdir/freshclam.conf"
echo "  fi"
echo "else"
echo "  if [ \" \$fgd\" = \" yes\" -o \" \$fgd\" = \" Yes\" ] ; then"
echo "    exec $QmailBinPrefix/bin/setuidgid qscand \\"
echo "      $clamdPrefix/bin/freshclam -v --stdout --datadir=\$dbd -d -c 2 \\"
echo "      --config-file=$qsysconfdir/freshclam.conf"
echo "  else"
echo "    exec $QmailBinPrefix/bin/setuidgid qscand \\"
echo "      $clamdPrefix/bin/freshclam -v --stdout --datadir=\$dbd -f -d -c 2 \\"
echo "      --config-file=$qsysconfdir/freshclam.conf"
echo "  fi"
echo "fi"
) > "$DESTDIR"$SERVICEDIR/freshclam/run
/bin/chmod +x "$DESTDIR"$SERVICEDIR/freshclam/run

if [ ! -d $LOGDIR ] ; then
	/bin/mkdir -p $LOGDIR
	$chown qmaill:nofiles $LOGDIR
fi
# freshclam log script
(
echo "#!/bin/sh"
echo "$RCSID"
echo "# generated on $host on `date`"
echo "# $prog_args"
echo ""
echo "exec $QmailBinPrefix/bin/setuidgid qmaill \\"
echo "$QmailBinPrefix/sbin/multilog t $LOGDIR/freshclam"
) > "$DESTDIR"$SERVICEDIR/freshclam/log/run
/bin/chmod +x "$DESTDIR"$SERVICEDIR/freshclam/log/run
echo "$prog_args" > $conf_dir/.options

if [ $run_file_only -eq 1 ] ; then
	if [ -d "$conf_dir".bak ] ; then
		/bin/rm -rf $conf_dir
		/bin/mv "$conf_dir".bak $conf_dir
	fi
fi
# fix QHPSI variable in services which require virus scanning
for q in smtpd.465 smtpd.25 smtpd.587 qmqpd.628 qmtpd.209
do
	grep qhpsi "$DESTDIR"$SERVICEDIR/qmail-"$q"/variables/.options >/dev/null 2>&1
	if [ $? -ne 0 ] ; then
		qhpsi="$clamdPrefix/bin/clamdscan %s --fdpass --quiet --no-summary"
		cur_options=`/bin/cat "$DESTDIR"$SERVICEDIR/qmail-"$q"/variables/.options`
		if [ -n "$cur_options" ] ; then
			cur_options="$cur_options --qhpsi=\"$qhpsi\""
			echo "$cur_options" >  "$DESTDIR"$SERVICEDIR/qmail-"$q"/variables/.options
			echo $qhpsi > "$DESTDIR"$SERVICEDIR/qmail-"$q"/variables/QHPSI
		fi
	fi
done
# fix QHPSI for default queue
grep qhpsi "$DESTDIR"$sysconfdir/control/defaultqueue/.options > /dev/null 2>&1
if [ $? -ne 0 ] ; then
	qhpsi="$clamdPrefix/bin/clamdscan %s --fdpass --quiet --no-summary"
	cur_options=`/bin/cat "$DESTDIR"$sysconfdir/control/defaultqueue/.options`
	if [ -n "$cur_options" ] ; then
		cur_options="$cur_options --qhpsi=\"$qhpsi\""
		echo "$cur_options" >  "$DESTDIR"$sysconfdir/control/defaultqueue/.options
		echo $qhpsi > "$DESTDIR"$sysconfdir/control/defaultqueue/QHPSI
	fi
fi
}

create_pwdlookup()
{
if [ $# -ne 9 ] ; then
	echo "USAGE: create_pwdlookup socket_path thread_count listen_timeout supervise_dir mysql_host mysql_user mysql_pass mysql_port mysql_socket" 1>&2
	return 1
fi
SOCKET_PATH=$1
THREAD_COUNT=$2
LISTEN_TIMEOUT=$3
SERVICEDIR=$4
if [ $nooverwrite -eq 1 -a -d "$DESTDIR"$SERVICEDIR/pwdlookup/variables ] ; then
	return 0
fi
conf_dir="$DESTDIR"$SERVICEDIR/pwdlookup/variables
if [ $run_file_only -eq 1 ] ; then
	if [ -d $conf_dir ] ; then
		/bin/mv $conf_dir "$conf_dir".bak
	fi
fi
/bin/mkdir -p "$DESTDIR"$SERVICEDIR/pwdlookup/log
if [ $down_state -eq 1 ] ; then
	$TOUCH "$DESTDIR"$SERVICEDIR/pwdlookup/down
fi
/bin/mkdir -p $conf_dir
/bin/chmod 500 $conf_dir
(
echo "#!/bin/sh"
echo "$RCSID"
echo "# generated on $host on `date`"
echo "# $prog_args"
echo ""
echo "if [ -d /run ] ; then"
echo "  mkdir -p /run/indimail"
echo "  chown indimail:indimail /run/indimail"
echo "  chmod 775 /run/indimail"
echo "elif [ -d /var/run ] ; then"
echo "  mkdir -p /var/run/indimail"
echo "  chown indimail:indimail /var/run/indimail"
echo "  chmod 775 /var/run/indimail"
echo "fi"
echo "exec 2>&1"
echo ""
echo "exec $QmailBinPrefix/bin/envdir variables \\"
echo "$QmailBinPrefix/bin/setuidgid indimail $QmailBinPrefix/sbin/nssd -d notice"
) > "$DESTDIR"$SERVICEDIR/pwdlookup/run
/bin/chmod +x "$DESTDIR"$SERVICEDIR/pwdlookup/run
(
echo "30"
echo "mysql.3306"
) > "$DESTDIR"$SERVICEDIR/pwdlookup/wait

if [ ! -d $LOGDIR ] ; then
	/bin/mkdir -p $LOGDIR
	$chown qmaill:nofiles $LOGDIR
fi
# pwdlookup log script
(
echo "#!/bin/sh"
echo "$RCSID"
echo "# generated on $host on `date`"
echo "# $prog_args"
echo ""
echo "exec $QmailBinPrefix/bin/setuidgid qmaill \\"
echo "$QmailBinPrefix/sbin/multilog t $LOGDIR/pwdlookup"
) > "$DESTDIR"$SERVICEDIR/pwdlookup/log/run
/bin/chmod +x "$DESTDIR"$SERVICEDIR/pwdlookup/log/run
echo "$prog_args" > $conf_dir/.options

if [ $run_file_only -eq 1 ] ; then
	if [ -d "$conf_dir".bak ] ; then
		/bin/rm -rf $conf_dir
		/bin/mv "$conf_dir".bak $conf_dir
	fi
else
	create_pwdlookup_conf "$5" "$6" "$7" "$8" "$9" > /tmp/config.cnf.$$
	if [ $? -eq 0 ] ; then
		conf_file=$DESTDIR"$sysconfdir/nssd.conf"
		change_config $conf_file /tmp/config.cnf.$$
	fi
fi
}

create_pwdlookup_conf()
{
if [ $# -ne 5 ] ; then
	echo "USAGE: create_pwdlookup_conf mysql_user mysql_pass mysql_port mysql_socket" 1>&2
	return 1
fi
mysql_host=$1
mysql_user=$2
mysql_pass=$3
mysql_port=$4
mysql_socket=$5
SYSTEM=$(uname -s)
case "$SYSTEM" in
	Linux)
	echo "getpwnam    SELECT pw_name,'x',555,555,pw_gecos,pw_dir,pw_shell \\"
	echo "            FROM indimail \\"
	echo "            WHERE pw_name='%1\$s' and pw_domain='%2\$s' \\"
	echo "            LIMIT 1"
	echo "getspnam    SELECT pw_name,pw_passwd,'1','0','99999','0','0','-1','0' \\"
	echo "            FROM indimail \\"
	echo "            WHERE pw_name='%1\$s'and pw_domain='%2\$s' \\"
	echo "            LIMIT 1"
	echo "getpwent    SELECT pw_name,'x',555,555,pw_gecos,pw_dir,pw_shell \\"
	echo "            FROM indimail LIMIT 100"
	echo "getspent    SELECT pw_name,pw_passwd,'1','0','99999','0','0','-1','0' \\"
	echo "            FROM indimail"
	;;
	FreeBSD)
	echo "getpwnam    SELECT pw_name,pw_passwd,555,555,0,'',pw_gecos,pw_dir,pw_shell,0 \\"
	echo "            FROM indimail \\"
	echo "            WHERE pw_name='%1\$s' and pw_domain='%2\$s' \\"
	echo "            LIMIT 1"
	echo "getpwent    SELECT pw_name,pw_passwd,555,555,0,'',pw_gecos,pw_dir,pw_shell,0 \\"
	echo "            FROM indimail"
	;;
esac
echo ""
echo "host        $mysql_host"
echo "database    indimail"
echo "username    $mysql_user"
echo "password    $mysql_pass"
if [ " $mysql_socket" != " " ] ; then
	echo "socket      $mysql_socket"
else
	if [ " $mysql_port" = " " ] ; then
		echo "port       3306"
	else
		echo "port       $mysql_port"
	fi
fi
if [ -d /run ] ; then
echo "pidfile     /run/indimail/nssd.pid"
elif [ -d /var/run ] ; then
echo "pidfile     /var/run/indimail/nssd.pid"
else
echo "pidfile     /tmp/indimail/nssd.pid"
fi
echo "threads     $THREAD_COUNT"
echo "timeout     $LISTEN_TIMEOUT"
echo "facility    daemon"
echo "priority    err"
}

create_inlookup()
{
if [ $# -ne 4 ] ; then
	echo "USAGE: create_inlookup infifo thread_count activeDays supervise_dir" 1>&2
	return 1
fi
INFIFO_PATH=$1
THREAD_COUNT=$2
activeDays=$3
SERVICEDIR=$4
base_fifo_name=`basename $INFIFO_PATH`
fifo_dir=`dirname $INFIFO_PATH`
if [ $fifo_dir = "." ] ; then
	fifo_dir=$QmailHOME/inquery
fi

if [ $nooverwrite -eq 1 -a -d "$DESTDIR"$SERVICEDIR/inlookup.$base_fifo_name/variables ] ; then
	return 0
fi
conf_dir="$DESTDIR"$SERVICEDIR/inlookup.$base_fifo_name/variables
if [ $run_file_only -eq 1 ] ; then
	if [ -d $conf_dir ] ; then
		/bin/mv $conf_dir "$conf_dir".bak
	fi
fi
/bin/mkdir -p "$DESTDIR"$SERVICEDIR/inlookup.$base_fifo_name/log
if [ $down_state -eq 1 ] ; then
	$TOUCH "$DESTDIR"$SERVICEDIR/inlookup.$base_fifo_name/down
fi
/bin/mkdir -p $conf_dir
/bin/chmod 500 $conf_dir
#
# do this so that vdeluser can run libexec script vdeluser
# which can send sighup to inlookup service using the svc command
#
/bin/mkdir -p "$DESTDIR"$SERVICEDIR/inlookup.$base_fifo_name/supervise
$chown root:0 "$DESTDIR"$SERVICEDIR/inlookup.$base_fifo_name/supervise
if [ ! -f "$DESTDIR"$SERVICEDIR/inlookup.$base_fifo_name/supervise/control ] ; then
/usr/bin/mkfifo      "$DESTDIR"$SERVICEDIR/inlookup.$base_fifo_name/supervise/control > /dev/null 2>&1
fi
/bin/chmod 660       "$DESTDIR"$SERVICEDIR/inlookup.$base_fifo_name/supervise/control
$chown root:indimail "$DESTDIR"$SERVICEDIR/inlookup.$base_fifo_name/supervise/control

echo "$base_fifo_name" > $conf_dir/INFIFO
echo "$fifo_dir" > $conf_dir/FIFODIR
echo $THREAD_COUNT > $conf_dir/THREAD_COUNT
if [ " $activeDays"  = " " ] ; then
echo 0 > $conf_dir/CACHE_COUNT
else
echo "`expr $activeDays \* 86400`" > $conf_dir/CACHE_COUNT
fi
if [ ! " $CONTROLDIR" = " " ] ; then
	echo $CONTROLDIR > $conf_dir/CONTROLDIR
else
	> $conf_dir/CONTROLDIR
fi
if [ " $password_cache" = " " ] ; then
	> $conf_dir/PASSWD_CACHE
else
	echo > $conf_dir/PASSWD_CACHE
fi
if [ " $query_cache" = " " ] ; then
	> $conf_dir/QUERY_CACHE
else
	echo > $conf_dir/QUERY_CACHE
fi
if [ " $use_btree" = " " ] ; then
	> $conf_dir/USE_BTREE
else
	echo 1 > $conf_dir/USE_BTREE
fi
if [ ! " $max_btree_count" = " " ] ; then
	echo $max_btree_count > $conf_dir/MAX_BTREE_COUNT
else
	echo 0 > $conf_dir/MAX_BTREE_COUNT
fi
if [ ! " $domainlimits" = " " ] ; then
	echo  > $conf_dir/DOMAIN_LIMITS
else
	> $conf_dir/DOMAIN_LIMITS
fi
echo $sysconfdir/indimail.cnf > $conf_dir/MYSQL_READ_DEFAULT_FILE
echo "inlookup" > $conf_dir/MYSQL_READ_DEFAULT_GROUP
echo 1 > $conf_dir/MYSQL_OPT_RECONNECT
(
echo "#!/bin/sh"
echo "$RCSID"
echo "# generated on $host on `date`"
echo "# $prog_args"
echo ""
echo "exec 2>&1"
echo ""
echo "exec $QmailBinPrefix/bin/envdir variables sh -c \""
echo "exec $QmailBinPrefix/bin/setuidgid indimail $QmailBinPrefix/sbin/inlookup \\"
echo "  -i \\\$THREAD_COUNT -c \\\$CACHE_COUNT\""
) > "$DESTDIR"$SERVICEDIR/inlookup.$base_fifo_name/run
/bin/chmod +x "$DESTDIR"$SERVICEDIR/inlookup.$base_fifo_name/run
(
echo "30"
echo "mysql.3306"
) > "$DESTDIR"$SERVICEDIR/inlookup.$base_fifo_name/wait

if [ ! -d $LOGDIR ] ; then
	/bin/mkdir -p $LOGDIR
	$chown qmaill:nofiles $LOGDIR
fi
# inlookup log script
(
echo "#!/bin/sh"
echo "$RCSID"
echo "# generated on $host on `date`"
echo "# $prog_args"
echo ""
echo "exec $QmailBinPrefix/bin/setuidgid qmaill \\"
echo "$QmailBinPrefix/sbin/multilog t $LOGDIR/inlookup.$base_fifo_name"
) > "$DESTDIR"$SERVICEDIR/inlookup.$base_fifo_name/log/run
/bin/chmod +x "$DESTDIR"$SERVICEDIR/inlookup.$base_fifo_name/log/run
echo "$prog_args" > $conf_dir/.options

if [ $run_file_only -eq 1 ] ; then
	if [ -d "$conf_dir".bak ] ; then
		/bin/rm -rf $conf_dir
		/bin/mv "$conf_dir".bak $conf_dir
	fi
fi
}

mariadb_ssl_rsa_setup()
{
if [ $# -ne 2 ] ; then
	echo "USAGE: mariadb_ssl_rsa_setup capath certdir" 1>&2
	return 1
fi
if [ ! -x /usr/bin/openssl ] ; then
	echo "/usr/bin/openssl: No such file or directory" 1>&2
	return 1
fi
ca_path=$1
certdir=$2
if [ -z "$ca_path" ] ; then
	ca_path="."
fi
if [ ! -d "$DESTDIR"$certdir ] ; then
	/bin/mkdir -p "$DESTDIR"$certdir
	if [ $? -ne 0 ] ; then
		return 1
	fi
else
	if [ -f "$DESTDIR"$certdir/client-cert.pem -o -f "$DESTDIR"$certdir/server-cert.pem ] ; then
		if [ $force -ne 1 ] ; then
			echo "SSL Certs exists. Remove client, server certs in "$DESTDIR"$certdir to proceed" 1>&2
			return 1
		fi
	fi
fi

if [ ! -f $ca_path/ca.pem -o ! -f $ca_path/ca-key.pem ] ; then
	# create CA certificate with x509 v3 extension
	if [ ! -d $ca_path ] ; then
		mkdir -p $ca_path
		if [ $? -ne 0 ] ; then
			echo "Failed to create $ca_path" 1>&2
			return 1
		fi
	fi
	cd $ca_path
	if [ $? -ne 0 ] ; then
		echo "unable to cd to $ca_path" 1>&2
		return 1
	fi
	echo "basicConstraints=CA:TRUE"  > cav3.ext
	# Create CA
	/usr/bin/openssl req -newkey rsa:2048 -days 3650 -nodes -keyout $ca_path/ca-key.pem \
		-subj /CN=MariaDB_Auto_Generated_CA_Certificate -out $ca_path/ca-req.pem
	if [ $? -ne 0 ] ; then
		echo "failed to create ca-req.pem" 1>&2
		/bin/rm -f $ca_path/cav3.ext
		return 1
	fi
	/usr/bin/openssl rsa -in $ca_path/ca-key.pem -out $ca_path/ca-key.pem 
	if [ $? -ne 0 ] ; then
		echo "failed to create ca-key.pem" 1>&2
		/bin/rm -f $ca_path/cav3.ext
		return 1
	fi
	/usr/bin/openssl x509 -sha256 -days 3650 -extfile $ca_path/cav3.ext -set_serial 1 \
		-req -in $ca_path/ca-req.pem -signkey $ca_path/ca-key.pem -out $ca_path/ca.pem
	if [ $? -ne 0 ] ; then
		echo "failed to create ca.pem" 1>&2
		/bin/rm -f $ca_path/cav3.ext
		return 1
	fi
	/bin/rm -f $ca_path/cav3.ext
fi

cd "$DESTDIR"$certdir
if [ $? -ne 0 ] ; then
	echo "unable to cd to "$DESTDIR"$certdir" 1>&2
	return 1
fi

# create certificats with x509 v3 extension
echo "basicConstraints=CA:FALSE" > certv3.ext
# Create Server Cert
/usr/bin/openssl req -newkey rsa:2048 -days 3650 -nodes -keyout server-key.pem \
	-subj /CN=MariaDB_Auto_Generated_Server_Certificate -out server-req.pem
if [ $? -ne 0 ] ; then
	echo "failed to create server-req.pem" 1>&2
	/bin/rm -f certv3.ext
	return 1
fi
/usr/bin/openssl rsa -in server-key.pem -out server-key.pem
if [ $? -ne 0 ] ; then
	echo "failed to create server-key.pem" 1>&2
	/bin/rm -f certv3.ext
	return 1
fi
/usr/bin/openssl x509 -sha256 -days 3650 -extfile certv3.ext -set_serial 2 -req \
	-in server-req.pem -CA $ca_path/ca.pem -CAkey $ca_path/ca-key.pem -out server-cert.pem
if [ $? -ne 0 ] ; then
	echo "failed to create server-cert.pem" 1>&2
	/bin/rm -f certv3.ext
	return 1
fi

# Create Client Cert
/usr/bin/openssl req -newkey rsa:2048 -days 3650 -nodes -keyout client-key.pem \
	-subj /CN=MariaDB_Auto_Generated_Client_Certificate -out client-req.pem
if [ $? -ne 0 ] ; then
	echo "failed to create client-req.pem" 1>&2
	/bin/rm -f certv3.ext
	return 1
fi
/usr/bin/openssl rsa -in client-key.pem -out client-key.pem
if [ $? -ne 0 ] ; then
	echo "failed to create client-key.pem" 1>&2
	/bin/rm -f certv3.ext
	return 1
fi
/usr/bin/openssl x509 -sha256 -days 3650 -extfile certv3.ext -set_serial 3 -req \
	-in client-req.pem -CA $ca_path/ca.pem -CAkey $ca_path/ca-key.pem -out client-cert.pem
if [ $? -ne 0 ] ; then
	echo "failed to create client-cert.pem" 1>&2
	/bin/rm -f certv3.ext
	return 1
fi
/bin/rm -f certv3.ext

# Verifiy the certificates
/usr/bin/openssl verify -CAfile $ca_path/ca.pem server-cert.pem client-cert.pem

# Generate public & private key
/usr/bin/openssl genrsa  -out private_key.pem 2048
/usr/bin/openssl rsa -in private_key.pem -pubout -out public_key.pem
$chown mysql:mysql $ca_path/ca-key.pem $ca_path/ca.pem server-key.pem server-cert.pem \
	client-key.pem client-cert.pem private_key.pem public_key.pem
/bin/chmod 600 $ca_path/ca-key.pem server-key.pem client-key.pem private_key.pem
/bin/chmod 644 $ca_path/ca.pem server-cert.pem client-cert.pem public_key.pem
/bin/rm -f ca-req.pem server-req.pem client-req.pem
echo ""
echo "Verifying server and client certs with ca.pem"
/usr/bin/openssl verify -CAfile $ca_path/ca.pem server-cert.pem client-cert.pem
echo ""
echo "ca.pem purpose"
/usr/bin/openssl x509 -in $ca_path/ca.pem -noout -purpose
echo ""
echo "client-cert.pem purpose"
/usr/bin/openssl x509 -in client-cert.pem -noout -purpose
echo ""
echo "server-cert.pem purpose"
/usr/bin/openssl x509 -in server-cert.pem -noout -purpose
return 0
}

mecho()
{
	echo "$*"
	echo " $*" 1>&2
}

wait_for_mysqld()
{
	die=$1
	count=0
	if [ " $die" = " 1" ] ; then
		/bin/echo -n "Waiting for MySQL Server to stop ."
	else
		/bin/echo -n "Waiting for MySQL Server to start ."
	fi
	while true
	do
		if [ $count -eq 5 ] ; then
			echo "giving up"
			break
		fi
		if [ " $die" = " 1" ] ; then
			if [ ! -f "$DESTDIR"$databasedir/mysqld.pid ] ; then
				echo
				sleep 5
				break
			fi
		else
			if [ -s "$DESTDIR"$databasedir/mysqld.pid ] ; then
				echo
				sleep 5
				break
			fi
		fi
		/bin/echo -n "."
		count=`expr $count + 1`
		sleep 5
	done
}

create_mysql_db()
{
if [ $# -ne 2 ] ; then
	echo "USAGE: create_mysql_db databasedir mysql_socket" 1>&2
	return 1
fi
databasedir=$1
mysql_socket=$2
if [ -x $mysqlPrefix/libexec/mysqld ] ; then
	mysqld=libexec/mysqld
elif [ -x $mysqlPrefix/sbin/mysqld ] ; then
	mysqld=sbin/mysqld
elif [ -x $mysqlPrefix/bin/mysqld ] ; then
	mysqld=bin/mysqld
else
	echo "mysqld: No such File or directory" 1>&2
	return 1
fi
mysql_version=`$mysqlPrefix/$mysqld --version |awk '{print $3}' 2>&1`
echo $mysql_version |grep MariaDB > /dev/null 2>&1
if [ $? -eq 0 ] ; then
	mysql_version=`echo $mysql_version|cut -d- -f1`
	mariadb=1
else
	$mysqlPrefix/$mysqld --version | egrep "MySQL Community Server|FreeBSD" > /dev/null 2>&1
	if [ $? -eq 0 ] ; then
		mysql_community_server=1
	else
		mysql_community_server=0
	fi
	mariadb=0
fi
mysql_version_8=0
mariadb_version_10=0
case "$mysql_version" in
	8.*)
	# the monkeys at Oracle have again succeeded in introducing incompatibility with previous
	# database initialization methods
	mysql_version_8=1
	;;

	10.*)
	if [ $mariadb -eq 1 ] ; then
		mariadb_version_10=1
	fi
	;;

	*)
	mysql_version_8=0
	;;
esac
if [ -x $mysqlPrefix/bin/mysql_install_db ] ; then
	install_db=$mysqlPrefix/bin/mysql_install_db
elif [ -x $mysqlPrefix/scripts/mysql_install_db ] ; then
	install_db=$mysqlPrefix/scripts/mysql_install_db
else
	install_db=""
fi

if [ ! -d "$DESTDIR"$databasedir/data -o "$force" -eq 1 ] ; then
	if [ $force -eq 1 ] ; then
		/bin/rm -rf "$DESTDIR"$databasedir/data
	fi
	if [ -d /run ] ; then
		rundir=/run
	elif [ -d /var/run ] ; then
		rundir=/var/run
	fi
	if [ ! -d $rundir/mysqld ] ; then
		/bin/mkdir -p $rundir/mysqld
		$chown mysql:mysql $rundir/mysqld
	fi
	if ( /bin/mkdir -p "$DESTDIR"$databasedir/data && /bin/mkdir -p "$DESTDIR"$databasedir/logs ) ; then
		(
		echo "$RCSID"
		echo "# generated on $host on `date`"
		echo ""
		echo "$prog_args"
		) > "$DESTDIR"$databasedir/README
		$chown -R mysql:mysql "$DESTDIR"$databasedir
		echo "Creating MySQL Database in "$DESTDIR"$databasedir/data" 1>&2
		if [ $mariadb -eq 1 ] ; then
			echo "$install_db --user=mysql --basedir=$mysqlPrefix --datadir="$DESTDIR"$databasedir/data" 1>&2
			$install_db --user=mysql --basedir=$mysqlPrefix --datadir="$DESTDIR"$databasedir/data
		else
			if [ $mysql_version_8 -eq 1 ] ; then
				opt_str="--user=root"
			else
				opt_str="--user=mysql"
			fi
			/bin/echo -n "$mysqlPrefix/$mysqld --no-defaults --initialize-insecure $opt_str" 1>&2
			/bin/echo -n " --skip-networking" 1>&2
			/bin/echo -n " --log-error="$DESTDIR"$databasedir/logs/mysqld.log"  1>&2
			/bin/echo    " --datadir="$DESTDIR"$databasedir/data --socket=$mysql_socket" 1>&2
			$mysqlPrefix/$mysqld --no-defaults --initialize-insecure $opt_str \
				--skip-networking \
				--log-error="$DESTDIR"$databasedir/logs/mysqld.log \
				--datadir="$DESTDIR"$databasedir/data --socket=$mysql_socket
			if [ $? -ne 0 ] ; then
				if [ -z $install_db ] ; then
					echo "couldn't locate db installation program" 1>&2
					return 1
				else
					echo "WARNING!!! mysqld --initialize-insecure failed. Running $install_db" 1>&2
					echo "$install_db $opt_str --basedir=$mysqlPrefix --datadir="$DESTDIR"$databasedir/data" 1>&2
					$install_db $opt_str --basedir=$mysqlPrefix --datadir="$DESTDIR"$databasedir/data
				fi
			fi
		fi
		if [ -x $mysqlPrefix/bin/mysql_ssl_rsa_setup ] ; then
			if [ ! -f "$DESTDIR"$databasedir/data/ca.pem ] ; then
				echo "Creating MySQL SSL Certs" 1>&2
				echo "$mysqlPrefix/bin/mysql_ssl_rsa_setup --uid=mysql --datadir="$DESTDIR"$databasedir/data" 1>&2
				$mysqlPrefix/bin/mysql_ssl_rsa_setup --uid=mysql --datadir="$DESTDIR"$databasedir/data
			fi
		elif [ $mariadb -eq 1 ] ; then
			echo "Creating MariaDB SSL/TLS Certificates" 1>&2
			mariadb_ssl_rsa_setup "$DESTDIR"$databasedir/ssl "$DESTDIR"$databasedir/ssl
		fi
		$chown -R mysql:mysql "$DESTDIR"$databasedir
		#
		# Pretty Dumb stuff in packing MySQL on openSUSE, creating /usr/my.cnf.
		#
		if [ -f /usr/my.cnf ] ; then
			/bin/rm /usr/my.cnf
		fi
		if [ $mysql_version_8 -eq 1 ] ; then
			pass_str=0
			auth_str=0
			plugin_str=0
		elif [ -f "$DESTDIR"$databasedir/data/mysql/user.frm ] ; then
			# Create user mysql with all privileges
			/usr/bin/strings "$DESTDIR"$databasedir/data/mysql/user.frm | grep "^Password" > /dev/null 2>&1
			if [ $? -eq 0 ] ; then
				pass_str=1
			else
				pass_str=0
			fi
			/usr/bin/strings "$DESTDIR"$databasedir/data/mysql/user.frm | grep "^authentication_string" > /dev/null 2>&1
			if [ $? -eq 0 ] ; then
				auth_str=1
			else
				auth_str=0
			fi
			if [ $mariadb -eq 1 ] ; then
				/usr/bin/strings "$DESTDIR"$databasedir/data/mysql/user.frm | grep "^plugin" > /dev/null 2>&1
				if [ $? -eq 0 ] ; then
					plugin_str=1
				else
					plugin_str=0
				fi
			else # from another monkey at oracle
					plugin_str=2
			fi
		else # hope for the best
			echo "Unable to create MySQL db in "$DESTDIR"$databasedir/data" 1>&2
			return 1
		fi
		if [ $mysql_version_8 -eq 1 ] ; then
			opt_str="--user=root"
		else
			opt_str="--user=mysql"
		fi
		#
		# Start MySQL daemon
		#
		/bin/echo -n "$mysqlPrefix/$mysqld --no-defaults --pid-file="$DESTDIR"$databasedir/mysqld.pid" 1>&2
		/bin/echo -n " --skip-networking --datadir="$DESTDIR"$databasedir/data" 1>&2
		/bin/echo -n " --log-error="$DESTDIR"$databasedir/logs/mysqld.log" 1>&2
		/bin/echo    " $opt_str --socket=$mysql_socket" 1>&2
		$mysqlPrefix/$mysqld --no-defaults --pid-file="$DESTDIR"$databasedir/mysqld.pid \
			--skip-networking --datadir="$DESTDIR"$databasedir/data \
			--log-error="$DESTDIR"$databasedir/logs/mysqld.log \
			$opt_str --socket=$mysql_socket &
		wait_for_mysqld
		if [ -s "$DESTDIR"$databasedir/mysqld.pid ] ; then
			pid=`/bin/cat "$DESTDIR"$databasedir/mysqld.pid`
			(
			# Create user mysql with all privileges
			echo "Creating MySQL admin User for Database in "$DESTDIR"$databasedir/data" 1>&2
			create_mysql_rootuser $mysql_version $mariadb $mysql_community_server $pass_str $auth_str $plugin_str
			echo "Creating MySQL indimail User for Database in "$DESTDIR"$databasedir/data" 1>&2
			create_mysql_user $mysql_version
			) | eval $mysqlPrefix/bin/mysql -u root --skip-password -S $mysql_socket
			kill $pid
			wait_for_mysqld 1
			$chown -R mysql:mysql "$DESTDIR"$databasedir
		else
			echo "did not find running mysqld: "$DESTDIR"$databasedir/mysqld.pid not found" 1>&2
			return 1
		fi
	else
		echo "Unable to create "$DESTDIR"$databasedir/data or "$DESTDIR"$databasedir/logs" 1>&2
		return 1
	fi
	return 0
fi
}

check_mysqld_variable()
{
if [ $# -ne 2 ] ; then
	echo "USAGE: check_mysqld_variable variable_name print" 1>&2
	return 1
fi
if [ -x $mysqlPrefix/libexec/mysqld ] ; then
	mysqld=libexec/mysqld
elif [ -x $mysqlPrefix/sbin/mysqld ] ; then
	mysqld=sbin/mysqld
elif [ -x $mysqlPrefix/bin/mysqld ] ; then
	mysqld=bin/mysqld
else
	echo "mysqld: No such File or directory" 1>&2
	return 1
fi
name=`echo $1 | cut -d= -f1`
should_print=$2
$mysqlPrefix/$mysqld --no-defaults --verbose --help 2>/dev/null |grep -w -- "$name" >/dev/null 2>&1
if [ $? -eq 0 ] ; then
	if [ $should_print -ne 0 ] ; then
		echo "$1 \\"
	fi
	return 0
else
	return 1
fi
}

check_mysqld_ini_variable()
{
if [ $# -ne 2 ] ; then
	echo "USAGE: check_mysqld_ini_variable variable_name print" 1>&2
	return 1
fi
if [ -x $mysqlPrefix/libexec/mysqld ] ; then
	mysqld=libexec/mysqld
elif [ -x $mysqlPrefix/sbin/mysqld ] ; then
	mysqld=sbin/mysqld
elif [ -x $mysqlPrefix/bin/mysqld ] ; then
	mysqld=bin/mysqld
else
	echo "mysqld: No such File or directory" 1>&2
	return 1
fi
name=`echo $1 | cut -d= -f1`
should_print=$2
$mysqlPrefix/$mysqld --no-defaults --verbose --help 2>/dev/null |grep -w "^$name" > /dev/null 2>&1
if [ $? -eq 0 ] ; then
	if [ $should_print -ne 0 ] ; then
		echo "$1"
	fi
	return 0
else
	echo $name | grep "_" > /dev/null 2>&1
	if [ $? -ne 0 ] ; then
		return 1
	fi
	# we found underscore in the variable name
	# mysqld variables have hyphen '-' to its equivalent ini variable.
	# replace '_' with '-' and perform check
	# replace underscores only in the variable name and not in the
	# variable value
	orig=`echo $name` # remove trailing space in $name, if present
	name=`echo $name|sed s{_{-{g`
	$mysqlPrefix/$mysqld --no-defaults --verbose --help 2>/dev/null |grep -w "^$name" > /dev/null 2>&1
	if [ $? -eq 0 ] ; then
		if [ $should_print -eq 1 ] ; then
			echo "$1" | sed s{"$orig"{"$name"{g
		elif [ $should_print -eq 2 ] ; then
			/bin/echo -n "# "
			echo "$1" | sed s{"$orig"{"$name"{g
		fi
		return 0
	fi
	return 1
fi
}

create_mysql_rootuser()
{
	mysql_version=$1
	mariadb=$2
	mysql_community_server=$3
	pass_str=$4
	auth_str=$5
	plugin_str=$6
	mysql_version_8=0
	mariadb_version_10=0
	case "$mysql_version" in
		8.*)
		mysql_version_8=1
		;;
		10.*)
		if [ $mariadb -eq 1 ] ; then
			mariadb_version_10=1
		fi
		;;
	esac
	if [ $mariadb -eq 1 ] ; then
		ver2=`echo $mysql_version | cut -d. -f2`
		if [ -n "$ver2" -a $ver2 -ge 2 ] ; then
			mecho "ALTER USER 'root'@'localhost' identified by '$PRIV_PASS';"
		else
			mecho "set PASSWORD for 'root'@'localhost' = PASSWORD('$PRIV_PASS');"
		fi
	else
		if [ $mysql_version_8 -eq 1 ] ; then
			mecho "ALTER USER 'root'@'localhost' identified by '$PRIV_PASS';"
		else
			mecho "set PASSWORD for 'root'@'localhost' = PASSWORD('$PRIV_PASS');"
		fi
	fi
	mecho "use mysql;"
	if [ $mysql_community_server -eq 1 ] ; then
		mecho "DELETE from user where user='';"
	else
		mecho "DELETE from user where user='' or password='';"
	fi
	mecho "DROP database if exists test;"
	mecho "DELETE from db where db like 'test%';"
}

create_mysql_user()
{
	if [ ! -x /usr/bin/openssl ] ; then
		echo "/usr/bin/openssl: No such file or directory" 1>&2
		return 1
	fi
	mysql_version=$1
	case "$mysql_version" in
		8.*)
			mysql_version_8=1
			;;
		7.*)
			mysql_version_8=0
			;;
	esac

	# Bootstrap Indimail tables
	mecho "CREATE database indimail;"
	mecho "use indimail;"
	c_d=""
	c_d="$c_d CREATE TABLE mgmtaccess ("
	c_d="$c_d user  char(32) not null,"
	c_d="$c_d pass char(128) not null,"
	c_d="$c_d pw_uid int not null,"
	c_d="$c_d pw_gid int not null,"
	c_d="$c_d lastaccess int not null,"
	c_d="$c_d lastupdate int not null,"
	c_d="$c_d day char(2) not null,"
	c_d="$c_d attempts int not null,"
	c_d="$c_d status char(2) not null,"
	c_d="$c_d zztimestamp TIMESTAMP not null,"
	c_d="$c_d unique index(user));"
	mecho $c_d
	case "$host" in
		*-*-darwin*)
		TMP=$(head -c 8192 /dev/urandom | env LC_ALL=C tr -dc 'a-zA-Z0-9./' | head -c 8)
		CRYPT_PASS=$(openssl passwd -1 -salt $TMP $ADMIN_PASS)
		;;
		*)
		TMP=$(head -c 8192 /dev/urandom | env LC_TYPE=C tr -dc 'a-zA-Z0-9./' | head -c 16)
		CRYPT_PASS=$(openssl passwd -6 -salt $TMP $ADMIN_PASS)
		;;
	esac
	TMVAL=`date +'%s'`
	DAY=`date +'%d'`
	TIMESTAMP=`date +'%F %R:%S'`
	mecho "INSERT INTO mgmtaccess (user,pass,pw_uid,pw_gid,lastaccess,lastupdate,day,attempts,status,zztimestamp) VALUES ('admin','$CRYPT_PASS',0,0,$TMVAL,$TMVAL,$DAY,0,0,'$TIMESTAMP');"
	c_d=""
	c_d="$c_d CREATE TABLE indimail ("
	c_d="$c_d pw_name char(40) not null,"
	c_d="$c_d pw_domain char(67) not null,"
	c_d="$c_d pw_passwd char(128) not null,"
	c_d="$c_d pw_uid int,"
	c_d="$c_d pw_gid int,"
	c_d="$c_d pw_gecos char(48) not null,"
	c_d="$c_d pw_dir char(156),"
	c_d="$c_d pw_shell char(30),"
	c_d="$c_d primary key (pw_name, pw_domain), index pw_gecos (pw_gecos(25)), index pw_uid (pw_uid));"
	mecho $c_d
	c_d=""
	c_d="$c_d CREATE TABLE indibak ("
	c_d="$c_d pw_name char(40) not null,"
	c_d="$c_d pw_domain char(67) not null,"
	c_d="$c_d pw_passwd char(128) not null,"
	c_d="$c_d pw_uid int,"
	c_d="$c_d pw_gid int,"
	c_d="$c_d pw_gecos char(48) not null,"
	c_d="$c_d pw_dir char(156),"
	c_d="$c_d pw_shell char(30),"
	c_d="$c_d primary key (pw_name, pw_domain), index pw_gecos (pw_gecos(25)), index pw_uid (pw_uid));"
	mecho $c_d
	c_d=""
	c_d="$c_d CREATE TABLE vfilter ("
	c_d="$c_d emailid char(107) not null,"
	c_d="$c_d filter_no smallint not null,"
	c_d="$c_d filter_name char(32) not null,"
	c_d="$c_d header_name smallint not null,"
	c_d="$c_d comparision tinyint not null,"
	c_d="$c_d keyword char(64) not null,"
	c_d="$c_d destination char(156) not null,"
	c_d="$c_d bounce_action char(64) not null,"
	c_d="$c_d mailing_list tinyint not null,"
	c_d="$c_d primary key(emailid, filter_no), unique index (emailid, header_name, comparision, keyword, destination));"
	mecho $c_d

	mecho "use mysql;"
	mecho "CREATE USER 'indimail'@'%' identified by '$MYSQL_PASS';"
	mecho "CREATE USER 'admin'@'%'    identified by '$ADMIN_PASS';"
	mecho "CREATE USER 'repl'@'%'     identified by 'slaveserver';"
	if [ $mariadb -eq 1 -a $mariadb_version_10 -eq 1 ] ; then
		ver2=`echo $mysql_version | cut -d. -f2`
		if [ -n "$ver2" -a $ver2 -gt 0 ] ; then
			mecho "DROP USER if exists mysql@localhost;"
		fi
	fi
	mecho "CREATE USER 'mysql'@'%' identified by '$PRIV_PASS';"
	mecho "GRANT ALL on *.* to mysql;"
	if [ $mysql_version_8 -eq 1 -o $mariadb_version_10 -eq 1 ] ; then
		mecho "GRANT USAGE ON *.* TO mysql WITH GRANT OPTION;"
	fi
	mecho "GRANT SELECT,CREATE,ALTER,INDEX,INSERT,UPDATE,DELETE,CREATE TEMPORARY TABLES,LOCK TABLES ON indimail.* to indimail;"
	mecho "GRANT RELOAD,SHUTDOWN,PROCESS,SUPER on *.* to admin;"
	mecho "GRANT REPLICATION SLAVE on *.* to repl;"
	if [ $mysql_version_8 -eq 1 ] ; then
		c_d=""
		c_d="$c_d UPDATE global_grants set user='mysql' where user='root';"
		mecho $c_d
	fi
	mecho "FLUSH PRIVILEGES;"
}

create_mysql_service()
{
if [ $# -ne 5 ] ; then
	echo "USAGE: create_mysql_service port mysqlPrefix databasedir config_file servicedir" 1>&2
	return 1
fi
port=$1
mysqlPrefix=$2
databasedir=$3
conf_file=$4
SERVICEDIR=$5
if [ $nooverwrite -eq 1 -a -d "$DESTDIR"$SERVICEDIR/mysql.$port/variables ] ; then
	return 0
fi
if [ -x $mysqlPrefix/libexec/mysqld ] ; then
	mysqld=libexec/mysqld
elif [ -x $mysqlPrefix/sbin/mysqld ] ; then
	mysqld=sbin/mysqld
elif [ -x $mysqlPrefix/bin/mysqld ] ; then
	mysqld=bin/mysqld
else
	echo "mysqld: No such File or directory" 1>&2
	return 1
fi
mysql_version=`$mysqlPrefix/$mysqld --version 2>&1 | grep Ver | awk '{print $3}'`
case "$mysql_version" in
	8.*)
		mysql_version_8=1
		;;
	7.*)
		mysql_version_8=0
		;;
esac
echo $mysql_version |grep MariaDB > /dev/null 2>&1
if [ $? -eq 0 ] ; then
	mysql_version=`echo $mysql_version|cut -d- -f1`
	mariadb=1
else
	mariadb=0
fi
if [ ! -f "$DESTDIR"$conf_file ] ; then
	echo ""$DESTDIR"$conf_file: No such File or directory" 1>&2
	return 1
fi
conf_dir="$DESTDIR"$SERVICEDIR/mysql.$port/variables
if [ $run_file_only -eq 1 ] ; then
	if [ -d $conf_dir ] ; then
		/bin/mv $conf_dir "$conf_dir".bak
	fi
fi
/bin/mkdir -p "$DESTDIR"$SERVICEDIR/mysql.$port/log
if [ $down_state -eq 1 ] ; then
	$TOUCH "$DESTDIR"$SERVICEDIR/$mysql.$port/down
fi
/bin/mkdir -p $conf_dir
/bin/chmod 500 $conf_dir
if [ " $mysql_socket" = " " ]; then
	if [ -d /run/mysqld ] ; then
		mysql_socket=/run/mysqld/mysqld.sock
	elif [ -d /var/run/mysqld ] ; then
		mysql_socket=/var/run/mysqld/mysqld.sock
	elif [ -d /var/lib/mysql ] ; then
		mysql_socket=/var/lib/mysql/mysql.sock
	else
		mysql_socket=$mysqlSocket
	fi
fi
(
echo "#!/bin/sh"
echo "$RCSID"
echo "# generated on $host on `date`"
echo "# $prog_args"
echo ""
echo "exec 2>&1"
echo "socket_dir=\`dirname \$(grep socket $sysconfdir/indimail.cnf 2>/dev/null| head -1 | cut -d= -f2) 2>/dev/null\`"
echo "if [ -z \"\$socket_dir\" ] ; then"
echo "    socket_dir=`dirname $mysql_socket`"
echo "fi"
echo "if [ ! -d \$socket_dir ] ; then"
echo "    /bin/mkdir \$socket_dir"
echo "    $chown mysql:mysql \$socket_dir"
echo "fi"
echo "MYSQL_BASE=$mysqlPrefix"
echo "DATABASE=$databasedir"
echo "PIDFILE=\$socket_dir/mysqld."$port".pid"
echo ""
echo "# update $sysconfdir/control/mysql_lib with the latest MySQL shared lib"
echo "$QmailBinPrefix/sbin/svctool --fixsharedlibs"
echo ""
echo "exec $QmailBinPrefix/bin/softlimit -o 1024 -p 1024 \\"
echo "$QmailBinPrefix/bin/setuidgid mysql \$MYSQL_BASE/$mysqld --defaults-file=$conf_file \\"
echo "--port=$port --basedir=\$MYSQL_BASE \\"
echo "--datadir=\$DATABASE/data \\"
check_mysqld_variable --memlock 1
check_mysqld_variable --ssl 1
check_mysqld_variable --require-secure-transport 1
# skip external locking is not shown in the list of variables
echo "--skip-external-locking \\"
check_mysqld_variable --delay-key-write=all 1
check_mysqld_variable --skip-name-resolve 1
echo "--sql-mode=\"NO_ENGINE_SUBSTITUTION,NO_ZERO_IN_DATE,ERROR_FOR_DIVISION_BY_ZERO,STRICT_TRANS_TABLES\" \\"
check_mysqld_variable --explicit-defaults-for-timestamp=TRUE 1
if [ $? -ne 0 ] ; then
	check_mysqld_variable --explicit-defaults-for-timestamp 1
fi
check_mysqld_variable --general-log=1 1
check_mysqld_variable --general-log-file=\$DATABASE/logs/general-log 1
check_mysqld_variable --slow-query-log=1 1
check_mysqld_variable --slow-query-log-file=\$DATABASE/logs/slowquery-log 1
check_mysqld_variable --log-queries-not-using-indexes 1
check_mysqld_variable --log-error-verbosity=3 1
# On Unix systems, if the --log-error option is not used,
# the errors are written to stderr (usually, the command line).
#echo "--log-error=\$DATABASE/logs/mysqld.log \\"
if [ $mariadb -eq 1 ] ; then
check_mysqld_variable --log-warnings=2 1
fi
echo "--pid-file=\$PIDFILE 2>&1"
) > "$DESTDIR"$SERVICEDIR/mysql.$port/run
/bin/chmod +x "$DESTDIR"$SERVICEDIR/mysql.$port/run

(
echo "#!/bin/sh"
echo "$RCSID"
echo "# generated on $host on `date`"
echo "# $prog_args"
echo ""
echo "MYSQL_BASE=$mysqlPrefix"
echo ""
echo "exec 2>&1"
echo "exec \$MYSQL_BASE/bin/mysqladmin --defaults-file=$conf_file \\"
echo "  -u admin -p$ADMIN_PASS shutdown"
) > "$DESTDIR"$SERVICEDIR/mysql.$port/shutdown
/bin/chmod 500 "$DESTDIR"$SERVICEDIR/mysql.$port/shutdown

if [ ! -d $LOGDIR ] ; then
	/bin/mkdir -p $LOGDIR
	$chown qmaill:nofiles $LOGDIR
fi
# mysql log script
(
echo "#!/bin/sh"
echo "$RCSID"
echo "# generated on $host on `date`"
echo "# $prog_args"
echo ""
echo "exec $QmailBinPrefix/bin/setuidgid qmaill \\"
echo "$QmailBinPrefix/sbin/multilog t $LOGDIR/mysql.$port"
) > "$DESTDIR"$SERVICEDIR/mysql.$port/log/run
/bin/chmod +x "$DESTDIR"$SERVICEDIR/mysql.$port/log/run
echo "$prog_args" > $conf_dir/.options

if [ $run_file_only -eq 1 ] ; then
	if [ -d "$conf_dir".bak ] ; then
		/bin/rm -rf $conf_dir
		/bin/mv "$conf_dir".bak $conf_dir
	fi
fi
}

create_mysql_config()
{
if [ -x $mysqlPrefix/libexec/mysqld ] ; then
	mysqld=libexec/mysqld
elif [ -x $mysqlPrefix/sbin/mysqld ] ; then
	mysqld=sbin/mysqld
elif [ -x $mysqlPrefix/bin/mysqld ] ; then
	mysqld=bin/mysqld
else
	echo "mysqld: No such File or directory" 1>&2
	return 1
fi

mysql_version=`$mysqlPrefix/$mysqld --version 2>&1 | grep Ver | awk '{print $3}'`
echo $mysql_version |grep MariaDB > /dev/null 2>&1
if [ $? -eq 0 ] ; then
	mysql_version=`echo $mysql_version|cut -d- -f1`
	mariadb=1
else
	mariadb=0
fi
$mysqlPrefix/bin/mysql --version 2>/dev/null | grep MariaDB >/dev/null 2>&1
if [ $? -eq 0 ] ; then
	mariadb_client=1
else
	mariadb_client=0
fi

if [ -d "$DESTDIR"$databasedir ] ; then
	if [ -x $mysqlPrefix/bin/mysql_ssl_rsa_setup ] ; then
		echo "Creating MySQL SSL Certs" 1>&2
		echo "$mysqlPrefix/bin/mysql_ssl_rsa_setup --uid=mysql --datadir="$DESTDIR"$databasedir/data" 1>&2
		$mysqlPrefix/bin/mysql_ssl_rsa_setup --uid=mysql --datadir="$DESTDIR"$databasedir/data 1>&2
	elif [ $mariadb -eq 1 ] ; then
		echo "Creating MariaDB SSL/TLS Certificates" 1>&2
		mariadb_ssl_rsa_setup "$DESTDIR"$databasedir/ssl "$DESTDIR"$databasedir/ssl 1>&2
	fi
fi

echo "[client]"
echo "port      = $mysql_port"
echo "socket    = $mysql_socket"
check_mysqld_ini_variable "default_character_set=utf8mb4" 1
if [ $mariadb_client -eq 1 -a -d "$DESTDIR"$databasedir/ssl ] ; then
	echo ""
	echo "# MySQL Client SSL configuration"
	echo "ssl-ca=$databasedir/ssl/ca.pem"
	echo "ssl-cert=$databasedir/ssl/client-cert.pem"
	echo "ssl-key=$databasedir/ssl/client-key.pem"
	echo "# This option is disabled by default"
	echo "#ssl-verify-server-cert"
	echo ""
fi
echo ""
echo "[mysqld]"
echo "#"
echo "# * Basic Settings"
echo "#"
echo
echo "#"
echo "# * IMPORTANT"
echo "#   If you make changes to these settings and your system uses apparmor, you may"
echo "#   also need to also adjust /etc/apparmor.d/usr.sbin.mysqld."
echo "#"
echo
echo "#default-authentication-plugin=mysql_native_password"
echo "#sql_mode=\"NO_ENGINE_SUBSTITUTION,NO_ZERO_DATE,NO_ZERO_IN_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,STRICT_ALL_TABLES\""
echo "sql_mode=\"NO_ENGINE_SUBSTITUTION,STRICT_ALL_TABLES\""
if [ $mariadb -eq 1 -a -d "$DESTDIR"$databasedir/ssl ] ; then
	check_mysqld_variable --ssl 0
	if [ $? -eq 0 ] ; then
		echo ""
		echo "# MySQL Server SSL configuration"
		echo "# Securing the Database with ssl option and certificates"
		echo "# There is no control over the protocol level used."
		echo "# mariadb will use TLSv1.0 or better."
		echo "ssl"
		echo "ssl-ca=$databasedir/ssl/ca.pem"
		echo "ssl-cert=$databasedir/ssl/server-cert.pem"
		echo "ssl-key=$databasedir/ssl/server-key.pem"
		echo ""
	fi
else
	check_mysqld_ini_variable "ssl" 1
fi
check_mysqld_ini_variable "require_secure_transport = ON" 1
check_mysqld_ini_variable "explicit_defaults_for_timestamp=TRUE" 1
echo "user     = mysql"
echo "socket   = $mysql_socket"
echo "port     = $mysql_port"
echo "basedir  = $mysqlPrefix"
echo "datadir  = $databasedir/data"
check_mysqld_ini_variable "character_set_client_handshake = FALSE" 1
check_mysqld_ini_variable "character_set_server = utf8mb4" 1
check_mysqld_ini_variable "collation_server = utf8mb4_unicode_ci" 1
echo
echo "#Description: If set to 1, LOCAL is supported for LOAD DATA INFILE statements."
echo "#If set to 0 (default), usually for security reasons, attempts to perform a"
echo "#LOAD DATA LOCAL will fail with an error message."
check_mysqld_ini_variable "local_infile = 1" 2
echo
echo "[inlookup]"
echo "#The number of seconds the server waits for activity on an"
echo "#interactive connection before closing it. An interactive client is"
echo "#defined as a client that uses the 'CLIENT_INTERACTIVE' option to connect"
echo "interactive_timeout=28880"
echo
echo "#The number of seconds to wait for more data from a connection"
echo "#before aborting the read. This timeout applies only to TCP/IP"
echo "#connections, not to connections made via Unix socket files, named"
echo "#pipes, or shared memory."
echo "net_read_timeout=5"
echo
echo "#The number of seconds to wait for a block to be written to a"
echo "#connection before aborting the write. This timeout applies only to"
echo "#TCP/IP connections, not to connections made via Unix socket files,"
echo "#named pipes, or shared memory."
echo "net_write_timeout=5"
echo
echo "#The number of seconds the server waits for activity on a"
echo "#non-interactive connection before closing it. This timeout applies"
echo "#only to TCP/IP and Unix socket file connections, not to"
echo "#connections made via named pipes, or shared memory."
echo "wait_timeout=28800"
}

create_svscan()
{
if [ $# -lt 1 ] ; then
	echo "USAGE: create_svscan supervise_dir [initcmd]" 1>&2
	return 1
fi
SERVICEDIR=$1
if [ $# -eq 2 ] ; then
init_cmd=$2
else
init_cmd=""
fi
if [ $nooverwrite -eq 1 -a -d "$DESTDIR"$SERVICEDIR/.svscan/log ] ; then
	return 0
fi
# Setup variables INITCMD, SCANINTERVAL, SCANLOG, UNSHARE
conf_dir="$DESTDIR"$SERVICEDIR/.svscan/variables
if [ $run_file_only -eq 1 ] ; then
	if [ -d $conf_dir ] ; then
		/bin/mv $conf_dir "$conf_dir".bak
	fi
fi
/bin/mkdir -p $conf_dir
/bin/chmod 500 $conf_dir
echo "$prog_args" > $conf_dir/.options
if [ -z $init_cmd ] ; then
	echo           > $conf_dir/INITCMD
else
	echo $init_cmd > $conf_dir/INITCMD
fi
echo "/usr/bin:/bin:/usr/local/bin:/usr/sbin:/sbin:/usr/local/sbin" > $conf_dir/PATH
if [ " $scan_interval" = " " ] ; then
	echo           "300"  > $conf_dir/SCANINTERVAL
	else
	echo "$scan_interval" > $conf_dir/SCANINTERVAL
fi
echo > $conf_dir/SCANLOG
if [ -x /usr/bin/unshare -a $use_unshare -eq 1 ] ; then
	echo > $conf_dir/UNSHARE
else
	     > $conf_dir/UNSHARE
fi

/bin/mkdir -p "$DESTDIR"$SERVICEDIR/.svscan/log
/bin/mkdir -p "$DESTDIR"$sysconfdir
if [ -x /usr/bin/unshare -a -x "$DESTDIR"$SERVICEDIR/dnscache/run ] ; then
	# svscan run script
	(
	echo "#!/bin/sh"
	echo "$RCSID"
	echo "# generated on $host on `date`"
	echo "# $prog_args"
	echo ""
	echo "echo svscan \$PPID initialization PID \$\$"
	echo "exec 2>&1"
	echo "/usr/bin/mount --bind $sysconfdir/resolv.conf /etc/resolv.conf"
	echo "/usr/bin/mount -l"
	) > "$DESTDIR"$SERVICEDIR/.svscan/run
	(
	echo "# $prog_args"
	echo "search `uname -n`"
	echo "nameserver 127.0.0.1"
	) > "$DESTDIR"$sysconfdir/resolv.conf
	/bin/chmod +x "$DESTDIR"$SERVICEDIR/.svscan/run
else
	if [ -x "$DESTDIR"$SERVICEDIR/.svscan/run ] ; then
		/bin/chmod -x "$DESTDIR"$SERVICEDIR/.svscan/run
	fi
fi

(
echo "#!/bin/sh"
echo "$RCSID"
echo "# generated on $host on `date`"
echo "# $prog_args"
echo ""
echo "exec 2>&1"
echo "exec $QmailBinPrefix/bin/svc -Gdx ../* ../*/log ./log"
) > "$DESTDIR"$SERVICEDIR/.svscan/shutdown
/bin/chmod +x "$DESTDIR"$SERVICEDIR/.svscan/shutdown

if [ ! -d $LOGDIR ] ; then
	/bin/mkdir -p $LOGDIR
	$chown qmaill:nofiles $LOGDIR
fi
# svscan log script
(
echo "#!/bin/sh"
echo "$RCSID"
echo "# generated on $host on `date`"
echo "# $prog_args"
echo ""
echo "exec $QmailBinPrefix/bin/setuidgid qmaill \\"
echo "$QmailBinPrefix/sbin/multilog t $LOGDIR/svscan"
) > "$DESTDIR"$SERVICEDIR/.svscan/log/run
/bin/chmod +x "$DESTDIR"$SERVICEDIR/.svscan/log/run

if [ $run_file_only -eq 1 ] ; then
	if [ -d "$conf_dir".bak ] ; then
		/bin/rm -rf $conf_dir
		/bin/mv "$conf_dir".bak $conf_dir
	fi
fi

# resolvconf script using inotify
if [ -x /usr/bin/unshare -a -x "$DESTDIR"$SERVICEDIR/dnscache/run -a -x "$DESTDIR"$QmailBinPrefix/bin/inotify ] ; then
conf_dir="$DESTDIR"$SERVICEDIR/resolvconf/variables
if [ $run_file_only -eq 1 ] ; then
	if [ -d $conf_dir ] ; then
		/bin/mv $conf_dir "$conf_dir".bak
	fi
fi
/bin/mkdir -p "$DESTDIR"$SERVICEDIR/resolvconf/log
if [ $down_state -eq 1 ] ; then
	$TOUCH "$DESTDIR"$SERVICEDIR/resolvconf/down
fi
/bin/mkdir -p $conf_dir
/bin/chmod 500 $conf_dir
echo "$prog_args" > $conf_dir/.options
# resolvconf run script
(
echo "#!/bin/sh"
echo "$RCSID"
echo "# generated on $host on `date`"
echo "# $prog_args"
echo ""
echo "trap clean_up 1 2 15"
echo ""
echo "function clean_up"
echo "{"
echo "	echo \"shutting down\""
echo "	pkill -P \`jobs -p\` inotify"
echo "	exit"
echo "}"
echo ""
echo "if [ -f /etc/resolv.conf -a ! -L /etc/resolv.conf ] ; then"
echo "	file=/etc/resolv.conf"
echo "else"
echo "	file=\`file /etc/resolv.conf |awk '{print \$5}'\`"
echo "fi"
echo "dir=\`dirname \$file\`"
echo "echo \"starting with resolv_conf_dir=\$dir\""
echo "/bin/cat /etc/resolv.conf"
echo "exec 2>&1"
echo "("
echo "/usr/bin/inotify -n \$dir | while read line"
echo "do"
echo "	set \$line"
echo "	if [ \" \$1\" != \" file\" ] ; then"
echo "		continue"
echo "	fi"
echo "	file=\$2"
echo "	event=\$3"
echo "	if [ \" \$file\" != \" resolv.conf\" ] ; then"
echo "		continue"
echo "	fi"
echo "	if [ \" \$event\" != \" closed\" ] ; then"
echo "		continue"
echo "	fi"
echo "	list=\`grep nameserver /etc/resolv.conf\` > /dev/null"
echo "	if [ \$? -eq 0 ] ; then"
echo "		echo \$list"
echo "		echo \"/usr/bin/umount /etc/resolv.conf\""
echo "		/usr/bin/umount /etc/resolv.conf"
echo "		echo \"/usr/bin/mount --bind /etc/indimail/resolv.conf /etc/resolv.conf\""
echo "		/usr/bin/mount --bind /etc/indimail/resolv.conf /etc/resolv.conf"
echo "	fi"
echo "done"
echo ") &"
echo "wait"
) > "$DESTDIR"$SERVICEDIR/resolvconf/run
/bin/chmod +x "$DESTDIR"$SERVICEDIR/resolvconf/run

# resolvconf log script
(
echo "#!/bin/sh"
echo "$RCSID"
echo "# generated on $host on `date`"
echo "# $prog_args"
echo ""
echo "exec $QmailBinPrefix/bin/setuidgid qmaill \\"
echo "$QmailBinPrefix/sbin/multilog t $LOGDIR/resolvconf"
) > "$DESTDIR"$SERVICEDIR/resolvconf/log/run
/bin/chmod +x "$DESTDIR"$SERVICEDIR/resolvconf/log/run
fi

if [ $run_file_only -eq 1 ] ; then
	if [ -d "$conf_dir".bak ] ; then
		/bin/rm -rf $conf_dir
		/bin/mv "$conf_dir".bak $conf_dir
	fi
fi
}

create_fetchmail()
{
if [ $# -ne 4 ] ; then
	echo "USAGE: create_fetchmail qbase queue_count first_queue_no supervise_dir" 1>&2
	return 1
fi
QUEUE_BASE=$1
NO_OF_QUEUES=$2
FIRST_QUEUE=$3
SERVICEDIR=$4

if [ $nooverwrite -eq 1 -a -d "$DESTDIR"$SERVICEDIR/fetchmail/variables ] ; then
	return 0
fi
conf_dir="$DESTDIR"$SERVICEDIR/fetchmail/variables
if [ $run_file_only -eq 1 ] ; then
	if [ -d $conf_dir ] ; then
		/bin/mv $conf_dir "$conf_dir".bak
	fi
fi
/bin/mkdir -p "$DESTDIR"$SERVICEDIR/fetchmail/log
if [ $down_state -eq 1 ] ; then
	$TOUCH "$DESTDIR"$SERVICEDIR/fetchmail/down
fi
/bin/mkdir -p $conf_dir
/bin/chmod 500 $conf_dir
echo $QUEUE_BASE > $conf_dir/QUEUE_BASE
echo $NO_OF_QUEUES > $conf_dir/QUEUE_COUNT
echo $FIRST_QUEUE > $conf_dir/QUEUE_START
if [ " $min_free" = " " ] ; then
	echo 52428800 > $conf_dir/MIN_FREE
else
	echo $min_free > $conf_dir/MIN_FREE
fi
if [ " $QmailBinPrefix" = " /usr" ] ; then
	echo "/bin:/usr/bin:/usr/sbin:/sbin" > $conf_dir/PATH
else
	echo "/bin:/usr/bin:$QmailBinPrefix/bin:$QmailBinPrefix/sbin" > $conf_dir/PATH
fi
if [ ! " $CONTROLDIR" = " " ] ; then
	echo $CONTROLDIR > $conf_dir/CONTROLDIR
else
	> $conf_dir/CONTROLDIR
fi
if [ " $usefsync" = " " ] ; then
	> $conf_dir/USE_FSYNC
else
	echo > $conf_dir/USE_FSYNC
fi
if [ " $usesyncdir" = " " ] ; then
	> $conf_dir/USE_SYNCDIR
else
	echo > $conf_dir/USE_SYNCDIR
fi
if [ ! " $memory" = " " ] ; then
	echo $memory > $conf_dir/SOFT_MEM
else
	echo 5242880 > $conf_dir/SOFT_MEM
fi
if [ ! " $spamfilter" = " " ] ; then
	echo "$spamfilter" > $conf_dir/SPAMFILTER
	echo "1" > $conf_dir/MAKE_SEEKABLE
	if [ ! " $spamexitcode" = " " ] ; then
		echo "$spamexitcode" > $conf_dir/SPAMEXITCODE
		if [ ! " $rejectspam" = " " ] ; then
			echo "$rejectspam" > $conf_dir/REJECTSPAM
		else
			> $conf_dir/REJECTSPAM
		fi
	else
		> $conf_dir/SPAMEXITCODE
	fi
else
	> $conf_dir/SPAMFILTER
	> $conf_dir/REJECTSPAM
	> $conf_dir/SPAMEXITCODE
fi
if [ " $qhpsi" = " " ] ; then
	> $conf_dir/QHPSI
else
	echo $qhpsi > $conf_dir/QHPSI
fi
if [ ! " $domainlimits" = " " ] ; then
	echo  > $conf_dir/DOMAIN_LIMITS
else
	> $conf_dir/DOMAIN_LIMITS
fi
case "$dkverify_option" in
	dkimstrict)
	/bin/rm -f $conf_dir/DKSIGN $conf_dir/DKIMSIGN $conf_dir/DKVERIFY $conf_dir/DKIMVERIFY $conf_dir/DKQUEUE $conf_dir/DKIMQUEUE
	echo FGHIKLMNOQRTUVWjp > $conf_dir/DKIMVERIFY
	> $conf_dir/UNSIGNED_SUBJECT
	> $conf_dir/UNSIGNED_FROM
	echo "$QmailBinPrefix/sbin/qmail-dkim" > $conf_dir/QMAILQUEUE
	;;
	dkim)
	/bin/rm -f $conf_dir/DKSIGN $conf_dir/DKIMSIGN $conf_dir/DKVERIFY $conf_dir/DKIMVERIFY $conf_dir/DKQUEUE $conf_dir/DKIMQUEUE
	echo > $conf_dir/DKIMVERIFY
	echo > $conf_dir/UNSIGNED_SUBJECT
	> $conf_dir/UNSIGNED_FROM
	echo "$QmailBinPrefix/sbin/qmail-dkim" > $conf_dir/QMAILQUEUE
	;;
	dkstrict)
	echo BDEGIJKfh > $conf_dir/DKVERIFY
	/bin/rm -f $conf_dir/DKSIGN $conf_dir/DKIMSIGN $conf_dir/DKVERIFY $conf_dir/DKIMVERIFY $conf_dir/DKQUEUE $conf_dir/DKIMQUEUE
	echo "$QmailBinPrefix/sbin/qmail-dk" > $conf_dir/QMAILQUEUE
	;;
	dk)
	echo > $conf_dir/DKVERIFY
	/bin/rm -f $conf_dir/DKSIGN $conf_dir/DKIMSIGN $conf_dir/DKVERIFY $conf_dir/DKIMVERIFY $conf_dir/DKQUEUE $conf_dir/DKIMQUEUE
	echo "$QmailBinPrefix/sbin/qmail-dk" > $conf_dir/QMAILQUEUE
	;;
	bothstrict)
	/bin/rm -f $conf_dir/DKSIGN $conf_dir/DKIMSIGN $conf_dir/DKVERIFY $conf_dir/DKIMVERIFY $conf_dir/DKQUEUE $conf_dir/DKIMQUEUE
	echo FGHIKLMNOQRTUVWjp > $conf_dir/DKIMVERIFY
	echo BDEGIJKfh > $conf_dir/DKVERIFY
	> $conf_dir/UNSIGNED_SUBJECT
	> $conf_dir/UNSIGNED_FROM
	echo "$QmailBinPrefix/sbin/qmail-dk" > $conf_dir/QMAILQUEUE
	echo "$QmailBinPrefix/sbin/qmail-dkim" > $conf_dir/DKQUEUE
	;;
	both)
	/bin/rm -f $conf_dir/DKSIGN $conf_dir/DKIMSIGN $conf_dir/DKVERIFY $conf_dir/DKIMVERIFY $conf_dir/DKQUEUE $conf_dir/DKIMQUEUE
	echo > $conf_dir/DKIMVERIFY
	echo > $conf_dir/DKVERIFY
	echo > $conf_dir/UNSIGNED_SUBJECT
	> $conf_dir/UNSIGNED_FROM
	echo "$QmailBinPrefix/sbin/qmail-dk" > $conf_dir/QMAILQUEUE
	echo "$QmailBinPrefix/sbin/qmail-dkim" > $conf_dir/DKQUEUE
	;;
	none|*)
	/bin/rm -f $conf_dir/DKSIGN $conf_dir/DKIMSIGN $conf_dir/DKVERIFY $conf_dir/DKIMVERIFY $conf_dir/DKQUEUE $conf_dir/DKIMQUEUE
	if [ $no_multi -eq 1 ] ; then
		> $conf_dir/QMAILQUEUE
		echo "$QUEUE_BASE"/queue1 > $conf_dir/QUEUEDIR
	else
		echo "$QmailBinPrefix/sbin/qmail-multi" > $conf_dir/QMAILQUEUE
		> $conf_dir/QUEUEDIR
	fi
	;;
esac
(
echo "#!/bin/sh"
echo "$RCSID"
echo "# generated on $host on `date`"
echo "# $prog_args"
echo ""
echo "exec 2>&1"
echo "exec $QmailBinPrefix/bin/envdir variables sh -c \""
echo "exec $QmailBinPrefix/bin/setuidgid indimail \\"
echo "$QmailBinPrefix/bin/softlimit -m \\\$SOFT_MEM -o 1024 \\"
if [ $silent -eq 1 ] ; then
	echo "$QmailBinPrefix/bin/fetchmail --silent --nodetach -f $sysconfdir/fetchmailrc\""
else
	echo "$QmailBinPrefix/bin/fetchmail --nodetach -f $sysconfdir/fetchmailrc\""
fi
) > "$DESTDIR"$SERVICEDIR/fetchmail/run
/bin/chmod +x "$DESTDIR"$SERVICEDIR/fetchmail/run

if [ ! -d $LOGDIR ] ; then
	/bin/mkdir -p $LOGDIR
	$chown qmaill:nofiles $LOGDIR
fi
# fetchmail log script
(
echo "#!/bin/sh"
echo "$RCSID"
echo "# generated on $host on `date`"
echo "# $prog_args"
echo ""
echo "exec $QmailBinPrefix/bin/setuidgid qmaill \\"
echo "$QmailBinPrefix/sbin/multilog t $LOGDIR/fetchmail"
) > "$DESTDIR"$SERVICEDIR/fetchmail/log/run
/bin/chmod +x "$DESTDIR"$SERVICEDIR/fetchmail/log/run
echo "$prog_args" > $conf_dir/.options

if [ $run_file_only -eq 1 ] ; then
	if [ -d "$conf_dir".bak ] ; then
		/bin/rm -rf $conf_dir
		/bin/mv "$conf_dir".bak $conf_dir
	fi
fi

if [ ! " $logfilter" = " " ] ; then
	echo  $logfilter > $conf_dir/LOGFILTER
	if [ ! -f $SERVICEDIR/qmail-logfifo/run ] ; then
		prog_args="$QmailBinPrefix/sbin/svctool --fifologger=\"$logfilter\" --servicedir=\"$SERVICEDIR\""
		create_fifologger $logfilter $SERVICEDIR
	fi
else
	> $conf_dir/LOGFILTER
fi
}

create_poppass()
{
if [ $# -ne 4 ] ; then
	echo "USAGE: create_poppass supervise_dir poppass_port password_command use_ssl=0|1" 1>&2
	return 1
fi
SERVICEDIR=$1
pwd_cmd=$3
poppass_ssl=$4
if [ " $poppass_ssl" = " 1" -a " $certfile" = " " ] ; then
	echo "Certificate not specfied" 1>&2
	return 1
fi

if [ " $servicetag" = " " ] ; then
	tag=$2
else
	tag=$servicetag
fi

if [ $nooverwrite -eq 1 -a -d "$DESTDIR"$SERVICEDIR/qmail-poppass.$tag/variables ] ; then
	return 0
fi
conf_dir="$DESTDIR"$SERVICEDIR/qmail-poppass.$tag/variables
if [ $run_file_only -eq 1 ] ; then
	if [ -d $conf_dir ] ; then
		/bin/mv $conf_dir "$conf_dir".bak
	fi
fi
/bin/mkdir -p "$DESTDIR"$SERVICEDIR/qmail-poppass.$tag/log
if [ $down_state -eq 1 ] ; then
	$TOUCH "$DESTDIR"$SERVICEDIR/qmail-poppass.$tag/down
fi
/bin/mkdir -p $conf_dir
$chown root:indimail $conf_dir
/bin/chmod 550 $conf_dir

if [ " $ipaddress" = " " ] ; then
	echo 0 > $conf_dir/LOCALIP
else
	echo $ipaddress > $conf_dir/LOCALIP
fi
if [ ! " $memory" = " " ] ; then
	echo $memory > $conf_dir/SOFT_MEM
else
	echo 52428800 > $conf_dir/SOFT_MEM
fi
echo $2 > $conf_dir/PORT
if [ ! " $maxdaemons" = " " ] ; then
	echo "$maxdaemons" > $conf_dir/MAXDAEMONS
else
	echo $CONCURRENCYINCOMING > $conf_dir/MAXDAEMONS
fi
if [ ! " $maxperip" = " " ] ; then
	echo "$maxperip" > $conf_dir/MAXPERIP
else
	echo 10 > $conf_dir/MAXPERIP
fi
if [ -f /bin/false ] ; then
	false="/bin/false"
else
	false="/usr/bin/false"
fi
if [ ! " $pwd_cmd" = " " ] ; then
	echo "$pwd_cmd $false" > $conf_dir/PASSWORD_COMMAND
else
	echo "$QmailBinPrefix""/sbin/vsetpass $false" > $conf_dir/PASSWORD_COMMAND
fi
if [ " $poppass_ssl" = " 1" ] ; then
	echo $certfile > $conf_dir/CERTFILE
else
	> $conf_dir/CERTFILE
fi
(
echo "#!/bin/sh"
echo "$RCSID"
echo "# generated on $host on `date`"
echo "# $prog_args"
echo ""
echo "exec 2>&1"
echo "QMAILDUID=\`/usr/bin/id -u indimail\`"
echo "NOFILESGID=\`/usr/bin/id -g indimail\`"
echo "HOSTNAME=\`uname -n\`"
echo ""
echo "if [ -z \"\$QMAILDUID\" -o -z \"\$NOFILESGID\" ]; then"
echo "    echo QMAILDUID or NOFILESGID is unset in"
echo "    echo \`pwd\`/run"
echo "    sleep 5"
echo "    exit 1"
echo "fi"
echo "if [ ! -f \$CERTFILE ]; then"
echo "    echo Certificate not present"
echo "    sleep 5"
echo "    exit 1"
echo "fi"
echo ""
echo "exec $QmailBinPrefix/bin/envdir variables sh -c \""
echo "exec $QmailBinPrefix/bin/softlimit -m \\\$SOFT_MEM -o 1024 \\"
echo "$QmailBinPrefix/bin/tcpserver -v -H -R -l \$HOSTNAME \\"
echo "-x $sysconfdir/tcp/tcp.poppass.cdb -X \\"
echo "-c variables/MAXDAEMONS -C \\\$MAXPERIP -o -b \\\$MAXDAEMONS \\"
if [ " $poppass_ssl" = " 1" ] ; then
	echo "-n \\\$CERTFILE \\"
fi
if [ -f /bin/false ] ; then
	false="/bin/false"
else
	false="/usr/bin/false"
fi
echo "-u \$QMAILDUID -g \$NOFILESGID \\\$LOCALIP \\\$PORT \\"
echo "$QmailBinPrefix/sbin/qmail-poppass \$HOSTNAME $QmailBinPrefix/sbin/vchkpass $false\""
) > /tmp/poppass-run.$$
/bin/mv /tmp/poppass-run.$$ "$DESTDIR"$SERVICEDIR/qmail-poppass.$tag/run
/bin/chmod +x "$DESTDIR"$SERVICEDIR/qmail-poppass.$tag/run

if [ ! -d $LOGDIR ] ; then
	/bin/mkdir -p $LOGDIR
	$chown qmaill:nofiles $LOGDIR
fi
# qmail-poppass log script
(
echo "#!/bin/sh"
echo "$RCSID"
echo "# generated on $host on `date`"
echo "# $prog_args"
echo ""
echo "exec $QmailBinPrefix/bin/setuidgid qmaill \\"
echo "$QmailBinPrefix/sbin/multilog t $LOGDIR/poppass.$tag"
) > /tmp/popass-run.$$
/bin/mv /tmp/popass-run.$$ "$DESTDIR"$SERVICEDIR/qmail-poppass.$tag/log/run
/bin/chmod +x "$DESTDIR"$SERVICEDIR/qmail-poppass.$tag/log/run
echo "$prog_args" > $conf_dir/.options

if [ $run_file_only -eq 1 ] ; then
	if [ -d "$conf_dir".bak ] ; then
		/bin/rm -rf $conf_dir
		/bin/mv "$conf_dir".bak $conf_dir
	fi
fi
}

create_delivery()
{
if [ $# -ne 8 ] ; then
	echo "USAGE: create_delivery qbase queue_count first_queue_no supervise_dir ident routes=smtp|qmtp|static use_ssl utf8" 1>&2
	return 1
fi
QUEUE_BASE=$1
NO_OF_QUEUES=$2
FIRST_QUEUE=$3
SERVICEDIR=$4
QUEUE_IDENT=$5
routes=$6
qmr_ssl=$7
utf8=$8
if [ " $servicetag" = " " ] ; then
	tag=$QUEUE_IDENT
else
	tag=$servicetag
fi

# Create QUEUES
#---------------------------------------------------------------------------------------
if [ ! " $QUEUE_BASE" = " $QmailHOME" ] ; then
	if [ ! -d "$DESTDIR"$QUEUE_BASE ] ; then
		/bin/mkdir -p "$DESTDIR"$QUEUE_BASE
	fi
	/bin/chmod 755 "$DESTDIR"$QUEUE_BASE
	$chown root:qmail "$DESTDIR"$QUEUE_BASE
fi
if [ ! -d "$DESTDIR"$QUEUE_BASE/nqueue ] ; then
	/bin/mkdir -p "$DESTDIR"$QUEUE_BASE/nqueue
fi
if [ $nooverwrite -eq 1 -a -d "$DESTDIR"$QUEUE_BASE/nqueue ] ; then
	return 0
fi
echo "Creating Queue "$DESTDIR"$QUEUE_BASE/nqueue"
if [ -f "$DESTDIR"$QmailBinPrefix/bin/queue-fix ] ; then
	"$DESTDIR"$QmailBinPrefix/bin/queue-fix "$DESTDIR"$QUEUE_BASE/nqueue > /dev/null
else
	./queue-fix "$DESTDIR"$QUEUE_BASE/nqueue > /dev/null
fi

QUEUE_NO=$FIRST_QUEUE
COUNT=1
while true
do
	if [ ! -d "$DESTDIR"$QUEUE_BASE/queue"$QUEUE_NO" ] ; then
		/bin/mkdir -p "$DESTDIR"$QUEUE_BASE/queue"$QUEUE_NO"
	fi
	echo "Creating Queue "$DESTDIR"$QUEUE_BASE/queue"$QUEUE_NO""
	if [ -f "$DESTDIR"$QmailBinPrefix/bin/queue-fix ] ; then
		"$DESTDIR"$QmailBinPrefix/bin/queue-fix "$DESTDIR"$QUEUE_BASE/queue"$QUEUE_NO" > /dev/null
	else
		./queue-fix "$DESTDIR"$QUEUE_BASE/queue"$QUEUE_NO" > /dev/null
	fi
	if [ $COUNT -eq $NO_OF_QUEUES ] ; then
		break
	fi
	COUNT=`expr $COUNT + 1`
	QUEUE_NO=`expr $QUEUE_NO + 1`
done
echo $QUEUE_BASE > "$DESTDIR"$CONTROLDIR/queue_base

# qmail-send script
conf_dir="$DESTDIR"$SERVICEDIR/qmail-send.$tag/variables
if [ $run_file_only -eq 1 ] ; then
	if [ -d $conf_dir ] ; then
		/bin/mv $conf_dir "$conf_dir".bak
	fi
fi
/bin/mkdir -p "$DESTDIR"$SERVICEDIR/qmail-send.$tag/log
if [ $down_state -eq 1 ] ; then
	$TOUCH "$DESTDIR"$SERVICEDIR/qmail-send.$tag/down
fi
/bin/mkdir -p $conf_dir
/bin/chmod 500 $conf_dir
if [ $no_multi -eq 1 ] ; then
	echo "$QUEUE_BASE"/queue1 > $conf_dir/QUEUEDIR
	> $conf_dir/QMAILQUEUE
else
	echo $QUEUE_BASE > $conf_dir/QUEUE_BASE
	echo $NO_OF_QUEUES > $conf_dir/QUEUE_COUNT
	echo $FIRST_QUEUE > $conf_dir/QUEUE_START
	echo "$QmailBinPrefix/sbin/qmail-multi" > $conf_dir/QMAILQUEUE
	> $conf_dir/QUEUEDIR
fi
if [ " $min_free" = " " ] ; then
	echo 52428800 > $conf_dir/MIN_FREE
else
	echo $min_free > $conf_dir/MIN_FREE
fi
if [ " $QmailBinPrefix" = " /usr" ] ; then
	echo "/bin:/usr/bin:/usr/sbin:/sbin" > $conf_dir/PATH
else
	echo "/bin:/usr/bin:$QmailBinPrefix/bin:$QmailBinPrefix/sbin" > $conf_dir/PATH
fi
if [ $qmr_ssl -eq 1 ] ; then
echo $sysconfdir/certs > $conf_dir/CERTDIR #for qmail-remote
fi
if [ $utf8 -eq 1 ] ; then
	echo $utf8 > $conf_dir/UTF8
else
	> $conf_dir/UTF8
fi
if [ ! " $routes" = " " ] ; then
	echo $routes > $conf_dir/ROUTES
else
	> $conf_dir/ROUTES
fi
if [ " $enable_cname_lookup" = " " ] ; then
	echo 1 > $conf_dir/DISABLE_CNAME_LOOKUP
else
	> $conf_dir/DISABLE_CNAME_LOOKUP
fi
if [ ! " $CONTROLDIR" = " " ] ; then
	echo "$CONTROLDIR" > $conf_dir/CONTROLDIR
else
	> $conf_dir/CONTROLDIR
fi
if [ ! " $mailcount_limit" = " " ] ; then
	echo "$mailcount_limit" > $conf_dir/MAILCOUNT_LIMIT
else
	> $conf_dir/MAILCOUNT_LIMIT
fi
if [ ! " $mailsize_limit" = " " ] ; then
	echo "$mailsize_limit" > $conf_dir/MAILSIZE_LIMIT
else
	> $conf_dir/MAILSIZE_LIMIT
fi
if [ ! " $domainlimits" = " " ] ; then
	echo  > $conf_dir/DOMAIN_LIMITS
else
	> $conf_dir/DOMAIN_LIMITS
fi
> $conf_dir/FAST_QUOTA
echo "8192"  > $conf_dir/MAILDIRSIZE_MAX_SIZE
echo "43200" > $conf_dir/MAILDIRSIZE_MAX_AGE
if [ ! " $overquota_mailsize" = " " ] ; then
	echo $overquota_mailsize > $conf_dir/OVERQUOTA_MAILSIZE
else
	> $conf_dir/OVERQUOTA_MAILSIZE
fi
if [ " $usefsync" = " " ] ; then
	> $conf_dir/USE_FSYNC
else
	echo > $conf_dir/USE_FSYNC
fi
if [ " $usesyncdir" = " " ] ; then
	> $conf_dir/USE_SYNCDIR
else
	echo > $conf_dir/USE_SYNCDIR
fi
if [ ! " $dmemory" = " " ] ; then
	echo $dmemory > $conf_dir/SOFT_MEM
else
	echo 83886080 > $conf_dir/SOFT_MEM
fi
if [ " $persistdb" = " 1" ] ; then
	echo postmaster > $conf_dir/ROUTE_NULL_USER
	echo > $conf_dir/AUTHSELF
	echo 1 > $conf_dir/MYSQL_OPT_RECONNECT
else
	> $conf_dir/ROUTE_NULL_USER
	> $conf_dir/AUTHSELF
	> $conf_dir/MYSQL_OPT_RECONNECT
fi
if [ ! " $remoteauthsmtp" = " " ] ; then
	echo $remoteauthsmtp > $conf_dir/AUTH_SMTP
else
	> $conf_dir/AUTH_SMTP
fi
if [ ! " $localfilter" = " " ] ; then
	echo "$QmailBinPrefix/sbin/spawn-filter" > $conf_dir/QMAILLOCAL
	echo "1" > $conf_dir/MAKE_SEEKABLE
else
	> $conf_dir/QMAILLOCAL
fi
if [ ! " $remotefilter" = " " ] ; then
	echo "$QmailBinPrefix/sbin/spawn-filter" > $conf_dir/QMAILREMOTE
	echo "$CONTROLDIR/ratelimit" > $conf_dir/RATELIMIT_DIR
	echo "1" > $conf_dir/MAKE_SEEKABLE
else
	> $conf_dir/QMAILREMOTE
fi
echo "startup.so" > $conf_dir/START_PLUGIN
> $conf_dir/SPAMFILTER
> $conf_dir/REJECTSPAM
> $conf_dir/SPAMEXITCODE
#
# DEFAULT_DOMAIN will be used by vdelivermail for bounces
#
if [ ! " $CONTROLDIR" = " " ] ; then
	if [ -f $CONTROLDIR/defaulthost ] ; then
		ln -sf $CONTROLDIR/defaulthost $conf_dir/DEFAULT_DOMAIN
	else
		> $conf_dir/DEFAULT_DOMAIN
	fi
else
	> $conf_dir/DEFAULT_DOMAIN
fi
echo > $conf_dir/LOCK_LOGS
case "$dksign_option" in
	dkim)
	/bin/rm -f $conf_dir/DKSIGN $conf_dir/DKIMSIGN $conf_dir/DKVERIFY $conf_dir/DKIMVERIFY $conf_dir/DKQUEUE $conf_dir/DKIMQUEUE
	echo "$private_key" > $conf_dir/DKIMSIGN
	> $conf_dir/UNSIGNED_SUBJECT
	> $conf_dir/UNSIGNED_FROM
	if [ ! -f "$DESTDIR"$CONTROLDIR/filterargs ] ; then
		echo "*:remote:$QmailBinPrefix/bin/dk-filter" > "$DESTDIR"$CONTROLDIR/filterargs
	fi
	;;
	dk)
	/bin/rm -f $conf_dir/DKSIGN $conf_dir/DKIMSIGN $conf_dir/DKVERIFY $conf_dir/DKIMVERIFY $conf_dir/DKQUEUE $conf_dir/DKIMQUEUE
	echo "$private_key" > $conf_dir/DKSIGN
	if [ ! -f "$DESTDIR"$CONTROLDIR/filterargs ] ; then
		echo "*:remote:$QmailBinPrefix/bin/dk-filter" > "$DESTDIR"$CONTROLDIR/filterargs
	fi
	;;
	both)
	echo "$private_key" > $conf_dir/DKSIGN
	echo "$private_key" > $conf_dir/DKIMSIGN
	echo > $conf_dir/UNSIGNED_SUBJECT
	> $conf_dir/UNSIGNED_FROM
	if [ ! -f "$DESTDIR"$CONTROLDIR/filterargs ] ; then
		echo "*:remote:$QmailBinPrefix/bin/dk-filter" > "$DESTDIR"$CONTROLDIR/filterargs
	fi
	;;
	none|*)
	/bin/rm -f $conf_dir/DKSIGN $conf_dir/DKIMSIGN $conf_dir/DKVERIFY $conf_dir/DKIMVERIFY $conf_dir/DKQUEUE $conf_dir/DKIMQUEUE
	;;
esac
(
echo "#!/bin/sh"
echo "$RCSID"
echo "# generated on $host on `date`"
echo "# $prog_args"
echo ""
echo "exec 2>&1"
echo "if [ -s variables/CONTROLDIR ] ; then"
echo "  cntrl_dir=\`/bin/cat variables/CONTROLDIR\`"
echo "else"
echo "  cntrl_dir=/etc/indimail/control"
echo "fi"
echo "if [ -f \$cntrl_dir/defaultdelivery ] ; then"
echo "  defaultdelivery=\`/bin/cat \$cntrl_dir/defaultdelivery\`"
echo "else"
echo "  defaultdelivery=\"./Maildir/\""
echo "fi"
echo "exec $QmailBinPrefix/bin/envdir variables sh -c \""
echo "exec $QmailBinPrefix/bin/softlimit -m \\\$SOFT_MEM -o 1024 \\"
echo "$QmailBinPrefix/sbin/qmail-daemon \$defaultdelivery\""
) > "$DESTDIR"$SERVICEDIR/qmail-send."$tag"/run
/bin/chmod +x "$DESTDIR"$SERVICEDIR/qmail-send."$tag"/run

if [ ! -d $LOGDIR ] ; then
	/bin/mkdir -p $LOGDIR
	$chown qmaill:nofiles $LOGDIR
fi
# qmail-send log script
/bin/mkdir -p "$DESTDIR"$SERVICEDIR/qmail-send."$tag"/log
if [ $down_state -eq 1 ] ; then
	$TOUCH "$DESTDIR"$SERVICEDIR/qmail-send.$tag/down
fi
(
echo "#!/bin/sh"
echo "$RCSID"
echo "# generated on $host on `date`"
echo "# $prog_args"
echo ""
echo "exec $QmailBinPrefix/bin/setuidgid qmaill \\"
echo "$QmailBinPrefix/sbin/multilog t $LOGDIR/deliver."$tag""
) > "$DESTDIR"$SERVICEDIR/qmail-send."$tag"/log/run
/bin/chmod +x "$DESTDIR"$SERVICEDIR/qmail-send."$tag"/log/run
if [ -z "$skipsend" ] ; then
	echo "$prog_args" > $conf_dir/.options
fi

if [ $run_file_only -eq 1 ] ; then
	if [ -d "$conf_dir".bak ] ; then
		/bin/rm -rf $conf_dir
		/bin/mv "$conf_dir".bak $conf_dir
	fi
fi
}

rmsvc()
{
if [ $# -lt 1 ] ; then
	echo "rmsvc service_with_full_path" 1>&2
	return 1
fi
for i in $*
do
	if [ ! -d $i ] ; then
		echo "$i: No such file or directory" 1>&2
		continue
	fi
	dir=`dirname $i`
	svcname=`basename $i`
	if [ ! -p $i/supervise/control ] ; then
		echo "$i/supervise not a supervise directory" 1>&2
		continue
	fi
	/bin/mv $i $dir/".""$svcname"
	#
	# prepend a . to the directory so that svscan will skip this directory
	#
	echo "Removed Service $svcname    : `"$DESTDIR"$QmailBinPrefix/bin/svc -d $dir/"."$svcname 2>&1`"
	if [ -d $dir/"."$svcname/log ] ; then
		echo "Removed Service $svcname/log: `"$DESTDIR"$QmailBinPrefix/bin/svc -d $dir/"."$svcname/log 2>&1`"
	fi
done
}

ensvc()
{
if [ $# -lt 1 ] ; then
	echo "ensvc service_with_full_path" 1>&2
	return 1
fi
for i in $*
do
	if [ ! -d $i ] ; then
		echo "$i: No such file or directory" 1>&2
		continue
	fi
	dir=`dirname $i`
	svcname=`basename $i`
	first_char=`echo $svcname | cut -c1`
	if [ " $first_char" = " ." ] ; then
		svcname=`echo $svcname | cut -c2-`
		/bin/mv $i $dir/$svcname
		echo "Enabled Service $svcname" 
	else
		echo "Service $i is not disabled (should have a '.' as the first char in $svcname)" 1>&2
	fi
done
sleep 5
for i in $*
do
	dir=`dirname $i`
	svcname=`basename $i`
	first_char=`echo $svcname | cut -c1`
	if [ " $first_char" = " ." ] ; then
		svcname=`echo $svcname | cut -c2-`
		"$DESTDIR"$QmailBinPrefix/bin/svstat $dir/$svcname
		if [ -d $dir/$svcname/log ] ; then
			"$DESTDIR"$QmailBinPrefix/bin/svstat $dir/$svcname/log
		fi
	fi
done
}

refreshsvc()
{
if [ $# -lt 1 ] ; then
	echo "refreshsvc service_with_full_path" 1>&2
	return 1
fi
if [ " $1" = " all" ] ; then
	for j in `/bin/ls "$DESTDIR"$servicedir/*/variables/.options $servicedir/.svscan/variables/.options`
	do
		# remove last 19 char to get the directory+service_name
		i=`echo $j|sed 's/.\{19\}$//'`
		svcname=`basename $i`
		if [ ! -s $i/variables/.options -a ! -s $i/.options ] ; then
			echo "$i/variables/.options or $i/.options missing" 1>&2
			continue
		fi
		if [ -f $i/variables/.norefreshsvc ] ; then
			echo "Skip Refreshing service $svcname"
		else
			echo "Refreshing service $svcname command `/bin/cat $i/variables/.options`"
			sh $i/variables/.options
		fi
	done
	if [ -f "$DESTDIR"$sysconfdir/control/defaultqueue/.norefreshsvc ] ; then
		echo "Skip Refreshing config defaultqueue"
	else
		echo "Refreshing config defaultqueue command `/bin/cat "$DESTDIR"$sysconfdir/control/defaultqueue/.options`"
		sh "$DESTDIR"$sysconfdir/control/defaultqueue/.options
	fi
else
	for i in $*
	do
		if [ ! -d "$DESTDIR"$i ] ; then
			echo "$i: No such file or directory" 1>&2
			continue
		fi
		svcname=`basename $i`
		if [ ! -s "$DESTDIR"$i/variables/.options -a ! -s "$DESTDIR"$i/.options ] ; then
			echo "$i/variables/.options or $i/.options missing" 1>&2
			continue
		fi
		if [ -f "$DESTDIR"$i/variables/.norefreshsvc -o -f "$DESTDIR"$i/.norefreshsvc ] ; then
			echo "Skip Refreshing service/config $svcname"
			continue
		fi
		if [ -f "$DESTDIR"$i/variables/.options ] ; then
			echo "Refreshing service $svcname command `/bin/cat "$DESTDIR"$i/variables/.options`"
			sh "$DESTDIR"$i/variables/.options
		elif [ -f "$DESTDIR"$i/.options ] ; then
			echo "Refreshing config $svcname command `/bin/cat "$DESTDIR"$i/.options`"
			sh "$DESTDIR"$i/.options
		fi
	done
fi
}

norefreshsvc()
{
if [ $# -lt 2 ] ; then
	echo "norefreshsvc=0|1 service_with_full_path" 1>&2
	return 1
fi
svc_opt=$1
shift
if [ " $1" = " all" ] ; then
	for j in `/bin/ls "$DESTDIR"$servicedir/*/variables/.options $servicedir/.svscan/variables/.options`
	do
		# remove last 19 char to get the directory+service_name
		i=`echo $j|sed 's/.\{19\}$//'`
		if [ ! -s $i/variables/.options -a ! -s $i/.options ] ; then
			echo "$i/variables/.options or $i/.options missing" 1>&2
			continue
		fi
		if [ $svc_opt -eq 1 ] ; then
			echo "Enabling  auto refresh for $i"
			/bin/rm -f $i/variables/.norefreshsvc
		else
			echo "Disabling auto refresh for $i"
			touch $i/variables/.norefreshsvc
		fi
	done
	if [ $svc_opt -eq 1 ] ; then
		echo "Enabling  auto refresh for $sysconfdir/control/defaultqueue"
		/bin/rm -f "$DESTDIR"$sysconfdir/control/defaultqueue/.norefreshsvc
	else
		echo "Disabling auto refresh for $sysconfdir/control/defaultqueue"
		touch "$DESTDIR"$sysconfdir/control/defaultqueue/.norefreshsvc
	fi
else
	for i in $*
	do
		if [ ! -d "$DESTDIR"$i ] ; then
			echo "$i: No such file or directory" 1>&2
			continue
		fi
		if [ ! -s "$DESTDIR"$i/variables/.options -a ! -s "$DESTDIR"$i/.options ] ; then
			echo "$i/variables/.options or $i/.options missing" 1>&2
			continue
		fi
		if [ $svc_opt -eq 1 ] ; then
			echo "Enabling  auto refresh for $1"
			if [ -d $i/variables ] ; then
				/bin/rm -f "$DESTDIR"$i/variables/.norefreshsvc
			else
				/bin/rm -f "$DESTDIR"$i/.norefreshsvc
			fi
		else
			echo "Disabling auto refresh for $i"
			if [ -d "$DESTDIR"$i/variables ] ; then
				touch "$DESTDIR"$i/variables/.norefreshsvc
			else
				touch "$DESTDIR"$i/.norefreshsvc
			fi
		fi
	done
fi
}

enable_service()
{
	for i in $*
	do
		#
		# upstart/systemd
		#
		if [ -f /lib/systemd/system/$i.service -a -f /bin/systemctl ] ; then
			/bin/systemctl enable "$i".service
		elif [ -f /usr/lib/systemd/system/$i.service -a -f /bin/systemctl ] ; then
			/bin/systemctl enable "$i".service
		elif [ -f /Library/LaunchDaemons/org.indimail.svscan.plist ] ; then
			launchctl load -w /Library/LaunchDaemons/org.indimail.svscan.plist
		elif [ -f /sbin/initctl -a -f /etc/init/$i.override ] ; then
			/bin/rm -f /etc/init/$i.override
		elif [ -f /etc/event.d/$i.override ] ; then
			/bin/rm -f /etc/event.d/$i.override
		elif [ -f $QmailBinPrefix/etc/rc.d/svscan ] ; then
			service svscan enable
		fi
		#
		# traditional sys v
		#
		if [ -f /etc/init.d/$i ] ; then
			if [ -f /sbin/chkconfig ] ; then
				if [ -f /etc/debian_version ] ; then
					/sbin/chkconfig --add $i 2>/dev/null
				else
					/sbin/chkconfig --add $i
				fi
			elif [ -f /usr/sbin/update-rc.d ] ; then
				/usr/sbin/update-rc.d $i defaults
				/usr/sbin/update-rc.d $i enable
			fi
		fi
	done
}

disable_service()
{
	for i in $*
	do
		#
		# upstart/systemd
		#
		if [ -d /lib/systemd/system -a -f /bin/systemctl ] ; then
			/bin/systemctl stop "$i".service
			/bin/systemctl disable "$i".service
		elif [ -d /usr/lib/systemd/system -a -f /bin/systemctl ] ; then
			/bin/systemctl stop "$i".service
			/bin/systemctl disable "$i".service
		elif [ -f /Library/LaunchDaemons/org.indimail.svscan.plist ] ; then
			launchctl unload -w /Library/LaunchDaemons/org.indimail.svscan.plist 2>/dev/null
			launchctl remove /Library/LaunchDaemons/org.indimail.svscan.plist
		elif [ -f /sbin/initctl -a -d /etc/init ] ; then
			/sbin/initctl stop $i
			if [ -f /etc/init/$i.conf ] ; then
				echo "manual" > /etc/init/$i.override
			fi
		elif [ -d /etc/event.d ] ; then
			/sbin/initctl stop $i
			echo "manual" > /etc/event.d/$i.override
		elif [ -f $QmailBinPrefix/etc/rc.d/svscan ] ; then
			service svscan disable
		else
			/usr/sbin/service $i stop
		fi
		#
		# traditional sys v
		#
		if [ -f /etc/init.d/$i ] ; then
			/etc/init.d/$i stop
			if [ -f /sbin/chkconfig ] ; then
				if [ -f /etc/debian_version ] ; then
					/sbin/chkconfig --del $i 2>/dev/null
				else
					/sbin/chkconfig --del $i
				fi
			elif [ -f /usr/sbin/update-rc.d ] ; then
				/usr/sbin/update-rc.d -f $i disable
				/usr/sbin/update-rc.d -f $i remove
			fi
		fi
	done
}

macOSgroupadd()
{
	echo "groupadd $*"
	groupid=""
	while test $# -gt 1; do
		case "$1" in
		-g)
		groupid=$2
		for i in `dscl . -list /Groups PrimaryGroupID | awk '{print $2}'`
		do
			if [ $i -eq $groupid ] ; then
				echo "groupid $groupid not unique" 1>&2
				return 1
			fi
		done
		;;
		esac
    	shift
	done
	/usr/bin/dscl . -list /Groups/$1 > /dev/null 2>&1
	if [ $? -eq 0 ] ; then
		echo "group $1 exists"
		return 1
	fi
	if [ -n "$groupid" ] ; then
		echo "dscl . -create /Groups/$1 PrimaryGroupID $groupid"
		/usr/bin/dscl . -create /Groups/$1 PrimaryGroupID $groupid
	else
		echo "dseditgroup -o create $1"
		/usr/sbin/dseditgroup -o create $1
	fi
	return $?
}

macOSuseradd()
{
	echo "useradd $*"
	userid=""
	group=""
	members=""
	homedir=""
	shell=""
	password=""
	create_home=1
	while test $# -gt 1; do
		case "$1" in
		-M)
		create_home=0
		;;
		-u)
		userid=$2
		for i in `dscl . -list /Users UniqueID | awk '{print $2}'`
		do
			if [ $i -eq $userid ] ; then
				echo "userid $userid not unique" 1>&2
				return 1
			fi
		done
		;;
		-g)
		group=$2
		dscl . -read /Groups/$group PrimaryGroupID >/dev/null 2>&1
		if [ $? -ne 0 ] ; then
			echo "error with Group $group" 1>&2
			return 1
		fi
		groupid=`dscl . -read /Groups/$group PrimaryGroupID | grep -v "No such key"| awk '{print $2}'`
		;;
		-G)
		members=$2
		;;
		-d)
		homedir=$2
		;;
		-s)
		shell=$2
		;;
		-p)
		password=$2
		;;
		esac
    	shift
	done
	dscl . -list /Users/$1 > /dev/null 2>&1
	if [ $? -eq 0 ] ; then
		echo "user $1 exists"
		return 1
	fi
	echo "dscl . -create /Users/$1 UniqueID $userid"
	dscl . -create /Users/$1 UniqueID $userid
	echo "dscl . -create /Users/$1 home $homedir"
	dscl . -create /Users/$1 home $homedir
	echo "dscl . -create /Users/$1 PrimaryGroupID $groupid"
	dscl . -create /Users/$1 PrimaryGroupID $groupid
	echo "dscl . -create /Users/$1 UserShell $shell"
	dscl . -create /Users/$1 UserShell $shell
	echo "dscl . -create /Users/$1 RealName $1"
	dscl . -create /Users/$1 RealName $1
	if [ ! " $password" = " " ] ; then
		echo "dscl . -passwd /Users/$1 xxxxxxxx"
		dscl . -passwd /Users/$1 $password
	fi
	if [ ! " $members" = " " ] ; then
		IFS=,
		j=`echo $members`
		unset IFS
		for i in $j
		do
			echo "dscl . -append /Groups/$i GroupMembership $1"
			dscl . -append /Groups/$i GroupMembership $1 >/dev/null 2>&1
		done
	fi
	if [ $create_home -eq 1 ] ; then
		if [ ! -d $homedir ] ; then
			mkdir -p $homedir
			chmod 700 $homedir
			chown $homedir $userid:$groupid
		fi
	fi
}

create_users()
{
	if [ -f /etc/debian_version ] ; then
		opt1=""
	else
		opt1="-M"
	fi
	if [ -f /sbin/nologin ] ; then
		safe_shell=/sbin/nologin
	elif [ -f /usr/bin/false ] ; then
		safe_shell=/usr/bin/false
	elif [ -f /bin/false ] ; then
		safe_shell=/bin/false
	else
		safe_shell=/usr/bin/false
	fi
	case "$host" in
		*-*-freebsd*)
		pw=/usr/sbin/pw
		opt1="-m"
		opt2="-n"
		opt3="-h -"
		;;
		*)
		pw=""
		opt2=""
		opt3=""
		;;
	esac
	(
	case "$host" in
		*-*-darwin*)
		/usr/bin/dscl . -list Groups/mysql >/dev/null 2>&1
		if [ $? -ne 0 ]; then
			echo "creating group mysql"
			macOSgroupadd -g 74 mysql
		fi
		/usr/bin/dscl . -list Users/mysql >/dev/null 2>&1
		if [ $? -ne 0 ]; then
			echo "creating user mysql"
			macOSuseradd -M -u 74 -g mysql -d /var/empty -s $safe_shell mysql
		fi
		;;
		*)
  		grep "^mysql:" /etc/group >/dev/null
		if [ $? -ne 0 ]; then
			echo "creating group mysql"
			echo $pw groupadd $opt2 mysql
			$pw groupadd $opt2 mysql
			if [ $? -ne 0 ] ; then
				exit 1
			fi
		fi
  		grep "^mysql:" /etc/passwd >/dev/null
		if [ $? -ne 0 ]; then
			echo "creating user mysql"
			echo $pw useradd $opt1 -g mysql -d /var/lib/mysql -s $safe_shell $opt2 mysql
			$pw useradd $opt1 -g mysql -d /var/lib/mysql -s $safe_shell $opt2 mysql
			if [ $? -ne 0 ] ; then
				exit 1
			fi
		fi
		;;
	esac

	######### indimail #####################
	userid=555
	groupid=555
	case "$host" in
		*-*-darwin*)
		/usr/bin/dscl . -list Groups/indimail >/dev/null 2>&1
		if [ $? -ne 0 ]; then
			echo "creating group indimail"
			macOSgroupadd -g $groupid indimail
		fi
		/usr/bin/dscl . -list Users/indimail >/dev/null 2>&1
		if [ $? -ne 0 ]; then
			echo "creating user indimail"
			if [ -f /bin/bash ] ; then
				macOSuseradd -M -u $userid -g indimail -d $QmailHOME -s /bin/bash indimail
			else
				macOSuseradd -M -u $userid -g indimail -d $QmailHOME -s /bin/sh indimail
			fi
		fi
		;;
		*)
		grep "^indimail:" /etc/group >/dev/null
		if [ $? -ne 0 ]; then
			echo "creating group indimail"
			echo $pw groupadd -g $groupid $opt2 indimail
			$pw groupadd -g $groupid $opt2 indimail
			if [ $? -ne 0 ] ; then
				exit 1
			fi
		fi
  		grep "^indimail:" /etc/passwd >/dev/null
		if [ $? -ne 0 ]; then
			echo "creating user indimail"
			#SALT=`date +'%s'`
			#CRYPT_PASS=$(openssl passwd -6 -salt $SALT $ADMIN_PASS)
			# echo $ADMIN_PASS | $pw useradd $opt1 -g indimail -d $QmailHOME -s /bin/sh $opt2 indimail -h 0
			$pw useradd $opt1 -g indimail -d $QmailHOME -s /bin/sh $opt2 indimail
			if [ $? -ne 0 ] ; then
				exit 1
			fi
		fi
		;;
	esac

	for i in qmail nofiles qscand; do
		case "$host" in
		*-*-darwin*)
		groupid=`dscl . -list /Groups PrimaryGroupID | awk '{print $2}' | sort -n | tail -1`
		groupid=`expr $groupid + 1`
		/usr/bin/dscl . -list Groups/$i >/dev/null 2>&1
		if [ $? -ne 0 ]; then
			echo "creating group $i"
			macOSgroupadd -g $groupid $i
		fi
		;;
		*)
		grep "^$i:" /etc/group >/dev/null
		if [ $? -ne 0 ]; then
			echo "creating group $i"
			echo $pw groupadd $opt2 $i
			$pw groupadd $opt2 $i
			if [ $? -ne 0 ] ; then
				exit 1
			fi
		fi
		;;
		esac
	done
	case "$host" in
		*-*-darwin*)
		userid=`expr $userid + 1`
		/usr/bin/dscl . -list Users/alias >/dev/null 2>&1
		if [ $? -ne 0 ]; then
			echo "creating user alias"
			macOSuseradd -M -u $userid -g nofiles -d $QmailHOME/alias -s $safe_shell alias
		fi
		;;
		*)
  		grep "^alias:" /etc/passwd >/dev/null
		if [ $? -ne 0 ]; then
			echo "creating user alias"
			echo $pw useradd $opt1 -g nofiles -d $QmailHOME/alias -s $safe_shell $opt2 alias
			$pw useradd $opt1 -g nofiles -d $QmailHOME/alias -s $safe_shell $opt2 alias
			if [ $? -ne 0 ] ; then
				exit 1
			fi
		fi
		;;
	esac
	case "$host" in
		*-*-darwin*)
		userid=`dscl . -list /Users UniqueID | awk '{print $2}' | sort -n |tail -1`
		userid=`expr $userid + 1`
		/usr/bin/dscl . -list Users/qmaill >/dev/null 2>&1
		if [ $? -ne 0 ]; then
			echo "creating user qmaill"
			macOSuseradd -M -u $userid -g nofiles -d $LOGDIR -s $safe_shell qmaill
		fi
		;;
		*)
  		grep "^qmaill" /etc/passwd >/dev/null
		if [ $? -ne 0 ]; then
			echo "creating user qmaill"
			echo $pw useradd $opt1 -g nofiles -d $LOGDIR -s $safe_shell $opt2 qmaill
			$pw useradd $opt1 -g nofiles -d $LOGDIR -s $safe_shell $opt2 qmaill
			if [ $? -ne 0 ] ; then
				exit 1
			fi
		fi
		;;
	esac
	for i in qmaild qmailp; do
		case "$host" in
			*-*-darwin*)
			userid=`dscl . -list /Users UniqueID | awk '{print $2}' | sort -n |tail -1`
			userid=`expr $userid + 1`
			/usr/bin/dscl . -list Users/$i >/dev/null 2>&1
			if [ $? -ne 0 ]; then
				echo "creating user $i"
				macOSuseradd -M -u $userid -g nofiles -d $QmailHOME -s $safe_shell $i
			fi
			;;
			*)
  			grep "^$i:" /etc/passwd >/dev/null
			if [ $? -ne 0 ]; then
				echo "creating user $i"
				echo $pw useradd $opt1 -g nofiles -d $QmailHOME -s $safe_shell $opt2 $i
				$pw useradd $opt1 -g nofiles -d $QmailHOME -s $safe_shell $opt2 $i
				if [ $? -ne 0 ] ; then
					exit 1
				fi
			fi
			;;
		esac
	done
	for i in qmailq qmailr qmails; do
		case "$host" in
			*-*-darwin*)
			userid=`dscl . -list /Users UniqueID | awk '{print $2}' | sort -n |tail -1`
			userid=`expr $userid + 1`
			/usr/bin/dscl . -list Users/$i >/dev/null 2>&1
			if [ $? -ne 0 ]; then
				echo "creating user $i"
				macOSuseradd -M -u $userid -g qmail -d $QmailHOME -s $safe_shell $i
			fi
			;;
			*)
  			grep "^$i:" /etc/passwd >/dev/null
			if [ $? -ne 0 ]; then
				echo "creating user $i"
				echo $pw useradd $opt1 -g qmail -d $QmailHOME -s $safe_shell $opt2 $i
				$pw useradd $opt1 -g qmail -d $QmailHOME -s $safe_shell $opt2 $i
				if [ $? -ne 0 ] ; then
					exit 1
				fi
			fi
			;;
		esac
	done
	case "$host" in
		*-*-darwin*)
		userid=`dscl . -list /Users UniqueID | awk '{print $2}' | sort -n |tail -1`
		userid=`expr $userid + 1`
		/usr/bin/dscl . -list Users/qscand >/dev/null 2>&1
		if [ $? -ne 0 ]; then
			echo "creating user qscand"
			macOSuseradd -M -u $userid -g qscand -d $QmailHOME/qscanq -G qmail -s $safe_shell qscand
		fi
		;;
		*)
  		grep "^qscand" /etc/passwd >/dev/null
		if [ $? -ne 0 ]; then
			echo "creating user qscand"
			echo $pw useradd $opt1 -g qscand -d $QmailHOME/qscanq -G qmail -s $safe_shell $opt2 qscand 
			$pw useradd $opt1 -g qscand -d $QmailHOME/qscanq -G qmail -s $safe_shell $opt2 qscand 
			if [ $? -ne 0 ] ; then
				exit 1
			fi
		fi
		;;
	esac
	case "$host" in
		*-*-darwin*)
		loginwindow="/Library/Preferences/com.apple.loginwindow"
		defaults read $loginwindow HiddenUsersList | while read line
		do
			if [ " $line" = " (" -o " $line" = " )" ] ; then
				continue
			fi
			line=`echo $line | cut -d, -f1`
			case "$line" in
				indimail|alias|qmaild|qmaill|qmailp|qmailq|qmailr|qmails|qscand|mysql)
				echo $line
				;;
				*)
				defaults write $loginwindow HiddenUsersList -array-add $line
				;;
			esac
		done
		;;
	esac
	) 2>/tmp/svctool.user.$$
	if [ -s /tmp/svctool.user.$$ ] ; then
		/bin/cat /tmp/svctool.user.$$
		/bin/rm -f /tmp/svctool.user.$$
		return 1
	else
		/bin/rm -f /tmp/svctool.user.$$
		return 0
	fi
}

delUsers()
{
	case "$host" in
		*-*-freebsd*)
		pw=/usr/sbin/pw
		;;
		*)
		pw=""
		;;
	esac
	(
	case "$host" in
		*-*-darwin*)
		for i in indimail qmail nofiles qscand; do
			echo "deleting group $i"
			dscl . -delete /Groups/$i
		done
		for i in indimail alias qmaild qmaill qmailp qmailq qmailr qmails qscand; do
			echo "deleting user $i"
			dscl . -delete /Users/$i
		done
		#defaults delete /Library/Preferences/com.apple.loginwindow HiddenUsersList
		defaults write /Library/Preferences/com.apple.loginwindow HiddenUsersList mysql
		;;
		*)
		for i in indimail qmail nofiles qscand; do
			echo "deleting group $i"
			$pw groupdel $i
		done
		for i in indimail alias qmaild qmaill qmailp qmailq qmailr qmails qscand; do
			echo "deleting user $i"
			$pw userdel $i
		done
		;;
	esac
	) 2>/tmp/svctool.user.$$
	if [ -s /tmp/svctool.user.$$ ] ; then
		/bin/cat /tmp/svctool.user.$$
		/bin/rm -f /tmp/svctool.user.$$
		return 1
	else
		/bin/rm -f /tmp/svctool.user.$$
		return 0
	fi
}

create_qmail_config()
{
	default_qmail_control
	echo "Creating catch-all alias ($QmailHOME/alias/Maildir) for all system users"
	if [ -x "$DESTDIR"$QmailBinPrefix/bin/maildirmake ] ; then
		"$DESTDIR"$QmailBinPrefix/bin/maildirmake "$DESTDIR"$QmailHOME/alias/Maildir >/dev/null 2>&1
	else
		/bin/mkdir -p "$DESTDIR"$QmailHOME/alias/Maildir/tmp >/dev/null 2>&1
		/bin/mkdir -p "$DESTDIR"$QmailHOME/alias/Maildir/new >/dev/null 2>&1
		/bin/mkdir -p "$DESTDIR"$QmailHOME/alias/Maildir/cur >/dev/null 2>&1
	fi
	if [ $? -eq 0 ] ; then
		$chown -R alias:qmail "$DESTDIR"$QmailHOME/alias/Maildir
		/bin/chmod -R 775 "$DESTDIR"$QmailHOME/alias/Maildir
	fi
	/bin/rm -f "$DESTDIR"$QmailHOME/alias/.qmail-postmaster
	first_char=`echo $postmaster | cut -c1`
	if [ " $first_char" = " /" ] ; then
		if [ -x "$DESTDIR"$QmailBinPrefix/bin/maildirmake ] ; then
			"$DESTDIR"$QmailBinPrefix/bin/maildirmake "$DESTDIR"$postmaster >/dev/null 2>&1
		else
			/bin/mkdir -p "$DESTDIR"$postmaster/tmp >/dev/null 2>&1
			/bin/mkdir -p "$DESTDIR"$postmaster/new >/dev/null 2>&1
			/bin/mkdir -p "$DESTDIR"$postmaster/cur >/dev/null 2>&1
		fi
		if [ $? -eq 0 ] ; then
			$chown -R alias:qmail "$DESTDIR"$postmaster
			/bin/chmod -R 775 "$DESTDIR"$postmaster
		fi
	fi
	echo $postmaster > "$DESTDIR"$QmailHOME/alias/.qmail-postmaster
	$chown -R alias:qmail "$DESTDIR"$QmailHOME/alias/.qmail-postmaster
	cd "$DESTDIR"$QmailHOME/alias
	if [ $? -eq 0 ] ; then
		/bin/rm -f .qmail-root
		/bin/rm -f .qmail-mailer-daemon
		/bin/ln -s .qmail-postmaster .qmail-root
		/bin/ln -s .qmail-postmaster .qmail-mailer-daemon
	fi
}

create_startup()
{
	case "$host" in
		*-*-darwin*)
		if [ -n "$DESTDIR" ] ; then
			mkdir -p "$DESTDIR"/etc
		fi
		if [ ! -f /etc/synthetic.conf ] ; then
			echo "Creating /service in /etc/synthetic.conf"
			printf "service\t/private/var/run/svscan\n" > /etc/synthetic.conf
		else
			grep "^service" /etc/synthetic.conf >/dev/null
			if [ $? -ne 0 ] ; then
				echo "Creating /service in /etc/synthetic.conf"
				if [ -z "$DESTDIR" ] ; then
					printf "service\t/private/var/run/svscan\n" >> /etc/synthetic.conf
				else
				(
					printf "service\t/private/var/run/svscan\n"
					cat /etc/synthetic.conf
				) > "$DESTDIR"/etc/synthetic.conf
				fi
			else
				echo "/service exists in /etc/synthetic.conf"
			fi
		fi
		;;
		*)
		if [ ! -d /service -a ! -L /service ] ; then
			if [ -d /run ] ; then
				ln -s /run/svscan /service
			elif [ -d /var/run ] ; then
				ln -s /var/run/svscan /service
			elif [ "$servicedir" != "/service" ] ; then
				ln -s $servicedir /service
			fi
		fi
		;;
	esac
	if [ -x "$DESTDIR"$QmailBinPrefix/sbin/initsvc ] ; then
		"$DESTDIR"$QmailBinPrefix/sbin/initsvc -status
	else
		if [ -x /bin/systemctl -a -d /lib/systemd/system ] ; then
    		cmp -s "$DESTDIR"$shareddir/boot/systemd /lib/systemd/system/svscan.service >/dev/null 2>&1
    		if [ $? -ne 0 ] ; then
				echo "svscan startup enabled in systemd /lib/systemd/system/svscan.service"
				/bin/cp "$DESTDIR"$shareddir/boot/systemd /lib/systemd/system/svscan.service
			fi
		elif [ -x /bin/systemctl -a -d /usr/lib/systemd/system ] ; then
    		cmp -s "$DESTDIR"$shareddir/boot/systemd /usr/lib/systemd/system/svscan.service >/dev/null 2>&1
    		if [ $? -ne 0 ] ; then
				echo "svscan startup enabled in systemd /usr/lib/systemd/system/svscan.service"
				/bin/cp "$DESTDIR"$shareddir/boot/systemd /usr/lib/systemd/system/svscan.service
			fi
		elif [ -f /sbin/initctl -a -d /etc/init ] ; then
    		cmp -s "$DESTDIR"$shareddir/boot/upstart /etc/init/svscan.conf >/dev/null 2>&1
    		if [ $? -ne 0 ] ; then
				echo "svscan startup enabled in upstart /etc/init/svscan.conf"
				/bin/cp "$DESTDIR"$shareddir/boot/upstart /etc/init/svscan.conf
			fi
		elif [ -d /etc/event.d ] ; then
    		cmp -s "$DESTDIR"$shareddir/boot/upstart /etc/event.d/upstart >/dev/null 2>&1
    		if [ $? -ne 0 ] ; then
				echo "svscan startup enabled in upstart /etc/event.d/upstart"
				/bin/cp "$DESTDIR"$shareddir/boot/upstart /etc/event.d
			fi
		elif [ -d /etc/rc.d -a -f /etc/rc.subr ] ; then
			cmp -s "$DESTDIR"$shareddir/boot/svscan $QmailBinPrefix/etc/rc.d/svscan >/dev/null 2>&1
			if [ $? -ne 0 ] ; then
				echo "svscan startup enabled in rc $QmailBinPrefix/etc/rc.d/svscan"
				/bin/cp "$DESTDIR"$shareddir/boot/svscan $QmailBinPrefix/etc/rc.d/svscan
				/bin/chmod 755 $QmailBinPrefix/etc/rc.d/svscan
				service svscan enable
			fi
		elif [ -d /Library/LaunchDaemons ] ; then
			cmp -s "$DESTDIR"$shareddir/boot/svscan.plist /Library/LaunchDaemons/org.indimail.svscan.plist >/dev/null 2>&1
			if [ $? -ne 0 ] ; then
				echo "svscan startup enabled in upstart /Library/LaunchDaemons/org.indimail.svscan.plist"
				/bin/cp "$DESTDIR"$shareddir/boot/svscan.plist /Library/LaunchDaemons/org.indimail.svscan.plist
			fi
		fi
	fi
	if [ -d /etc/init.d ] ; then
		cmp -s "$DESTDIR"$QmailBinPrefix/bin/qmailctl /etc/init.d/svscan >/dev/null 2>&1
		if [ $? -ne 0 ] ; then
			/bin/cp "$DESTDIR"$QmailBinPrefix/bin/qmailctl /etc/init.d/svscan
		fi
	fi
	if [ -f /etc/init.d/svscan ] ; then
		if [ -f /sbin/chkconfig ] ; then
			if [ -f /etc/debian_version ] ; then
				/sbin/chkconfig --add svscan 2>/dev/null
			else
				/sbin/chkconfig --add svscan
			fi
		elif [ -f /usr/sbin/update-rc.d ] ; then
			/usr/sbin/update-rc.d svscan start 14 2 3 4 5 . stop 91 0 1 6 .
		fi
	fi
	if [ ! -f $QmailBinPrefix/bin/qmail-inject ] ; then # daemontools
		return 0
	fi
}

remove_startup()
{
	echo "Giving IndiMail exactly 5 seconds to exit nicely" 1>&2
	if [ -f "$DESTDIR"$QmailBinPrefix/sbin/initsvc ] ; then
		"$DESTDIR"$QmailBinPrefix/sbin/initsvc -off
	fi
	if [ -f /lib/systemd/system/svscan.service -a -x /bin/systemctl ] ; then
		/bin/systemctl stop svscan
		/bin/systemctl disable svscan.service
		/bin/rm -f /lib/systemd/system/svscan.service
	elif [ -f /usr/lib/systemd/system/svscan.service -a -x /bin/systemctl ] ; then
		/bin/systemctl stop svscan
		/bin/systemctl disable svscan.service
		/bin/rm -f /usr/lib/systemd/system/svscan
	elif [ -f /etc/init/svscan.conf ] ; then
		/sbin/initctl emit qmailstop > /dev/null
		/bin/rm -f /etc/event.d/svscan
	elif [ -f /etc/event.d/svscan ] ; then
		/sbin/initctl emit qmailstop > /dev/null
		/bin/rm -f /etc/event.d/svscan
	elif [ -d /etc/rc.d -a -f /etc/rc.subr ] ; then
		service svscan stop
		service svscan disable
		service svscan delete
		/bin/rm -f $QmailBinPrefix/etc/rc.d/svscan
	fi
	if [ -f ${shareddir}/boot/rpm.init ] ; then
		echo "Running Custom Un-Installation Script for preun" 1>&2
		/bin/sh ${shareddir}/boot/rpm.init preun
	fi
	if [ -f /etc/init.d/svscan ] ; then
		if [ -f /sbin/chkconfig ] ; then
			if [ -f /etc/debian_version ] ; then
				/sbin/chkconfig --del svscan 2>/dev/null
			else
				/sbin/chkconfig --del svscan
			fi
		elif [ -f /usr/sbin/update-rc.d ] ; then
			/usr/sbin/update-rc.d -f svscan remove
		fi
		/bin/rm -f /etc/init.d/svscan
	fi
	if [ ! -f $QmailBinPrefix/bin/qmail-inject ] ; then # daemontools. This should be called before removing package
		return 0
	fi
}

add_alternatives()
{
	if [ -x /usr/sbin/alternatives -o -x /usr/sbin/update-alternatives -o -x /usr/bin/update-alternatives ] ; then
		for i in /usr/lib/sendmail /usr/sbin/sendmail; do
			if [ -f $i -a ! -L $i ]; then
				echo "! $i is a file, should be a link" 1>&2
				/bin/mv $i $i.old
			fi
		done
		if [ -f /etc/pam.d/smtp -a ! -L /etc/pam.d/smtp ] ; then
			echo "! /etc/pam.d/smtp is a file, should be a link" 1>&2
			/bin/mv /etc/pam.d/smtp /etc/pam.d/smtp.old
		fi
		if [ -x /usr/sbin/alternatives ] ; then
			alternatives_cmd=/usr/sbin/alternatives
		elif [ -x /usr/sbin/update-alternatives ] ; then
			alternatives_cmd=/usr/sbin/update-alternatives
		else
			alternatives_cmd=/usr/bin/update-alternatives
		fi
		if [ -f /etc/os-release ] ; then
			openSUSE=$(grep openSUSE /etc/os-release 2>/dev/null)
		else
			openSUSE=""
		fi
		if [ -z "$openSUSE" -a ! -f /etc/SuSE-release -a ! -f /etc/debian_version ] ; then
			init_script="--initscript svscan"
		else
			init_script=""
		fi
		cmd="$alternatives_cmd"
		cmd="$cmd --install /usr/sbin/sendmail  mta            $QmailBinPrefix/bin/sendmail 120"
		cmd="$cmd --slave   /usr/bin/mailq      mta-mailq      $QmailBinPrefix/bin/qmail-qread"
		cmd="$cmd --slave   /usr/bin/rmail      mta-rmail      $QmailBinPrefix/bin/irmail"
		cmd="$cmd --slave   /usr/bin/newaliases mta-newaliases $QmailBinPrefix/bin/inewaliases"
		cmd="$cmd --slave   /usr/lib/sendmail   mta-sendmail   $QmailBinPrefix/bin/sendmail"
		if [ -f $mandir/man1/inewaliases.1.gz ] ; then
			cmd="$cmd --slave $mandir/man1/newaliases.1.gz mta-newaliasesman $mandir/man1/inewaliases.1.gz"
		fi
		if [ -f $mandir/man8/qmail-qread.8.gz ] ; then
			cmd="$cmd --slave $mandir/man1/mailq.1.gz mta-mailqman $mandir/man8/qmail-qread.8.gz"
		fi
		if [ -f $mandir/man8/isendmail.8.gz ] ; then
			cmd="$cmd --slave $mandir/man8/sendmail.8.gz mta-sendmailman $mandir/man8/isendmail.8.gz"
		fi
		if [ -f $mandir/man8/irmail.8.gz ] ; then
			cmd="$cmd --slave $mandir/man8/rmail.8.gz mta-rmailman $mandir/man8/irmail.8.gz"
		fi
		if [ -f /etc/pam.d/pam-multi ] ; then
			cmd="$cmd --slave /etc/pam.d/smtp mta-pam /etc/pam.d/pam-multi"
		fi
		if [ -n "$init_script" ] ; then
			cmd="$cmd $init_script"
		fi
		eval $cmd
	elif [ -f /usr/sbin/mailwrapper ] ; then
		if [ ! -f /etc/mail/mailer.conf.indimail-mta ] ; then
			/bin/mv /etc/mail/mailer.conf /etc/mail/mailer.conf.indimail-mta
		fi
		(
		echo "#"
		echo "# Execute the "real" sendmail program, named /usr/local/bin/sendmail"
		echo "#"
		echo "sendmail   $QmailBinPrefix/bin/sendmail"
		echo "mailq      $QmailBinPrefix/bin/qmail-qread"
		echo "newaliases $QmailBinPrefix/bin/inewaliases"
		echo "hoststat   $QmailBinPrefix/sbin/qmail-tcpto"
		echo "purgestat  $QmailBinPrefix/sbin/qmail-tcpok"
		) > /etc/mail/mailer.conf
	else
		for i in /usr/lib/sendmail /usr/sbin/sendmail; do
			if [ -f $i -a ! -L $i ]; then
				echo "! $i is a file, should be a link. Fixing..."
				/bin/mv $i $i.old
				/bin/ln -s $QmailBinPrefix/bin/sendmail $i
			elif [ -L $i ];then
				/bin/mv $i $i.old
				/bin/ln -s $QmailBinPrefix/bin/sendmail $i
			elif [ ! -f $i ];then
				echo "! $i is missing. Fixing..."
				/bin/ln -s $QmailBinPrefix/bin/sendmail $i
			fi
		done
		if [ -f /etc/pam.d/smtp -a ! -L /etc/pam.d/smtp ] ; then
			echo "! /etc/pam.d/smtp is a file, should be a link. Fixing..."
			/bin/mv /etc/pam.d/smtp /etc/pam.d/smtp.old
			/bin/ln -s /etc/pam.d/pam.multi /etc/pam.d/smtp
		fi
	fi
}

remove_alternatives()
{
	if [ -x /usr/sbin/alternatives ] ; then
		/usr/sbin/alternatives --remove mta $QmailBinPrefix/bin/sendmail
		/usr/sbin/alternatives --auto mta
	elif [ -x /usr/sbin/update-alternatives ] ; then
		/usr/sbin/update-alternatives --remove mta $QmailBinPrefix/bin/sendmail
		/usr/sbin/update-alternatives --auto mta
	elif [ -x /usr/sbin/mailwrapper ] ; then
		if [  -f /etc/mail/mailer.conf.indimail-mta ] ; then
			/bin/mv /etc/mail/mailer.conf.indimail-mta /etc/mail/mailer.conf
		else
			echo "unable to restore original mailer.conf" 1>&2
		fi
	else
		for i in /usr/lib/sendmail /usr/sbin/sendmail /etc/pam.d/smtp; do
			if [ -f $i.old -o -L $i.old ]; then
				echo "restoring $i"
				/bin/rm -f $i
				/bin/mv $i.old $i
			fi
		done
	fi
}

selinux_module()
{
config_name=$1
policy_file=$2
# selinux
status=0
	if [ ! -x /usr/sbin/selinuxenabled ] ; then
		exit 1
	fi
	/usr/sbin/selinuxenabled
	if [ $? -ne 0 ] ; then
		exit 1
	fi
	if [ -x /usr/bin/checkmodule -a -x /usr/bin/semodule_package -a -f "$policy_file".te ] ; then
		echo "Creating selinux module `date`"
		/usr/bin/checkmodule -M -m -o "$policy_file".mod   "$policy_file".te
		if [ $status -eq 0 ] ; then
			status=$?
		fi
		echo "/usr/bin/semodule_package -o "$policy_file".pp -m "$policy_file".mod -f "$policy_file".fc `date`"
		/usr/bin/semodule_package -o "$policy_file".pp -m "$policy_file".mod -f "$policy_file".fc
		if [ $status -eq 0 ] ; then
			status=$?
		fi
		if [ -x /usr/sbin/semodule -a $status -eq 0 ] ; then
			echo "enabling selinux module "$policy_file".pp `date`"
			/usr/sbin/semodule -i "$policy_file".pp 
			if [ $status -eq 0 ] ; then
				status=$?
			fi
		fi
	fi

	if [ " $config_name" = " qselinux" ] ; then
		echo "selinux settings for indimail-mta `date`"
		if [ -x /usr/sbin/setsebool ] ; then
			echo "setting clamd_use_jit `date`"
			/usr/sbin/setsebool -P clamd_use_jit on
			if [ $status -eq 0 ] ; then
				status=$?
			fi
			echo "setting antivirus_can_scan_system `date`"
			/usr/sbin/setsebool -P antivirus_can_scan_system on
			if [ $status -eq 0 ] ; then
				status=$?
			fi
		fi
		if [ -x /usr/bin/chcon ] ; then
			echo "changing security context (antivirus_db_t) for $indimaildir/clamd `date`"
			/usr/bin/chcon -R -u system_u -r object_r -t antivirus_db_t  $indimaildir/clamd
			if [ $status -eq 0 ] ; then
				status=$?
			fi
		fi
		if [ " $QmailBinPrefix" = " $indimaildir" ] ; then
			for i in sendmail envdir qmail-inject
			do
				if [ -x /usr/bin/chcon ] ; then
					echo "changing security context for $QmailBinPrefix/bin/$i `date`"
					/usr/bin/chcon -t bin_t $QmailBinPrefix/bin/$i
					if [ $status -eq 0 ] ; then
						status=$?
					fi
				fi
				if [ -x /usr/sbin/semanage ] ; then
					echo "Manage file context mapping (bin_t) definitions for $QmailBinPrefix/bin/$i `date`"
					/usr/sbin/semanage fcontext -a -t bin_t $QmailBinPrefix/bin/$i
					if [ $status -eq 0 ] ; then
						status=$?
					fi
				fi
				if [ -x /usr/sbin/restorecon ] ; then
					echo "/usr/sbin/restorecon -Rv $QmailBinPrefix/$i `date`"
					/usr/sbin/restorecon -Rv $QmailBinPrefix/$i
					if [ $status -eq 0 ] ; then
						status=$?
					fi
				fi
			done
		fi
	fi

	if [ " $config_name" = " iselinux" ] ; then
		echo "selinux settings for indimail `date`"
		if [ -x /usr/sbin/setsebool ] ; then
			echo "setsebool -P httpd_can_network_connect 1 `date`"
			setsebool -P httpd_can_network_connect 1
		fi
		if [ -x /usr/bin/chcon ] ; then
			echo "changing security context (mysqld_db_t) for $indimaildir/mysqldb/data `date`"
			/usr/bin/chcon -R -u system_u -r object_r -t mysqld_db_t  $indimaildir/mysqldb/data
			if [ $status -eq 0 ] ; then
				status=$?
			fi
			echo "changing security context (mysqld_log_t) for $indimaildir/mysqldb/logs `date`"
			/usr/bin/chcon -R -u system_u -r object_r -t mysqld_log_t $indimaildir/mysqldb/logs
			if [ $status -eq 0 ] ; then
				status=$?
			fi
			echo "changing security context (mysqld_etc_t) for $sysconfdir/indimail.cnf `date`"
			/usr/bin/chcon -R -u system_u -r object_r -t mysqld_etc_t $sysconfdir/indimail.cnf
			if [ $status -eq 0 ] ; then
				status=$?
			fi
			if [ -f /tmp/mysql.sock ] ; then
				echo "changing security context (mysqld_var_run_t) for /tmp/mysql.sock `date`"
				/usr/bin/chcon -R -u system_u -r object_r -t mysqld_var_run_t /tmp/mysql.sock
				if [ $status -eq 0 ] ; then
					status=$?
				fi
			fi
		fi
		if [ -x /usr/sbin/restorecon ] ; then
			for i in $indimaildir/mysqldb/data $indimaildir/mysqldb/logs $sysconfdir/indimail.cnf \
				$indimaildir/clamd $sysconfdir $servicedir
			do
				echo "/usr/sbin/restorecon -Rv $i `date`"
				/usr/sbin/restorecon -Rv $i
				if [ $status -eq 0 ] ; then
					status=$?
				fi
			done
		fi
	fi
	if [ -x /usr/bin/chcon ] ; then
		echo "changing security context (etc_t) for $sysconfdir `date`"
		/usr/bin/chcon -R -u system_u -r object_r -t etc_t $sysconfdir
		if [ $status -eq 0 ] ; then
			status=$?
		fi
		echo "changing security context (svc_svc_t) for $servicedir `date`"
		/usr/bin/chcon -R -u system_u -r object_r -t svc_svc_t $servicedir
		if [ $status -eq 0 ] ; then
			status=$?
		fi
	fi
	exit $status
}

create_clamd_conf()
{
echo "# Uncomment this option to enable logging."
echo "# LogFile must be writable for the user running daemon."
echo "# A full path is required."
echo "# Default: disabled"
echo "#LogFile /var/log/clamd.scan"
echo ""
echo "# By default the log file is locked for writing - the lock protects against"
echo "# running clamd multiple times (if want to run another clamd, please"
echo "# copy the configuration file, change the LogFile variable, and run"
echo "# the daemon with --config-file option)."
echo "# This option disables log file locking."
echo "# Default: no"
echo "#LogFileUnlock yes"
echo ""
echo "# Maximum size of the log file."
echo "# Value of 0 disables the limit."
echo "# You may use 'M' or 'm' for megabytes (1M = 1m = 1048576 bytes)"
echo "# and 'K' or 'k' for kilobytes (1K = 1k = 1024 bytes). To specify the size"
echo "# in bytes just don't use modifiers. If LogFileMaxSize is enabled, log"
echo "# rotation (the LogRotate option) will always be enabled."
echo "# Default: 1M"
echo "#LogFileMaxSize 2M"
echo ""
echo "# Log time with each message."
echo "# Default: no"
echo "#LogTime yes"
echo ""
echo "# Also log clean files. Useful in debugging but drastically increases the"
echo "# log size."
echo "# Default: no"
echo "LogClean yes"
echo ""
echo "# Use system logger (can work together with LogFile)."
echo "# Default: no"
echo "#LogSyslog yes"
echo ""
echo "# Specify the type of syslog messages - please refer to 'man syslog'"
echo "# for facility names."
echo "# Default: LOG_LOCAL6"
echo "#LogFacility LOG_MAIL"
echo ""
echo "# Enable verbose logging."
echo "# Default: no"
echo "#LogVerbose yes"
echo ""
echo "# Enable log rotation. Always enabled when LogFileMaxSize is enabled."
echo "# Default: no"
echo "#LogRotate yes"
echo ""
echo "# Enable Prelude output."
echo "# Default: no"
echo "#PreludeEnable yes"
echo "#"
echo "# Set the name of the analyzer used by prelude-admin."
echo "# Default: ClamAV"
echo "#PreludeAnalyzerName ClamAV"
echo ""
echo "# Log additional information about the infected file, such as its"
echo "# size and hash, together with the virus name."
echo "ExtendedDetectionInfo yes"
echo ""
echo "# This option allows you to save a process identifier of the listening"
echo "# daemon (main thread)."
echo "# Default: disabled"
echo "#PidFile /var/run/clamd.scan/clamd.pid"
echo ""
echo "# Optional path to the global temporary directory."
echo "# Default: system specific (usually /tmp or /var/tmp)."
echo "#TemporaryDirectory /var/tmp"
echo ""
echo "# Path to the database directory."
echo "# Default: hardcoded (depends on installation options)"
echo "DatabaseDirectory $indimaildir/clamd"
echo ""
echo "# Only load the official signatures published by the ClamAV project."
echo "# Default: no"
echo "#OfficialDatabaseOnly no"
echo ""
echo "# The daemon can work in local mode, network mode or both. "
echo "# Due to security reasons we recommend the local mode."
echo ""
echo "# Path to a local socket file the daemon will listen on."
echo "# Default: disabled (must be specified by a user)"
echo "LocalSocket /var/run/clamd.scan/clamd.sock"
echo ""
echo "# Sets the group ownership on the unix socket."
echo "# Default: disabled (the primary group of the user running clamd)"
echo "LocalSocketGroup qmail"
echo ""
echo "# Sets the permissions on the unix socket to the specified mode."
echo "# Default: disabled (socket is world accessible)"
echo "LocalSocketMode 660"
echo ""
echo "# Remove stale socket after unclean shutdown."
echo "# Default: yes"
echo "FixStaleSocket yes"
echo ""
echo "# TCP port address."
echo "# Default: no"
echo "#TCPSocket 3310"
echo ""
echo "# TCP address."
echo "# By default we bind to INADDR_ANY, probably not wise."
echo "# Enable the following to provide some degree of protection"
echo "# from the outside world. This option can be specified multiple"
echo "# times if you want to listen on multiple IPs. IPv6 is now supported."
echo "# Default: no"
echo "#TCPAddr 127.0.0.1"
echo ""
echo "# Maximum length the queue of pending connections may grow to."
echo "# Default: 200"
echo "#MaxConnectionQueueLength 30"
echo ""
echo "# Clamd uses FTP-like protocol to receive data from remote clients."
echo "# If you are using clamav-milter to balance load between remote clamd daemons"
echo "# on firewall servers you may need to tune the options below."
echo ""
echo "# Close the connection when the data size limit is exceeded."
echo "# The value should match your MTA's limit for a maximum attachment size."
echo "# Default: 25M"
echo "#StreamMaxLength 10M"
echo ""
echo "# Limit port range."
echo "# Default: 1024"
echo "#StreamMinPort 30000"
echo "# Default: 2048"
echo "#StreamMaxPort 32000"
echo ""
echo "# Maximum number of threads running at the same time."
echo "# Default: 10"
echo "#MaxThreads 20"
echo ""
echo "# Waiting for data from a client socket will timeout after this time (seconds)."
echo "# Default: 120"
echo "#ReadTimeout 300"
echo ""
echo "# This option specifies the time (in seconds) after which clamd should"
echo "# timeout if a client doesn't provide any initial command after connecting."
echo "# Default: 5"
echo "#CommandReadTimeout 5"
echo ""
echo "# This option specifies how long to wait (in milliseconds) if the send buffer"
echo "# is full."
echo "# Keep this value low to prevent clamd hanging"
echo "#"
echo "# Default: 500"
echo "#SendBufTimeout 200"
echo ""
echo "# Maximum number of queued items (including those being processed by"
echo "# MaxThreads threads)"
echo "# It is recommended to have this value at least twice MaxThreads if possible."
echo "# WARNING: you shouldn't increase this too much to avoid running out  of file"
echo "# descriptors,"
echo "# the following condition should hold:"
echo "# MaxThreads*MaxRecursion + (MaxQueue - MaxThreads) + 6< RLIMIT_NOFILE (usual"
echo "# max is 1024)"
echo "#"
echo "# Default: 100"
echo "#MaxQueue 200"
echo ""
echo "# Waiting for a new job will timeout after this time (seconds)."
echo "# Default: 30"
echo "#IdleTimeout 60"
echo ""
echo "# Don't scan files and directories matching regex"
echo "# This directive can be used multiple times"
echo "# Default: scan all"
echo "#ExcludePath ^/proc/"
echo "#ExcludePath ^/sys/"
echo ""
echo "# Maximum depth directories are scanned at."
echo "# Default: 15"
echo "#MaxDirectoryRecursion 20"
echo ""
echo "# Follow directory symlinks."
echo "# Default: no"
echo "#FollowDirectorySymlinks yes"
echo ""
echo "# Follow regular file symlinks."
echo "# Default: no"
echo "#FollowFileSymlinks yes"
echo ""
echo "# Scan files and directories on other filesystems."
echo "# Default: yes"
echo "#CrossFilesystems yes"
echo ""
echo "# Perform a database check."
echo "# Default: 600 (10 min)"
echo "#SelfCheck 600"
echo ""
echo "# Execute a command when virus is found. In the command string %v will"
echo "# be replaced with the virus name."
echo "# Default: no"
echo "#VirusEvent /usr/local/bin/send_sms 123456789 \"VIRUS ALERT: %v\""
echo ""
echo "# Run as another user (clamd must be started by root for this option to work)"
echo "# Default: don't drop privileges"
echo "User qscand"
echo ""
echo "# Stop daemon when libclamav reports out of memory condition."
echo "ExitOnOOM yes"
echo ""
echo "# Don't fork into background."
echo "# Default: no"
echo "Foreground yes"
echo ""
echo "# Enable debug messages in libclamav."
echo "# Default: no"
echo "#Debug yes"
echo ""
echo "# Do not remove temporary files (for debug purposes)."
echo "# Default: no"
echo "#LeaveTemporaryFiles yes"
echo ""
echo "# Permit use of the ALLMATCHSCAN command. If set to no, clamd will reject"
echo "# any ALLMATCHSCAN command as invalid."
echo "# Default: yes"
echo "#AllowAllMatchScan no"
echo ""
echo "# Detect Possibly Unwanted Applications."
echo "# Default: no"
echo "#DetectPUA yes"
echo ""
echo "# Exclude a specific PUA category. This directive can be used multiple times."
echo "# See https://github.com/vrtadmin/clamav-faq/blob/master/faq/faq-pua.md for "
echo "# the complete list of PUA categories."
echo "# Default: Load all categories (if DetectPUA is activated)"
echo "#ExcludePUA NetTool"
echo "#ExcludePUA PWTool"
echo ""
echo "# Only include a specific PUA category. This directive can be used multiple"
echo "# times."
echo "# Default: Load all categories (if DetectPUA is activated)"
echo "#IncludePUA Spy"
echo "#IncludePUA Scanner"
echo "#IncludePUA RAT"
echo ""
echo "# In some cases (eg. complex malware, exploits in graphic files, and others),"
echo "# ClamAV uses special algorithms to provide accurate detection. This option"
echo "# controls the algorithmic detection."
echo "# Default: yes"
echo "#AlgorithmicDetection yes"
echo ""
echo "# This option causes memory or nested map scans to dump the content to disk."
echo "# If you turn on this option, more data is written to disk and is available"
echo "# when the LeaveTemporaryFiles option is enabled."
echo "#ForceToDisk yes"
echo ""
echo "# This option allows you to disable the caching feature of the engine. By"
echo "# default, the engine will store an MD5 in a cache of any files that are"
echo "# not flagged as virus or that hit limits checks. Disabling the cache will"
echo "# have a negative performance impact on large scans."
echo "# Default: no"
echo "#DisableCache yes"
echo ""
echo "##"
echo "## Executable files"
echo "##"
echo ""
echo "# PE stands for Portable Executable - it's an executable file format used"
echo "# in all 32 and 64-bit versions of Windows operating systems. This option"
echo "# allows ClamAV to perform a deeper analysis of executable files and it's also"
echo "# required for decompression of popular executable packers such as UPX, FSG,"
echo "# and Petite. If you turn off this option, the original files will still be"
echo "# scanned, but without additional processing."
echo "# Default: yes"
echo "#ScanPE yes"
echo ""
echo "# Certain PE files contain an authenticode signature. By default, we check"
echo "# the signature chain in the PE file against a database of trusted and"
echo "# revoked certificates if the file being scanned is marked as a virus."
echo "# If any certificate in the chain validates against any trusted root, but"
echo "# does not match any revoked certificate, the file is marked as whitelisted."
echo "# If the file does match a revoked certificate, the file is marked as virus."
echo "# The following setting completely turns off authenticode verification."
echo "# Default: no"
echo "#DisableCertCheck yes"
echo ""
echo "# Executable and Linking Format is a standard format for UN*X executables."
echo "# This option allows you to control the scanning of ELF files."
echo "# If you turn off this option, the original files will still be scanned, but"
echo "# without additional processing."
echo "# Default: yes"
echo "#ScanELF yes"
echo ""
echo "# With this option clamav will try to detect broken executables (both PE and"
echo "# ELF) and mark them as Broken.Executable."
echo "# Default: no"
echo "DetectBrokenExecutables yes"
echo ""
echo ""
echo "##"
echo "## Documents"
echo "##"
echo ""
echo "# This option enables scanning of OLE2 files, such as Microsoft Office"
echo "# documents and .msi files."
echo "# If you turn off this option, the original files will still be scanned, but"
echo "# without additional processing."
echo "# Default: yes"
echo "#ScanOLE2 yes"
echo ""
echo "# With this option enabled OLE2 files with VBA macros, which were not"
echo "# detected by signatures will be marked as \"Heuristics.OLE2.ContainsMacros\"."
echo "# Default: no"
echo "#OLE2BlockMacros no"
echo ""
echo "# This option enables scanning within PDF files."
echo "# If you turn off this option, the original files will still be scanned, but"
echo "# without decoding and additional processing."
echo "# Default: yes"
echo "ScanPDF yes"
echo ""
echo "# This option enables scanning within SWF files."
echo "# If you turn off this option, the original files will still be scanned, but"
echo "# without decoding and additional processing."
echo "# Default: yes"
echo "#ScanSWF yes"
echo ""
echo "# This option enables scanning xml-based document files supported by libclamav."
echo "# If you turn off this option, the original files will still be scanned, but"
echo "# without additional processing."
echo "# Default: yes"
echo "#ScanXMLDOCS yes"
echo ""
echo "# This option enables scanning of HWP3 files."
echo "# If you turn off this option, the original files will still be scanned, but"
echo "# without additional processing."
echo "# Default: yes"
echo "#ScanHWP3 yes"
echo ""
echo ""
echo "##"
echo "## Mail files"
echo "##"
echo ""
echo "# Enable internal e-mail scanner."
echo "# If you turn off this option, the original files will still be scanned, but"
echo "# without parsing individual messages/attachments."
echo "# Default: yes"
echo "#ScanMail yes"
echo ""
echo "# Scan RFC1341 messages split over many emails."
echo "# You will need to periodically clean up \$TemporaryDirectory/clamav-partial"
echo "# directory."
echo "# WARNING: This option may open your system to a DoS attack."
echo "#	   Never use it on loaded servers."
echo "# Default: no"
echo "#ScanPartialMessages yes"
echo ""
echo "# With this option enabled ClamAV will try to detect phishing attempts by using"
echo "# signatures."
echo "# Default: yes"
echo "#PhishingSignatures yes"
echo ""
echo "# Scan URLs found in mails for phishing attempts using heuristics."
echo "# Default: yes"
echo "#PhishingScanURLs yes"
echo ""
echo "# Always block SSL mismatches in URLs, even if the URL isn't in the database."
echo "# This can lead to false positives."
echo "#"
echo "# Default: no"
echo "#PhishingAlwaysBlockSSLMismatch no"
echo ""
echo "# Always block cloaked URLs, even if URL isn't in database."
echo "# This can lead to false positives."
echo "#"
echo "# Default: no"
echo "#PhishingAlwaysBlockCloak no"
echo ""
echo "# Detect partition intersections in raw disk images using heuristics."
echo "# Default: no"
echo "#PartitionIntersection no"
echo ""
echo "# Allow heuristic match to take precedence."
echo "# When enabled, if a heuristic scan (such as phishingScan) detects"
echo "# a possible virus/phish it will stop scan immediately. Recommended, saves CPU"
echo "# scan-time."
echo "# When disabled, virus/phish detected by heuristic scans will be reported"
echo "# only at the end of a scan. If an archive contains both a heuristically"
echo "# detected virus/phish, and a real malware, the real malware will be reported."
echo "#"
echo "# Keep this disabled if you intend to handle \"*.Heuristics.*\" viruses "
echo "# differently from \"real\" malware."
echo "# If a non-heuristically-detected virus (signature-based) is found first, "
echo "# the scan is interrupted immediately, regardless of this config option."
echo "#"
echo "# Default: no"
echo "#HeuristicScanPrecedence yes"
echo ""
echo ""
echo "##"
echo "## Data Loss Prevention (DLP)"
echo "##"
echo ""
echo "# Enable the DLP module"
echo "# Default: No"
echo "#StructuredDataDetection yes"
echo ""
echo "# This option sets the lowest number of Credit Card numbers found in a file"
echo "# to generate a detect."
echo "# Default: 3"
echo "#StructuredMinCreditCardCount 5"
echo ""
echo "# This option sets the lowest number of Social Security Numbers found"
echo "# in a file to generate a detect."
echo "# Default: 3"
echo "#StructuredMinSSNCount 5"
echo ""
echo "# With this option enabled the DLP module will search for valid"
echo "# SSNs formatted as xxx-yy-zzzz"
echo "# Default: yes"
echo "#StructuredSSNFormatNormal yes"
echo ""
echo "# With this option enabled the DLP module will search for valid"
echo "# SSNs formatted as xxxyyzzzz"
echo "# Default: no"
echo "#StructuredSSNFormatStripped yes"
echo ""
echo ""
echo "##"
echo "## HTML"
echo "##"
echo ""
echo "# Perform HTML normalisation and decryption of MS Script Encoder code."
echo "# Default: yes"
echo "# If you turn off this option, the original files will still be scanned, but"
echo "# without additional processing."
echo "#ScanHTML yes"
echo ""
echo ""
echo "##"
echo "## Archives"
echo "##"
echo ""
echo "# ClamAV can scan within archives and compressed files."
echo "# If you turn off this option, the original files will still be scanned, but"
echo "# without unpacking and additional processing."
echo "# Default: yes"
echo "#ScanArchive yes"
echo ""
echo "# Mark encrypted archives as viruses (Encrypted.Zip, Encrypted.RAR)."
echo "# Default: no"
echo "#ArchiveBlockEncrypted no"
echo ""
echo ""
echo "##"
echo "## Limits"
echo "##"
echo ""
echo "# The options below protect your system against Denial of Service attacks"
echo "# using archive bombs."
echo ""
echo "# This option sets the maximum amount of data to be scanned for each input"
echo "# file."
echo "# Archives and other containers are recursively extracted and scanned up to"
echo "# this value."
echo "# Value of 0 disables the limit"
echo "# Note: disabling this limit or setting it too high may result in severe damage"
echo "# to the system."
echo "# Default: 100M"
echo "#MaxScanSize 150M"
echo ""
echo "# Files larger than this limit won't be scanned. Affects the input file itself"
echo "# as well as files contained inside it (when the input file is an archive, a"
echo "# document or some other kind of container)."
echo "# Value of 0 disables the limit."
echo "# Note: disabling this limit or setting it too high may result in severe damage"
echo "# to the system."
echo "# Default: 25M"
echo "#MaxFileSize 30M"
echo ""
echo "# Nested archives are scanned recursively, e.g. if a Zip archive contains a RAR"
echo "# file, all files within it will also be scanned. This options specifies how"
echo "# deeply the process should be continued."
echo "# Note: setting this limit too high may result in severe damage to the system."
echo "# Default: 16"
echo "#MaxRecursion 10"
echo ""
echo "# Number of files to be scanned within an archive, a document, or any other"
echo "# container file."
echo "# Value of 0 disables the limit."
echo "# Note: disabling this limit or setting it too high may result in severe damage"
echo "# to the system."
echo "# Default: 10000"
echo "#MaxFiles 15000"
echo ""
echo "# Maximum size of a file to check for embedded PE. Files larger than this value"
echo "# will skip the additional analysis step."
echo "# Note: disabling this limit or setting it too high may result in severe damage"
echo "# to the system."
echo "# Default: 10M"
echo "#MaxEmbeddedPE 10M"
echo ""
echo "# Maximum size of a HTML file to normalize. HTML files larger than this value"
echo "# will not be normalized or scanned."
echo "# Note: disabling this limit or setting it too high may result in severe damage"
echo "# to the system."
echo "# Default: 10M"
echo "#MaxHTMLNormalize 10M"
echo ""
echo "# Maximum size of a normalized HTML file to scan. HTML files larger than this"
echo "# value after normalization will not be scanned."
echo "# Note: disabling this limit or setting it too high may result in severe damage"
echo "# to the system."
echo "# Default: 2M"
echo "#MaxHTMLNoTags 2M"
echo ""
echo "# Maximum size of a script file to normalize. Script content larger than this"
echo "# value will not be normalized or scanned."
echo "# Note: disabling this limit or setting it too high may result in severe damage"
echo "# to the system."
echo "# Default: 5M"
echo "#MaxScriptNormalize 5M"
echo ""
echo "# Maximum size of a ZIP file to reanalyze type recognition. ZIP files larger"
echo "# than this value will skip the step to potentially reanalyze as PE."
echo "# Note: disabling this limit or setting it too high may result in severe damage"
echo "# to the system."
echo "# Default: 1M"
echo "#MaxZipTypeRcg 1M"
echo ""
echo "# This option sets the maximum number of partitions of a raw disk image to be"
echo "# scanned."
echo "# Raw disk images with more partitions than this value will have up to"
echo "# the value number partitions scanned. Negative values are not allowed."
echo "# Note: setting this limit too high may result in severe damage or impact"
echo "# performance."
echo "# Default: 50"
echo "#MaxPartitions 128"
echo ""
echo "# This option sets the maximum number of icons within a PE to be scanned."
echo "# PE files with more icons than this value will have up to the value number"
echo "# icons scanned."
echo "# Negative values are not allowed."
echo "# WARNING: setting this limit too high may result in severe damage or impact"
echo "# performance."
echo "# Default: 100"
echo "#MaxIconsPE 200"
echo ""
echo "# This option sets the maximum recursive calls for HWP3 parsing during"
echo "# scanning. HWP3 files using more than this limit will be terminated and"
echo "# alert the user."
echo "# Scans will be unable to scan any HWP3 attachments if the recursive limit"
echo "# is reached."
echo "# Negative values are not allowed."
echo "# WARNING: setting this limit too high may result in severe damage or impact"
echo "# performance."
echo "# Default: 16"
echo "#MaxRecHWP3 16"
echo ""
echo "# This option sets the maximum calls to the PCRE match function during"
echo "# an instance of regex matching."
echo "# Instances using more than this limit will be terminated and alert the user"
echo "# but the scan will continue."
echo "# For more information on match_limit, see the PCRE documentation."
echo "# Negative values are not allowed."
echo "# WARNING: setting this limit too high may severely impact performance."
echo "# Default: 100000"
echo "#PCREMatchLimit 20000"
echo ""
echo "# This option sets the maximum recursive calls to the PCRE match function"
echo "# during an instance of regex matching."
echo "# Instances using more than this limit will be terminated and alert the user"
echo "# but the scan will continue."
echo "# For more information on match_limit_recursion, see the PCRE documentation."
echo "# Negative values are not allowed and values > PCREMatchLimit are superfluous."
echo "# WARNING: setting this limit too high may severely impact performance."
echo "# Default: 5000"
echo "#PCRERecMatchLimit 10000"
echo ""
echo "# This option sets the maximum filesize for which PCRE subsigs will be"
echo "# executed. Files exceeding this limit will not have PCRE subsigs executed"
echo "# unless a subsig is encompassed to a smaller buffer."
echo "# Negative values are not allowed."
echo "# Setting this value to zero disables the limit."
echo "# WARNING: setting this limit too high or disabling it may severely impact"
echo "# performance."
echo "# Default: 25M"
echo "#PCREMaxFileSize 100M"
echo ""
echo "# When BlockMax is set, files exceeding the MaxFileSize, MaxScanSize, or"
echo "# MaxRecursion limit will be flagged with the virus"
echo "# \"Heuristic.Limits.Exceeded\"."
echo "# Default: no"
echo "#BlockMax yes"
echo ""
echo "##"
echo "## On-access Scan Settings"
echo "##"
echo ""
echo "# Enable on-access scanning. Currently, this is supported via fanotify."
echo "# Clamuko/Dazuko support has been deprecated."
echo "# Default: no"
echo "#ScanOnAccess yes"
echo ""
echo "# Set the  mount point to be scanned. The mount point specified, or the mount"
echo "# point containing the specified directory will be watched. If any directories"
echo "# are specified, this option will preempt the DDD system. This will notify"
echo "# only. It can be used multiple times."
echo "# (On-access scan only)"
echo "# Default: disabled"
echo "#OnAccessMountPath /"
echo "#OnAccessMountPath /home/user"
echo ""
echo "# Don't scan files larger than OnAccessMaxFileSize"
echo "# Value of 0 disables the limit."
echo "# Default: 5M"
echo "#OnAccessMaxFileSize 10M"
echo ""
echo "# Set the include paths (all files inside them will be scanned). You can have"
echo "# multiple OnAccessIncludePath directives but each directory must be added"
echo "# in a separate line. (On-access scan only)"
echo "# Default: disabled"
echo "#OnAccessIncludePath /home"
echo "#OnAccessIncludePath /students"
echo ""
echo "# Set the exclude paths. All subdirectories are also excluded."
echo "# (On-access scan only)"
echo "# Default: disabled"
echo "#OnAccessExcludePath /home/bofh"
echo ""
echo "# With this option you can whitelist the root UID (0). Processes run under"
echo "# root with be able to access all files without triggering scans or"
echo "# permission denied events."
echo "# Note that if clamd cannot check the uid of the process that generated an"
echo "# on-access scan event (e.g., because OnAccessPrevention was not enabled, and"
echo "# the process already exited), clamd will perform a scan.  Thus, setting"
echo "# OnAccessExcludeRootUID is not *guaranteed* to prevent every access by the"
echo "# root user from triggering a scan (unless OnAccessPrevention is enabled)."
echo "# Default: no"
echo "#OnAccessExcludeRootUID no"
echo ""
echo "# With this option you can whitelist specific UIDs. Processes with these UIDs"
echo "# will be able to access all files without triggering scans or permission"
echo "# denied events."
echo "# This option can be used multiple times (one per line)."
echo "# Using a value of 0 on any line will disable this option entirely."
echo "# To whitelist the root UID (0) please enable the OnAccessExcludeRootUID"
echo "# option."
echo "# Also note that if clamd cannot check the uid of the process that generated an"
echo "# on-access scan event (e.g., because OnAccessPrevention was not enabled, and"
echo "# the process already exited), clamd will perform a scan.  Thus, setting"
echo "# OnAccessExcludeUID is not *guaranteed* to prevent every access by the"
echo "# specified uid from triggering a scan (unless OnAccessPrevention is enabled)."
echo "# Default: disabled"
echo "#OnAccessExcludeUID -1"
echo ""
echo "# Toggles dynamic directory determination. Allows for recursively watching"
echo "# include paths."
echo "# (On-access scan only)"
echo "# Default: no"
echo "#OnAccessDisableDDD yes"
echo ""
echo "# Modifies fanotify blocking behaviour when handling permission events."
echo "# If off, fanotify will only notify if the file scanned is a virus,"
echo "# and not perform any blocking."
echo "# (On-access scan only)"
echo "# Default: no"
echo "#OnAccessPrevention yes"
echo ""
echo "# Toggles extra scanning and notifications when a file or directory is"
echo "# created or moved."
echo "# Requires the  DDD system to kick-off extra scans."
echo "# NOTE:  This feature is disabled until a thread resource leak bug"
echo "#        in the OnAccessExtraScanning code can be resolved."
echo "# (On-access scan only)"
echo "# Default: no"
echo "#OnAccessExtraScanning yes"
echo ""
echo "##"
echo "## Bytecode"
echo "##"
echo ""
echo "# With this option enabled ClamAV will load bytecode from the database. "
echo "# It is highly recommended you keep this option on, otherwise you'll miss"
echo "# detections for many new viruses."
echo "# Default: yes"
echo "#Bytecode yes"
echo ""
echo "# Set bytecode security level."
echo "# Possible values:"
echo "#   None -      No security at all, meant for debugging."
echo "#               DO NOT USE THIS ON PRODUCTION SYSTEMS."
echo "#               This value is only available if clamav was built"
echo "#               with --enable-debug!"
echo "#   TrustSigned - Trust bytecode loaded from signed .c[lv]d files, insert"
echo "#               runtime safety checks for bytecode loaded from other sources."
echo "#   Paranoid -  Don't trust any bytecode, insert runtime checks for all."
echo "# Recommended: TrustSigned, because bytecode in .cvd files already has these"
echo "# checks."
echo "# Note that by default only signed bytecode is loaded, currently you can only"
echo "# load unsigned bytecode in --enable-debug mode."
echo "#"
echo "# Default: TrustSigned"
echo "#BytecodeSecurity TrustSigned"
echo ""
echo "# Set bytecode timeout in milliseconds."
echo "# "
echo "# Default: 5000"
echo "# BytecodeTimeout 1000"
echo ""
echo "##"
echo "## Statistics gathering and submitting"
echo "##"
}

create_freshclam_conf()
{
echo "# Path to the database directory."
echo "# WARNING: It must match clamd.conf's directive!"
echo "# Default: hardcoded (depends on installation options)"
echo "DatabaseDirectory $indimaildir/clamd"
echo ""
echo "# Path to the log file (make sure it has proper permissions)"
echo "# Default: disabled"
echo "#UpdateLogFile /var/log/freshclam.log"
echo ""
echo "# Maximum size of the log file."
echo "# Value of 0 disables the limit."
echo "# You may use 'M' or 'm' for megabytes (1M = 1m = 1048576 bytes)"
echo "# and 'K' or 'k' for kilobytes (1K = 1k = 1024 bytes)."
echo "# in bytes just don't use modifiers. If LogFileMaxSize is enabled,"
echo "# log rotation (the LogRotate option) will always be enabled."
echo "# Default: 1M"
echo "#LogFileMaxSize 2M"
echo ""
echo "# Log time with each message."
echo "# Default: no"
echo "#LogTime yes"
echo ""
echo "# Enable verbose logging."
echo "# Default: no"
echo "#LogVerbose yes"
echo ""
echo "# Use system logger (can work together with UpdateLogFile)."
echo "# Default: no"
echo "#LogSyslog yes"
echo ""
echo "# Specify the type of syslog messages - please refer to 'man syslog'"
echo "# for facility names."
echo "# Default: LOG_LOCAL6"
echo "#LogFacility LOG_MAIL"
echo ""
echo "# Enable log rotation. Always enabled when LogFileMaxSize is enabled."
echo "# Default: no"
echo "#LogRotate yes"
echo ""
echo "# This option allows you to save the process identifier of the daemon"
echo "# Default: disabled"
echo "#PidFile /var/run/freshclam.pid"
echo ""
echo "# By default when started freshclam drops privileges and switches to the"
echo "# \"clamav\" user. This directive allows you to change the database owner."
echo "# Default: clamav (may depend on installation options)"
echo "DatabaseOwner qscand"
echo ""
echo "# Use DNS to verify virus database version. Freshclam uses DNS TXT records"
echo "# to verify database and software versions. With this directive you can change"
echo "# the database verification domain."
echo "# WARNING: Do not touch it unless you're configuring freshclam to use your"
echo "# own database verification domain."
echo "# Default: current.cvd.clamav.net"
echo "#DNSDatabaseInfo current.cvd.clamav.net"
echo ""
echo "# database.clamav.net is now the primary domain name to be used world-wide."
echo "# Now that CloudFlare is being used as our Content Delivery Network (CDN), "
echo "# this one domain name works world-wide to direct freshclam to the closest "
echo "# geographic endpoint."
echo "DatabaseMirror database.clamav.net"
echo ""
echo "# How many attempts to make before giving up."
echo "# Default: 3 (per mirror)"
echo "MaxAttempts 5"
echo ""
echo "# With this option you can control scripted updates. It's highly recommended"
echo "# to keep it enabled."
echo "# Default: yes"
echo "#ScriptedUpdates yes"
echo ""
echo "# By default freshclam will keep the local databases (.cld) uncompressed to"
echo "# make their handling faster. With this option you can enable the compression;"
echo "# the change will take effect with the next database update."
echo "# Default: no"
echo "#CompressLocalDatabase no"
echo ""
echo "# With this option you can provide custom sources (http:// or file://) for"
echo "# database files. This option can be used multiple times."
echo "# Default: no custom URLs"
echo "#DatabaseCustomURL http://myserver.com/mysigs.ndb"
echo "#DatabaseCustomURL file:///mnt/nfs/local.hdb"
echo ""
echo "# This option allows you to easily point freshclam to private mirrors."
echo "# If PrivateMirror is set, freshclam does not attempt to use DNS"
echo "# to determine whether its databases are out-of-date, instead it will"
echo "# use the If-Modified-Since request or directly check the headers of the"
echo "# remote database files. For each database, freshclam first attempts"
echo "# to download the CLD file. If that fails, it tries to download the"
echo "# CVD file. This option overrides DatabaseMirror, DNSDatabaseInfo"
echo "# and ScriptedUpdates. It can be used multiple times to provide"
echo "# fall-back mirrors."
echo "# Default: disabled"
echo "#PrivateMirror mirror1.mynetwork.com"
echo "#PrivateMirror mirror2.mynetwork.com"
echo ""
echo "# Number of database checks per day."
echo "# Default: 12 (every two hours)"
echo "#Checks 24"
echo ""
echo "# Proxy settings"
echo "# Default: disabled"
echo "#HTTPProxyServer myproxy.com"
echo "#HTTPProxyPort 1234"
echo "#HTTPProxyUsername myusername"
echo "#HTTPProxyPassword mypass"
echo ""
echo "# If your servers are behind a firewall/proxy which applies User-Agent"
echo "# filtering you can use this option to force the use of a different"
echo "# User-Agent header."
echo "# Default: clamav/version_number"
echo "#HTTPUserAgent SomeUserAgentIdString"
echo ""
echo "# Use aaa.bbb.ccc.ddd as client address for downloading databases. Useful for"
echo "# multi-homed systems."
echo "# Default: Use OS'es default outgoing IP address."
echo "#LocalIPAddress aaa.bbb.ccc.ddd"
echo ""
echo "# Send the RELOAD command to clamd."
echo "# Default: no"
echo "#NotifyClamd /path/to/clamd.conf"
echo ""
echo "# Run command after successful database update."
echo "# Default: disabled"
echo "#OnUpdateExecute command"
echo ""
echo "# Run command when database update process fails."
echo "# Default: disabled"
echo "#OnErrorExecute command"
echo ""
echo "# Run command when freshclam reports outdated version."
echo "# In the command string %v will be replaced by the new version number."
echo "# Default: disabled"
echo "#OnOutdatedExecute command"
echo ""
echo "# Don't fork into background."
echo "# Default: no"
echo "Foreground yes"
echo ""
echo "# Enable debug messages in libclamav."
echo "# Default: no"
echo "#Debug yes"
echo ""
echo "# Timeout in seconds when connecting to database server."
echo "# Default: 30"
echo "#ConnectTimeout 60"
echo ""
echo "# Timeout in seconds when reading from database server."
echo "# Default: 30"
echo "#ReceiveTimeout 60"
echo ""
echo "# With this option enabled, freshclam will attempt to load new"
echo "# databases into memory to make sure they are properly handled"
echo "# by libclamav before replacing the old ones."
echo "# Default: yes"
echo "#TestDatabases yes"
echo ""
echo "# This option enables support for Google Safe Browsing. When activated for"
echo "# the first time, freshclam will download a new database file"
echo "# (safebrowsing.cvd) which will be automatically loaded by clamd and"
echo "# clamscan during the next reload, provided that the heuristic phishing"
echo "# detection is turned on. This database includes information about websites"
echo "# that may be phishing sites or possible sources of malware. When using this"
echo "# option, it's mandatory to run freshclam at least every 30 minutes."
echo "# Freshclam uses the ClamAV's mirror infrastructure to distribute the"
echo "# database and its updates but all the contents are provided under Google's"
echo "# terms of use. See https://www.google.com/transparencyreport/safebrowsing"
echo "# and https://www.clamav.net/documents/safebrowsing"
echo "# for more information."
echo "# Default: disabled"
echo "#SafeBrowsing yes"
echo ""
echo "# This option enables downloading of bytecode.cvd, which includes additional"
echo "# detection mechanisms and improvements to the ClamAV engine."
echo "# Default: enabled"
echo "#Bytecode yes"
echo ""
echo "# Download an additional 3rd party signature database distributed through"
echo "# the ClamAV mirrors. "
echo "# This option can be used multiple times."
echo "#ExtraDatabase dbname1"
echo "#ExtraDatabase dbname2"
}

create_bogofilter_conf()
{
if [ ! -f "$DESTDIR"$sysconfdir/bogofilter.cf.example ] ; then
	echo ""$DESTDIR"$sysconfdir/bogofilter.cf.example: No such file or directory" 1>&2
	return 1
fi
/bin/cat "$DESTDIR"$sysconfdir/bogofilter.cf.example | sed \
	-e 's,##bogofilter_dir=,bogofilter_dir=,g' \
	-e 's,#spam_header_name=,spam_header_name=,g' \
	-e 's,#spam_header_place=,spam_header_place=,g' \
	-e 's,##spamicity_tags = Yes\, No\, Unsure,spamicity_tags = Yes\, No\, Unsure,g' \
	-e 's,##spamicity_formats = %0.6f\, %0.6f\, %0.6f,spamicity_formats = %0.6f\, %0.6f\, %0.6f,g' \
	-e 's,#header_format = %h: %c\, tests=bogofilter\, spamicity=%p\, version=%v,header_format = %h: %c\, spamicity=%p\, cutoff=%o\, ham_cutoff=%O\,version=%v\,register-%r %w words %m msg,g' \
	-e 's,#log_update_format = register-%r\, %w words\, %m messages,log_update_format = register-%r\, %w words\, %m messages,g' \
	-e 's,##log_header_format = %h: %c\, spamicity=%f\, ipaddr=%A\, queueID=%Q\, msgID=%I\, subject=%s\, version=%v,log_header_format = %h: %c\, spamicity=%p\, cutoff=%o\, ham_cutoff=%O\, queueID=%Q\, msgID=%I\, ipaddr=%A,g' \
	-e 's,##ham_cutoff  = 0.00,ham_cutoff  = 0.00,g' \
	-e 's,##spam_cutoff = 0.99,spam_cutoff = 0.99,g'
}

repair_tables()
{
	MYSQL_DB="indimail"
	if [ -f $HOME/.mylogin.cnf ] ; then
	(
	$mysqlPrefix/bin/mysql --login-path=admin -s --database=$MYSQL_DB \
		--execute="show tables" | while read i
	do
		$mysqlPrefix/bin/mysql --login-path=admin -s --database=$MYSQL_DB \
			--execute="check table $i"
	done
	) | awk -v prefix=$mysqlPrefix \
		-v database=$MYSQL_DB '{
		table=$1
		operation=$2
		msg_type=$3
		msg_text=$4
		if (FNR == 1)
			printf("%s %-30s %-9s %-8s %s\n", "S/N", "Table", "Operation", "msg_type", "msg_text");
		printf("%03d %-30s %-9s %-8s %s\n", FNR, table, operation, msg_type, msg_text);
		if (msg_text != "OK")
		{
			cmd=sprintf("%s/bin/mysql --login-path=admin -s --database=%s \
				--execute=\"repair table %s;\"", \
				prefix, database, table);
			system(cmd);
		}
	}'
	else
	(
	$mysqlPrefix/bin/mysql -s -u $PRIV_USER -p$PRIV_PASS --database=$MYSQL_DB \
		--execute="show tables" | while read i
	do
		$mysqlPrefix/bin/mysql -s -u $PRIV_USER -p$PRIV_PASS --database=$MYSQL_DB \
			--execute="check table $i"
	done
	) | awk -v prefix=$mysqlPrefix -v mysql_user=$PRIV_USER -v mysql_pass=$PRIV_PASS \
		-v database=$MYSQL_DB '{
		table=$1
		operation=$2
		msg_type=$3
		msg_text=$4
		if (FNR == 1)
			printf("%s %-30s %-9s %-8s %s\n", "S/N", "Table", "Operation", "msg_type", "msg_text");
		printf("%03d %-30s %-9s %-8s %s\n", FNR, table, operation, msg_type, msg_text);
		if (msg_text != "OK")
		{
			cmd=sprintf("%s/bin/mysql -s -u %s -p%s --database=%s \
				--execute=\"repair table %s;\"", \
				prefix, mysql_user, mysql_pass, database, table);
			system(cmd);
		}
	}'
	fi
}

report ()
{
	for i in $*
	do
		case $i in
			all)
				report_option="all"
			;;
			zoverall|zddist|zsuccesses|zdeferrals|zfailures|zsenders|zrecipients| zrhosts| \
				zrxdelay| zsendmail|zsuids|zsmtp|zspam|all)
			;;
			*)
				echo "Invalid option $i" 1>&2
				usage 1
			;;
		esac
	done
	if [ ! -d $LOGDIR ] ; then
		/bin/mkdir -p $LOGDIR
		$chown qmaill:nofiles $LOGDIR
	fi
	if [ ! -d $LOGDIR/reports ] ; then
		/bin/mkdir -p $LOGDIR/reports
		$chown qmaill:nofiles $LOGDIR/reports
	fi
	(
	if [ -f $LOGDIR/reports/send_pend ] ; then
		/bin/cat $LOGDIR/reports/send_pend
		/bin/rm -f $LOGDIR/reports/send_pend
	fi
	/bin/cat $LOGDIR/deliver.25/current 
	) | "$DESTDIR"$libexecdir/matchup 5>$LOGDIR/reports/pend_tmp > $LOGDIR/reports/deliver25
	if [ -s $LOGDIR/reports/pend_tmp ] ; then
		/bin/mv $LOGDIR/reports/pend_tmp $LOGDIR/reports/send_pend
	else
		/bin/rm -f $LOGDIR/reports/pend_tmp
	fi

	(
	if [ -f $LOGDIR/reports/smtp25_pend ] ; then
		/bin/cat $LOGDIR/reports/smtp25_pend
		/bin/rm -f $LOGDIR/reports/smtp25_pend
	fi
	/bin/cat $LOGDIR/smtpd.25/current
	) | "$DESTDIR"$libexecdir/smtp-matchup 5>$LOGDIR/reports/pend_tmp | \
	"$DESTDIR"$QmailBinPrefix/bin/tai64nunix > $LOGDIR/reports/smtp25
	if [ -s $LOGDIR/reports/pend_tmp ] ; then
		/bin/mv $LOGDIR/reports/pend_tmp $LOGDIR/reports/smtp25_pend
	else
		/bin/rm -f $LOGDIR/reports/pend_tmp
	fi
	(
	if [ -f $LOGDIR/reports/smtp587_pend ] ; then
		/bin/cat $LOGDIR/reports/smtp587_pend
		/bin/rm -f $LOGDIR/reports/smtp587_pend
	fi
	/bin/cat $LOGDIR/smtpd.587/current
	) | "$DESTDIR"$libexecdir/smtp-matchup 5>$LOGDIR/reports/pend_tmp | \
	"$DESTDIR"$QmailBinPrefix/bin/tai64nunix > $LOGDIR/reports/smtp587
	if [ -s $LOGDIR/reports/pend_tmp ] ; then
		/bin/mv $LOGDIR/reports/pend_tmp $LOGDIR/reports/smtp587_pend
	else
		/bin/rm -f $LOGDIR/reports/pend_tmp
	fi

	spamheader_name=`grep ^spam_header_name $sysconfdir/bogofilter.cf | cut -d= -f2`
	if [ " $spamheader_name" = " " ] ; then
		> $LOGDIR/reports/spam
	else
		> $LOGDIR/reports/spam
		/bin/cat $LOGDIR/logfifo/current | grep $spamheader_name| "$DESTDIR"$QmailBinPrefix/bin/tai64nunix \
		> $LOGDIR/reports/spam
	fi

	if [ -s $LOGDIR/reports/deliver25 -o -s $LOGDIR/reports/smtp25 -o -s $LOGDIR/reports/smtp587 ] ; then
		EXT=`date +'%d/%m/%y %H:%M:%S'`
		(
		if [ " $report_option" = " all" ] ; then
			for i in zoverall zddist zrhosts zrxdelay \
				zfailures zdeferrals zsenders \
				zrecipients zsuids zsmtp zspam
			do
				echo "-- Report $i ----------------"
				if [ " $i" = " zsmtp" ] ; then
					if [ -s $LOGDIR/reports/smtp25 ] ; then
						echo "---- Port 25 -----------------"
						"$DESTDIR"$libexecdir/$i < $LOGDIR/reports/smtp25
					fi
					if [ -s $LOGDIR/reports/smtp587 ] ; then
						echo "---- Port 587 ----------------"
						"$DESTDIR"$libexecdir/$i < $LOGDIR/reports/smtp587
					fi
				elif [ " $i" = " zspam" ] ; then
					if [ -s $LOGDIR/reports/spam ] ; then
						"$DESTDIR"$libexecdir/$i < $LOGDIR/reports/spam
					fi
				else
					if [ -s $LOGDIR/reports/deliver25 ] ; then
						"$DESTDIR"$libexecdir/$i < $LOGDIR/reports/deliver25
					fi
				fi
				echo
			done
		else
			for i in $*
			do
				echo "-- Report $i ----------------"
				if [ " $i" = " zsmtp" ] ; then
					if [ -s $LOGDIR/reports/smtp25 ] ; then
						echo "---- Port 25 -----------------"
						"$DESTDIR"$libexecdir/$i < $LOGDIR/reports/smtp25
					fi
					if [ -s $LOGDIR/reports/smtp587 ] ; then
						echo "---- Port 587 ----------------"
						"$DESTDIR"$libexecdir/$i < $LOGDIR/reports/smtp587
					fi
				elif [ " $i" = " zspam" ] ; then
					if [ -s $LOGDIR/reports/spam ] ; then
						"$DESTDIR"$libexecdir/$i < $LOGDIR/reports/spam
					fi
				else
					if [ -s $LOGDIR/reports/deliver25 ] ; then
						"$DESTDIR"$libexecdir/$i < $LOGDIR/reports/deliver25
					fi
				fi
				echo
			done
		fi
		) > /tmp/report.$$
		if [ " $postmaster" = " " ] ; then
			/bin/cat /tmp/report.$$
			/bin/rm -f /tmp/report.$$
		else
			subject="Mail Statistics for `/usr/bin/head -1 $CONTROLDIR/me` on $EXT"
			date=`/bin/date -R`
			if [ " $attach_report" = " " ] ; then
				(
				echo "To: $postmaster"
				echo "From: \"IndiMail Reporter\" <Mailer-Daemon>"
				echo "Date: $date"
				echo "Subject: $subject"
				echo
				echo ATTENTION: Mail Administrators
				echo
				echo Mail Statistics for `/bin/cat $CONTROLDIR/me`
				echo on $date
				echo from host `"$DESTDIR"$libexecdir/hostname`
				echo
				echo "Since I am good only at reporting, please do not reply"
				echo "to me."
				echo
				echo "Thank you for using IndiMail"
				echo
				echo "I am enclosing a copy of the Statistics below"
				echo
				/bin/cat /tmp/report.$$
				/bin/rm -f /tmp/report.$$
				) | "$DESTDIR"$QmailBinPrefix/bin/sendmail -t
			else
				(
				echo ATTENTION: Mail Administrators
				echo
				echo Mail Statistics for `/usr/bin/head -1 $CONTROLDIR/me` 
				echo on $date
				echo from host `"$DESTDIR"$libexecdir/hostname`
				echo
				echo "I have attached a copy of the Statistics in zip file format."
				echo "Since I am good only at reporting, please do not reply"
				echo "to me."
				echo
				echo "Thank you for using IndiMail"
				echo
				) > /tmp/descfile.$$
				/usr/bin/zip -q -j -m /tmp/report.$$.zip /tmp/report.$$
				QMAILUSER=postmaster
				if [ ! " $default_domain" = " " ] ; then
					QMAILHOST=$default_domain
				fi
				QMAILNAME="IndiMail Reporter"
				export QMAILNAME
				"$DESTDIR"$QmailBinPrefix/bin/mpack -s "$subject" -d /tmp/descfile.$$ \
				-c "application/zip" /tmp/report.$$.zip $postmaster
				/bin/rm -f /tmp/descfile.$$ /tmp/report.$$.zip
			fi
		fi
		/bin/rm -f $LOGDIR/reports/deliver25 $LOGDIR/reports/smtp25 \
			$LOGDIR/reports/smtp587 $LOGDIR/reports/spam
	fi
}

dump_config()
{
if [ $# -ne 2 ] ; then
	echo "USAGE: dump_config servicedir controldir" 1>&2
	return 1
fi
servicedir=$1
CONTROLDIR=$2
export CONTROLDIR
if [ ! -d $servicedir ] ; then
	echo "servicedir: No such file or directory" 1>&2
	return 1
fi
echo "Service Configuration ================================================"
echo Service Directory $servicedir
cd $servicedir
scount=1
for j in `/bin/ls -a $servicedir`
do
	if [ " $j" = " ." -o " $j" = " .." ] ; then
		continue
	fi
	printf "Service %05d %s\n" $scount $j
	scount=`expr $scount + 1`
	if [ -f $j/run ] ; then
		echo "Run File [$j/run]"
		/bin/cat $j/run
		/bin/echo -n "- EOF -----------------"
		printf "%-20s" "$j/run"
		echo "-----------------------"
		echo
	fi
	if [ -f $j/log/run ] ; then
		echo "Log Run File [$j/log/run]"
		/bin/cat $j/log/run
		/bin/echo -n "- EOF -----------------"
		printf "%-20s" "$j/log/run"
		echo "-----------------------"
		echo
	fi
	if [ -f $j/shutdown ] ; then
		echo "Shutdown File [$j/shutdown]"
		/bin/cat $j/shutdown
		/bin/echo -n "- EOF -----------------"
		printf "%-20s" "$j/shutdown"
		echo "-----------------------"
		echo
	fi
	if [ -d $j/variables ] ; then
		count=1
		for k in `ls $j/variables`
		do
			if [ $count -eq 1 ] ; then
				echo "Variables List"
			fi
			if [ -s $j/variables/$k ] ; then
				printf "%-3d %s\nValue:[" $count $k
				val=`/bin/cat $j/variables/$k`
				if [ " $val" = " " ] ; then
					/bin/echo -n "SET"
				else
					/bin/echo -n $val
				fi
				printf "]\n"
			else
				printf "%-3d %s\nValue:[UNSET]\n" $count $k
			fi
			count=`expr $count + 1`
			echo
		done
	fi
	echo
done
echo
echo "Control Configuration ================================================="
echo
"$DESTDIR"$QmailBinPrefix/bin/qmail-showctl
echo
echo "IndiMail Assign File:"
/bin/cat "$DESTDIR"$sysconfdir/users/assign
echo
/bin/rm -f /tmp/svctool.ver.$$
}

# backup /service, system-startup config, indimail configuration
sort_backup()
{
if [ $# -lt 1 ] ; then
	echo "sort_backup service_dir" 1>&2
	return 1
fi
if [ -f /etc/event.d/svscan ] ; then
	file=/etc/event.d/svscan
elif [ -f /etc/init/svscan.conf ] ; then
	file=/etc/init/svscan.conf
elif [ -f /lib/systemd/system/svscan.service ] ; then
	file=/lib/systemd/system/svscan.service
elif [ -f /usr/lib/systemd/system/svscan.service ] ; then
	file=/usr/lib/systemd/system/svscan.service
fi
# who cuts the barber
if [ -f $sysconfdir/backup.conf ] ; then
	file="$file `/bin/cat $sysconfdir/backup.conf`"
fi
servicedir=$1
(
for i in $servicedir $CONTROLDIR \
	$sysconfdir $QmailHOME/domains $QmailHOME/autoturn \
	$QmailHOME/alias/.qmail-* \
	/etc/inittab /etc/init.d/svscan \
	$file /etc/passwd /etc/group /etc/hosts /etc/sysconfig/network \
	/etc/resolv.conf \
	$QmailHOME/.bashrc $QmailHOME/.bash_profile \
	$QmailHOME/.indimail $file
do
	if [ -f $i -o -d $i ] ; then
		echo $i
	fi
done
) | sort -u
}

create_mrtg()
{
if [ $# -lt 2 ] ; then
	echo "create_mrtg htmldir service_dir" 1>&2
	return 1
fi
htmldir=$1
SERVICEDIR=$2
conf_dir="$DESTDIR"$SERVICEDIR/mrtg/variables
if [ $nooverwrite -eq 1 -a -d $conf_dir ] ; then
	return 0
fi
/bin/mkdir -p $htmldir
$chown root:0 $htmldir
/bin/chmod 755 $htmldir
# mrtg - script
/bin/mkdir -p "$DESTDIR"$SERVICEDIR/mrtg/log
if [ $down_state -eq 1 ] ; then
	$TOUCH "$DESTDIR"$SERVICEDIR/mrtg/down
fi
/bin/mkdir -p $conf_dir
/bin/chmod 500 $conf_dir
$chown root:0 $conf_dir
/bin/mkdir -p "$conf_dir"/../etc
/bin/chmod 555 $conf_dir/../etc
$chown root:0 $conf_dir/../etc
echo C > $conf_dir/LANG
sed "s{MRTGHOSTNAME{`hostname`{;  s{HTMLDIR{$htmldir\/{" \
	$sysconfdir/indimail.mrtg.cfg > $conf_dir/../etc/indimail.mrtg.cfg
#
# Create index.html in htmldir
#
indexmaker=$(which indexmaker)
$indexmaker --title="IndiMail Statistics" --section=title \
	--output=$htmldir/index.html  $conf_dir/../etc/indimail.mrtg.cfg
# mrtg run script
(
echo "#!/bin/sh"
echo "$RCSID"
echo "# generated on $host on `date`"
echo "# $prog_args"
echo ""
echo "exec 2>&1"
echo "while true"
echo "do"
echo "  $QmailBinPrefix/bin/envdir variables \\"
echo "    /usr/bin/mrtg etc/indimail.mrtg.cfg"
echo "  status=\$?"
echo "  echo \"mrtg \`pwd\`/etc/indimail.mrtg.cfg status \$status\""
if [ " $scan_interval" = " " ] ; then
echo "  sleep 300"
else
echo "  sleep $scan_interval"
fi
echo "done"
echo "exit \$status"
) > "$DESTDIR"$SERVICEDIR/mrtg/run
/bin/chmod +x "$DESTDIR"$SERVICEDIR/mrtg/run

if [ ! -d $LOGDIR ] ; then
	/bin/mkdir -p $LOGDIR
	$chown qmaill:nofiles $LOGDIR
fi
# mrtg log script
(
echo "#!/bin/sh"
echo "$RCSID"
echo "# generated on $host on `date`"
echo "# $prog_args"
echo ""
echo "exec $QmailBinPrefix/bin/setuidgid qmaill \\"
echo "$QmailBinPrefix/sbin/multilog t $LOGDIR/mrtg"
) > "$DESTDIR"$SERVICEDIR/mrtg/log/run
/bin/chmod +x "$DESTDIR"$SERVICEDIR/mrtg/log/run
echo "$prog_args" > $conf_dir/.options
}

tls_cert_check()
{
if [ ! -x /usr/bin/openssl ] ; then
	echo "/usr/bin/openssl: No such file or directory" 1>&2
	return 1
fi
error=0
if [ $# -eq 1 ] ; then
	files=$1
else
	files="$sysconfdir/certs/servercert.pem $sysconfdir/certs/clientcert.pem"
fi
for cert in $files
do
	if [ -f $cert ]; then
		echo "Checking $cert"
		#First, check that it's a valid cert for the task
		TEMP_PURPOSE=`/usr/bin/openssl x509 -in $cert -noout -purpose 2>/dev/null`
		if [ "$?" != "0" ]; then
			error=1
			dir=`dirname $cert`
			fil=`basename $cert`
			$mv -f $cert $dir/BROKEN-${fil}
			if [ $? -eq 0 ] ; then
				echo $TEMP_PURPOSE 1>&2
				echo "$cert is a broken cert. Disabled" 1>&2
			fi
		fi

		#Now check it hasn't expired
		TEMP_DATE=`/usr/bin/openssl x509 -in $cert -noout -dates 2>/dev/null|grep -i after|cut -d= -f2`
		case "$host" in
			*-*-darwin*|*-*-freebsd*)
			EXPIRE_IN_SECS=`date -j -f "%b %d %T %Y %Z" "$TEMP_DATE" "+%s"`
			;;
			*)
			EXPIRE_IN_SECS=`date +%s --date $TEMP_DATE 2>/dev/null`
			;;
		esac
		if [ "`echo $EXPIRE_IN_SECS|egrep '^[0-9]+$'`" != "" ]; then
			NOW_IN_SECS=`date +%s 2>/dev/null`
			if [ "`echo $NOW_IN_SECS|egrep '^[0-9]+$'`" != "" ]; then
				if [ $NOW_IN_SECS -gt $EXPIRE_IN_SECS ]; then
					error=1
					echo expiry $TEMP_DATE 1>&2
					dir=`dirname $cert`
					fil=`basename $cert`
					$mv -f $cert $dir/EXPIRED-${fil}
					if [ $? -eq 0 ] ; then
						echo "$cert has EXPIRED. Disabling" 1>&2
					fi
				fi
			fi
		fi

		if [ "`echo $cert|grep server`" != "" ];then
			if [ "`echo $TEMP_PURPOSE|egrep -i '(any purpose|server).* yes'`" = "" ]; then
				error=1
				echo "Purpose $TEMP_PURPOSE" 1>&2
				dir=`dirname $cert`
				fil=`basename $cert`
				$mv -f $cert $dir/NOT-A-SERVER-CERT-${fil}
				if [ $? -eq 0 ] ; then
					echo "$cert is NOT a server cert. Disabled" 1>&2
				fi
			fi
		fi
		if [ "`echo $cert|grep client`" != "" ];then
			if [ "`echo $TEMP_PURPOSE|egrep -i '(any purpose|client).* yes'`" = "" ]; then
				error=1
				echo "Purpose $TEMP_PURPOSE" 1>&2
				dir=`dirname $cert`
				fil=`basename $cert`
				$mv -f $cert $dir/NOT-A-CLIENT-CERT-${fil}
				if [ $? -eq 0 ] ; then
					echo "$cert is NOT a client cert. Disabled" 1>&2
				fi
			fi		
		fi
	fi
done
if [ $error -eq 0 ] ; then
	echo "All Certificates found OK"
fi
}

################################# Main ##################################
if test $# -eq 0; then
    usage 1
fi
if [ -x /bin/chown ] ; then
	chown=/bin/chown
elif [ -x /usr/sbin/chown ] ; then
	chown=/usr/sbin/chown
elif [ -x /usr/bin/chown ] ; then
	chown=/usr/bin/chown
else
	chown=/bin/chown
fi

if [ -f $sysconfdir/svctool.cnf ] ; then
	$chown root:0 $sysconfdir/svctool.cnf
	/bin/chmod 400 $sysconfdir/svctool.cnf
	. $sysconfdir/svctool.cnf
fi
[ -z "$MYSQL_PASS" ] && MYSQL_PASS="ssh-1.5-"
[ -z "$PRIV_PASS" ]  && PRIV_PASS="4-57343-"
[ -z "$ADMIN_PASS" ] && ADMIN_PASS="benhur20"

prog_args="$QmailBinPrefix/sbin/svctool"
force=0
no_multi=0
silent=0
down_state=0
use_unshare=0
use_ssl=0
use_starttls=0
forcetls=0
nooverwrite=0
run_file_only=0
utf8=0
databytes=$DATABYTES
if [ " $CONTROLDIR" = " " ] ; then
	cntrldir=$sysconfdir/control
else
	slash=`echo $CONTROLDIR | cut -c1`
	if [ " $slash" = " /" ] ; then
		cntrldir=$CONTROLDIR
	else
		cntrldir=$sysconfdir/$CONTROLDIR
	fi
fi
CONTROLDIR=$cntrldir
export CONTROLDIR
if [ -f $cntrldir/servicedir.conf ] ; then
	servicedir=`cat $cntrldir/servicedir.conf`
else
	servicedir=/service
fi
if [ -x /bin/touch ] ; then
	touch=/bin/touch
elif [ -x /usr/bin/touch ] ; then
	touch=/usr/bin/touch
else
	touch=/bin/touch
fi
while test $# -gt 0; do
    case "$1" in
    -*=*)
	optarg=`echo "$1" | sed 's/[-_a-zA-Z0-9]*=//'`
	optval=`echo "$1" | cut -d'=' -f1`
	prog_args="$prog_args $optval=\"$optarg\""
	;;
    *)
	optarg=
	prog_args="$prog_args $1"
	;;
    esac

    case "$1" in
    --qbase=*)
	qbase=$optarg
	;;
    --verbose)
	verbose="-v"
	;;
    --qcount=*)
	qcount=$optarg
	;;
    --qstart=*)
	qstart=$optarg
	;;
    --min-free=*)
	min_free=$optarg
	;;
    --deliverylimit-count=*)
	mailcount_limit=$optarg
	;;
    --deliverylimit-size=*)
	mailsize_limit=$optarg
	;;
    --overquota_mailsize=*)
	overquota_mailsize=$optarg
	;;
    --servicedir=*)
	servicedir=$optarg
	;;
    --cntrldir=*)
	slash=`echo $optarg | cut -c1`
	if [ " $slash" = " /" ] ; then
		cntrldir=$optarg
	else
		cntrldir=$sysconfdir/$optarg
	fi
	CONTROLDIR=$cntrldir
	export CONTROLDIR
	;;
	--skipsend)
	skipsend=1
	;;
	--databytes=*)
	databytes=$optarg
	;;
	--scanint=*)
	scan_interval=$optarg
	;;
	--memory=*)
	memory=$optarg
	;;
	--dmemory=*)
	dmemory=$optarg
	;;
	--password-cache)
	password_cache=1
	;;
	--query-cache)
	query_cache=1
	;;
	--use-btree)
	use_btree=1
	;;
	--max-btree-count=*)
	max_btree_count=$optarg
	;;
	--servicetag=*)
	servicetag=$optarg
	;;
	--qregex)
	qregex=1
	;;
	--qhpsi=*)
	qhpsi=$optarg
	;;
	--virus-filter=*)
	viruscheck=$optarg
	;;
	--virus-filter)
	viruscheck=1
	;;
	--no-multi)
	no_multi=1
	;;
	--content-filter=*)
	bodycheck=$optarg
	;;
	--content-filter)
	bodycheck=1
	;;
	--dnscheck)
	dnscheck=1
	;;
	--helofqdn)
	helofqdn=1
	;;
	--helocheck)
	helocheck=1
	;;
	--fsync)
	usefsync=1
	;;
	--syncdir)
	usesyncdir=1
	;;
	--debug-level=*)
	debug_level=$optarg
	;;
	--spamfilter=*)
	spamfilter=$optarg
	echo $spamfilter | grep '/' >/dev/null 2>&1
	if [ $? -ne 0 ] ; then
		echo spamfilter must be an absolute path 1>&2
		exit 1
	fi
	;;
	--logfilter=*)
	logfilter=$optarg
	;;
	--localfilter)
	localfilter=1
	;;
	--remotefilter)
	remotefilter=1
	;;
	--rejectspam=*)
	rejectspam=$optarg
	;;
    --spamexitcode=*)
	spamexitcode=$optarg
	;;
	--masquerade)
	masquerade=1
	;;
    --logdir=*)
	LOGDIR=$optarg
	export LOGDIR
	;;
    --indimaildir=*)
	indimaildir=$optarg
	export indimaildir
	;;
	--domainlimits)
	domainlimits=1
	;;
    --chkrecipient)
	chkrecipient=1
	;;
    --antispoof)
	antispoof=1
	;;
    --cugmail)
	cugmail=1
	;;
    --forceauthsmtp)
	forceauthsmtp=1
	;;
    --authsmtp)
	authsmtp=1
	;;
    --remote-authsmtp=*)
	remoteauthsmtp=$optarg
	;;
	--min-resend-min=*)
	min_resend_min=$optarg
	;;
	--resend-win-hr=*)
	resend_win_hr=$optarg
	;;
	--timeout-days=*)
	timeout_days=$optarg
	;;
	--context-file=*)
	echo $optarg | grep '/' >/dev/null 2>&1
	if [ $? -eq 0 ] ; then
		echo context file cannot have absolute path 1>&2
		exit 1
	fi
	context_file=$optarg
	;;
	--save-interval=*)
	save_interval=$optarg
	;;
	--hash-size=*)
	hash_size=$optarg
	;;
	--whitelist=*)
	echo $optarg | grep '/' >/dev/null 2>&1
	if [ $? -eq 0 ] ; then
		echo whitelist file cannot have absolute path 1>&2
		exit 1
	fi
	whitelist=$optarg
	;;
	--authall)
	authall=1
	;;
	--chkrelay)
	chkrelay=1
	;;
	--paranoid)
	paranoid=1
	;;
	--dmasquerade)
	dmasquerade=1
	;;
	--force)
	force=1
	;;
	--routes=*)
	routes=$optarg
	;;
	--utf8)
	utf8=1
	;;
	--cname-lookup)
	enable_cname_lookup="yes"
	;;
	--odmr)
	odmr=1
	;;
	--rbl=*)
	rbl=1
	rbl_list="$optarg $rbl_list"
	;;
	--proxy=*)
	proxy_port=$optarg
	;;
	--localip=*)
	ipaddress=$optarg
	;;
	--maxdaemons=*)
	maxdaemons=$optarg
	;;
	--setpassword=*)
	password_cmd=$optarg
	;;
	--certfile=*)
	certfile=$optarg
	;;
	--maxperip=*)
	maxperip=$optarg
	;;
	--nolastauth)
	nolastauth=1
	;;
	--legacyserver)
	legacyserver=1
	;;
	--smtp-plugin)
	enable_smtp_plugin=1
	;;
	--starttls) # e.g. port 25, 587
	use_starttls=1
	use_ssl=0
	;;
	--ssl) # e.g. port 465
	use_starttls=0
	use_ssl=1
	;;
	--forcetls)
	forcetls=1
	;;
	--tlsprog=*)
	tlsprog=$optarg
	echo $tlsprog | grep '/' >/dev/null 2>&1
	if [ $? -ne 0 ] ; then
		echo tlsprog must be an absolute path 1>&2
		exit 1
	fi
	;;
	--persistdb)
	persistdb=1
	;;
	--mysqlhost=*)
	mysql_host=$optarg
	;;
	--mysqluser=*)
	mysql_user=$optarg
	;;
	--mysqlpass=*)
	mysql_pass=$optarg
	;;
	--mysqlport=*)
	mysql_port=$optarg
	;;
	--mysqlsocket=*)
	mysql_socket=$optarg
	;;
	--avguserquota=*)
	avg_user_quota=$optarg
	;;
	--hardquota=*)
	hard_quota=$optarg
	;;
	--base_path=*)
	base_path=$optarg
	;;
	--default-domain=*)
	default_domain=$optarg
	;;
	--databasedir=*)
	databasedir=$optarg
	;;
	--capath=*)
	ca_path=$optarg
	;;
	--certdir=*)
	certdir=$optarg
	;;
	--mysqlPrefix=*)
	mysqlPrefix=$optarg
	;;
	--clamdPrefix=*)
	clamdPrefix=$optarg
	;;
	--sysconfdir=*)
	mysysconfdir=$optarg
	;;
	--dbdir=*)
	dbdir=$optarg
	;;
	--postmaster=*)
	postmaster=$optarg
	;;
	--common_name=*)
	common_name=$optarg
	;;
	--attach)
	if [ -f /usr/bin/zip ] ; then
		attach_report=1
	else
		echo "/usr/bin/zip is missing on your system" 1>&2
		echo "will not use attachments to send out reports" 1>&2
		echo "Press ENTER to continue" 1>&2
		read key
	fi
	;;

	--showctl=*)
	CONTROLDIR=$optarg
	export CONTROLDIR
	echo $CONTROLDIR | grep '/' >/dev/null 2>&1
	if [ $? -eq 0 ] ; then
		if [ ! -d $CONTROLDIR ] ; then
			echo "$CONTROLDIR: No such file or directory" 1>&2
			exec "$DESTDIR"$QmailBinPrefix/bin/qmail-showctl
		fi
	else
		if [ ! -d /etc/indimail/$CONTROLDIR ] ; then
			echo "/etc/indimail/$CONTROLDIR: No such file or directory" 1>&2
		else
			exec "$DESTDIR"$QmailBinPrefix/bin/qmail-showctl
		fi
	fi
	exit 1
	;;

	--fixsharedlibs)
	if [ -z "$CONTROLDIR" ] ; then
		CONTROLDIR=$sysconfdir/control
	fi
	case "$host" in
		*-*-darwin**)
		libdir=/opt/local/lib
		if [ -n "$DESTDIR" ] ; then
			indlib=`ls -d "$DESTDIR""$libdir"*/libindimail.*.dylib 2>/dev/null|sed -e "'s}$DESTDIR}}g'"`
		else
			indlib=`ls -d "$libdir"*/libindimail.*.dylib 2>/dev/null`
		fi
		;;
		*)
		libdir=$QmailBinPrefix/lib
		if [ -n "$DESTDIR" ] ; then
			indlib=`ls -d "$DESTDIR""$libdir"*/libindimail.so.*.*.* 2>/dev/null|sed -e "'s}$DESTDIR}}g'"`
		else
			indlib=`ls -d "$libdir"*/libindimail.so.*.*.* 2>/dev/null`
		fi
		;;
	esac
	if [ -n "$indlib" -a -f "$indlib" ] ; then
		check_update_if_diff "$DESTDIR"$CONTROLDIR/libindimail $indlib
		if [ $? -eq 0 ] ; then
			echo ""$DESTDIR"$CONTROLDIR/libindimail exists: No Change" 1>&2
		fi
	elif [ -f "$DESTDIR"$CONTROLDIR/libindimail ] ; then
		echo "removing "$DESTDIR"$CONTROLDIR/libindimail"
		/bin/rm -f "$DESTDIR"$CONTROLDIR/libindimail
	fi
	check_libmysqlclient_lib
	nolog=1
	exit $?
	;;
	--queuefix=*)
	"$DESTDIR"$QmailBinPrefix/bin/queue-fix $optarg
	exit 0
	;;

	--threads=*)
	thread_count=$optarg
	;;

	--activeDays=*)
	activeDays=$optarg
	;;

	--timeout=*)
	timeout=$optarg
	;;

	--nolog)
	nolog=1
	;;

	# create new qmail assign file
	--wipe)
	wipe_option=1
	;;

	--silent)
	silent=1
	;;

	--destdir=*)
	DESTDIR=$optarg
	;;

	--dkverify=*)
	dkverify_option=$optarg
	;;
	--dksign=*)
	dksign_option=$optarg
	;;
	--private_key=*)
	private_key=$optarg
	;;
	--down)
	down_state=1
	;;
	--unshare)
	use_unshare=1
	;;

	--version)
	echo "$RCSID"
	exit 0
	;;

	--help)
	usage 0
	;;

	--smtp=*)
	option=1
	smtp_port=$optarg
	;;

	--imap=*)
	option=2
	imap_port=$optarg
	;;

	--pop3=*)
	option=3
	pop3_port=$optarg
	;;

	--rmsvc=*)
	option=4
	service=$optarg
	;;

	--ensvc=*)
	option=5
	service=$optarg
	;;

	--infifo=*)
	infifo=$optarg
	;;

	--inlookup=*)
	option=6
	infifo=$optarg
	;;

	--indisrvr=*)
	option=7
	bind_port=$optarg
	;;

	--mysql=*)
	option=8
	mysql_port=$optarg
	;;

	--fetchmail)
	option=9
	;;

	--nooverwrite)
	nooverwrite=1
	;;

	--config=*)
	if [ " $option" = " " ] ; then
		option=10
		config_name=$optarg
	else
		conf_file=$optarg
	fi
	;;

	--check-install)
	option=11
	;;

	--inittab)
	option=12
	;;

	--backup=*)
	backupdir=$optarg
	option=13
	;;

	--repair-tables)
	option=14
	;;

	--report=*)
	option=15
	report_option=$optarg
	;;

	--qscanq)
	option=16
	;;

	--clamd)
	option=17
	;;

	--poppass=*)
	poppass_port=$optarg
	option=18
	;;

	--svscanlog)
	option=19
	;;

	--initcmd=*)
	svscan_init_cmd=$optarg
	;;

	--pwdlookup=*)
	option=20
	socket_path=$optarg
	;;

	--dumpconfig)
	option=21
	;;

	--greylist=*)
	option=22
	grey_port=$optarg
	;;
	--use-greydaemon)
	use_greydaemon=1
	;;

	--qmtp=*)
	option=23
	qmtp_port=$optarg
	;;
	--qmqp=*)
	option=24
	qmqp_port=$optarg
	;;

	--queueParam=*)
	option=25
	queuedef=$optarg
	echo $queuedef | grep '/' >/dev/null 2>&1
	if [ $? -eq 0 ] ; then
		echo queuedef cannot be an absolute path 1>&2
		exit 1
	fi
	;;

	--delivery=*)
	option=26
	queue_ident=$optarg
	;;

	--udplogger=*)
	option=27
	udp_port=$optarg
	;;

	--fifologger=*)
	option=28
	logfilter=$optarg
	;;

	--mrtg=*)
	option=29
	htmldir=$optarg
	;;

	--shared-objects=*)
	shared_objects=$optarg
	;;

	--use-dlmopen=*)
	use_dlmopen=$optarg
	;;

	--check-certs)
	cert_file=""
	option=30
	;;

	--check-certs=*)
	cert_file=$optarg
	option=30
	;;
	--skip-sendmail)
	skip_sendmail_check=1
	;;

	--enable-service)
	option=31
	service=$optarg
	break
	;;

	--disable-service)
	option=32
	service=$optarg
	break
	;;

	--tlsa=*)
	option=33
	dane_port=$optarg
	;;

	--refreshsvc=*)
	option=34
	service=$optarg
	;;

	--run-file-only)
	if [ $option -eq 34 ] ; then
		run_file_only=1
	fi
	;;

	--norefreshsvc=*)
	option=35
	service=$optarg
	;;

	--mysqlupgrade)
	if [ " $mysqlPrefix" = " " ] ; then
		echo "MySQL Installation Prefix directory not specified" 1>&2
		usage 1
	fi
	if [ -x $mysqlPrefix/bin/mysql_upgrade ] ; then
		echo "Running MySQL Upgrade to fix MySQL 8.0 Montrosity"
		$mysqlPrefix/bin/mysql_upgrade -u mysql -p"$PRIV_PASS"
	fi
	;;

	*)
	echo "invalid option [$1]" 1>&2
	read key
	usage 1
	;;
	esac
	shift
done

#
# Main
#
case $option in
	1) # SMTP Service
	# Check that we're a privileged user
	[ `id -u` = 0 ] || exit 4
	if [ " $servicedir" = " " ] ; then
		echo "Supervise Directory not specified" 1>&2
		usage 1
	elif [ " $smtp_port" = " " ] ; then
		echo "SMTP PORT not specified" 1>&2
		usage 1
	elif [ $smtp_port -lt 1 ] ; then
		echo "SMTP PORT should be a positive number" 1>&2
		usage 1
	fi
	if [ " $odmr" = " " ] ; then
		if [ " $qbase" = " " ] ; then
			echo "Queue Directory not specified" 1>&2
			usage 1
		elif [ " $qcount" = " " ] ; then
			echo "Queue Count not specified" 1>&2
			usage 1
		elif [ " $qstart" = " " ] ; then
			echo "Start Queue Number not specified" 1>&2
			usage 1
		elif [ $qcount -lt 1 ] ; then
			echo "No of Queues should be a positive number" 1>&2
			usage 1
		elif [ $qstart -lt 1 ] ; then
			echo "Start Queue Number should be a positive number" 1>&2
			usage 1
		fi
		case "$dkverify_option" in
			dkim|dk|both)
			;;
			none|"")
			;;
			*)
			echo "invalid --dkverify=$dkverify_option" 1>&2
			usage 1
			;;
		esac
		case "$dksign_option" in
			dkim|dk|both)
			if [ " $private_key" = " " ] ; then
				echo "--private_key not specfied" 1>&2
				usage 1
			fi
			;;
			none|"")
			;;
			*)
			echo "invalid --dksign=$dksign_option" 1>&2
			usage 1
			;;
		esac
		if [ " $skipsend" = " " ] ; then
			echo "Creating $qcount queues"
			if [ $use_starttls -ne 0 -o $use_ssl -ne 0 ] ; then
				create_delivery "$qbase" "$qcount" "$qstart" "$servicedir" "$smtp_port" "$routes" "1" "$utf8"
			else
				create_delivery "$qbase" "$qcount" "$qstart" "$servicedir" "$smtp_port" "$routes" "0" "$utf8"
			fi
		fi
	fi
	if [ " $odmr" = " " ] ; then
	echo "Creating SMTP Listener Port $smtp_port, Service $servicedir, Queue Base $qbase, Queue Count $qcount, Queue Start $qstart"
	else
	echo "Creating SMTP Listener Port $smtp_port, Service $servicedir"
	fi
	create_smtp "$qbase" "$qcount" "$qstart" "$servicedir" "$smtp_port" "$chkrecipient" "$chkrelay" "$use_ssl" "$forcetls" "$infifo" "$utf8"
	;;

	2) # IMAP Service
	# Check that we're a privileged user
	[ `id -u` = 0 ] || exit 4
	if [ " $imap_port" = " " ] ; then
		echo "IMAP PORT not specified" 1>&2
		usage 1
	elif [ " $servicedir" = " " ] ; then
		echo "Supervise Directory not specified" 1>&2
		usage 1
	elif [ $imap_port -lt 1 ] ; then
		echo "IMAP PORT should be a positive number" 1>&2
		usage 1
	elif [ " $default_domain" = " " ] ; then
		echo "Default Domain not specified" 1>&2
		usage 1
	fi
	if [ ! " $proxy" = " " ] ; then
		if [ " $hard_quota" = " " ] ; then
			echo "User Hard Quota not specified" 1>&2
			usage 1
		elif [ $hard_quota -lt 500000 ] ; then
			echo "Hard Quota should be greater than 500k" 1>&2
			usage 1
		fi
	fi
	echo "Creating IMAP4 Listener Port $imap_port, Service $servicedir infifo $infifo"
	create_courier "$servicedir" "imapd" "$imap_port" "$nolastauth" "$legacyserver" "$use_ssl" "$infifo"
	;;

	3) # POP3 Service
	# Check that we're a privileged user
	[ `id -u` = 0 ] || exit 4
	if [ " $pop3_port" = " " ] ; then
		echo "POP3 PORT not specified" 1>&2
		usage 1
	elif [ " $servicedir" = " " ] ; then
		echo "Supervise Directory not specified" 1>&2
		usage 1
	elif [ $pop3_port -lt 1 ] ; then
		echo "POP3 PORT should be a positive number" 1>&2
		usage 1
	elif [ " $default_domain" = " " ] ; then
		echo "Default Domain not specified" 1>&2
		usage 1
	fi
	if [ ! " $proxy" = " " ] ; then
		if [ " $hard_quota" = " " ] ; then
			echo "User Hard Quota not specified" 1>&2
			usage 1
		elif [ $hard_quota -lt 500000 ] ; then
			echo "Hard Quota should be greater than 500k" 1>&2
			usage 1
		fi
	fi
	echo "Creating POP3 Listener Port $pop3_port, Service $servicedir infifo $infifo"
	create_courier "$servicedir" "pop3d" "$pop3_port" "$nolastauth" "$legacyserver" "$use_ssl" "$infifo"
	;;

	4) # remove service
	# Check that we're a privileged user
	[ `id -u` = 0 ] || exit 4
	rmsvc "$service"
	;;

	5) # enable servie
	# Check that we're a privileged user
	[ `id -u` = 0 ] || exit 4
	ensvc "$service"
	;;

	6) # inlookup service
	# Check that we're a privileged user
	[ `id -u` = 0 ] || exit 4
	if [ " $servicedir" = " " ] ; then
		echo "Supervise Directory not specified" 1>&2
		usage 1
	elif [ " $infifo" = " " ] ; then
		echo "INFIFO not specified" 1>&2
		usage 1
	elif [ " $thread_count" = " " ] ; then
		echo "Thread Count not specified" 1>&2
		usage 1
	elif [ " $activeDays" = " " ] ; then
		activeDays=7
	fi
	echo "Creating InLookup Daemon on Fifo $infifo, Service $servicedir, Threads $thread_count ActiveDays=$activeDays"
	create_inlookup "$infifo" "$thread_count" "$activeDays" "$servicedir"
	;;

	7) # indisrvr service
	# Check that we're a privileged user
	[ `id -u` = 0 ] || exit 4
	if [ " $servicedir" = " " ] ; then
		echo "Supervise Directory not specified" 1>&2
		usage 1
	elif [ " $bind_port" = " " ] ; then
		echo "Port not specified" 1>&2
		usage 1
	elif [ " $avg_user_quota" = " " ] ; then
		echo "Average User Quota not specified" 1>&2
		usage 1
	elif [ " $hard_quota" = " " ] ; then
		echo "User Hard Quota not specified" 1>&2
		usage 1
	elif [ " $base_path" = " " ] ; then
		echo "Base Path not specified" 1>&2
		usage 1
	elif [ $bind_port -lt 1 ] ; then
		echo "BIND PORT should be a positive number" 1>&2
		usage 1
	elif [ $avg_user_quota -lt 500000 ] ; then
		echo "Average User Quota should be greater than 500k" 1>&2
		usage 1
	elif [ $hard_quota -lt 500000 ] ; then
		echo "Hard Quota should be greater than 500k" 1>&2
		usage 1
	fi
	if [ -n "$mysql_host" ] ; then
		if [ " $mysql_user" = " " ] ; then
			echo "MySQL User not specified" 1>&2
			usage 1
		elif [ " $mysql_pass" = " " ] ; then
			echo "MySQL Passwd not specified" 1>&2
			usage 1
		fi
	fi
	echo "Creating IndiMail Admin Service Port $bind_port, Service $servicedir, Base Path $base_path"
	create_indisrvr "$bind_port" "$mysql_host" "$mysql_user" "$mysql_pass" "$avg_user_quota" "$hard_quota" \
		"$base_path" "$servicedir" "$use_ssl"
	;;

	8) # MySQL service
	# Check that we're a privileged user
	[ `id -u` = 0 ] || exit 4
	if [ " $servicedir" = " " ] ; then
		echo "Supervise Directory not specified" 1>&2
		usage 1
	elif [ " $default_domain" = " " ] ; then
		echo "default domain not specified" 1>&2
		exit 1
	elif [ " $databasedir" = " " ] ; then
		echo "Database directory not specified" 1>&2
		usage 1
	elif [ " $mysqlPrefix" = " " ] ; then
		echo "MySQL Installation Prefix directory not specified" 1>&2
		usage 1
	elif [ " $conf_file" = " " ] ; then
		echo "Config file not specified" 1>&2
		usage 1
	elif [ " $mysql_port" = " " ] ; then
		echo "Port not specified" 1>&2
		usage 1
	elif [ $mysql_port -lt 1 ] ; then
		echo "BIND PORT should be a positive number" 1>&2
		usage 1
	fi
	echo "Creating MySQL Service Port $mysql_port, Service $servicedir, conf file $conf_file"
	create_mysql_service "$mysql_port" "$mysqlPrefix" "$databasedir" "$conf_file" "$servicedir"
	;;

	9) # fetchmail service
	# Check that we're a privileged user
	[ `id -u` = 0 ] || exit 4
	if [ " $qbase" = " " ] ; then
		echo "Queue Directory not specified" 1>&2
		usage 1
	elif [ " $qcount" = " " ] ; then
		echo "Queue Count not specified" 1>&2
		usage 1
	elif [ " $qstart" = " " ] ; then
		echo "Start Queue Number not specified" 1>&2
		usage 1
	elif [ " $servicedir" = " " ] ; then
		echo "Supervise Directory not specified" 1>&2
		usage 1
	elif [ " $default_domain" = " " ] ; then
		echo "Default Domain not specified" 1>&2
		usage 1
	elif [ $qcount -lt 1 ] ; then
		echo "No of Queues should be a positive number" 1>&2
		usage 1
	elif [ $qstart -lt 1 ] ; then
		echo "Start Queue Number should be a positive number" 1>&2
		usage 1
	fi
	echo "Creating FetchMail Daemon Service $servicedir, Queue Base $qbase, Queue Count $qcount, Qstart $qstart"
	create_fetchmail "$qbase" "$qcount" "$qstart" "$servicedir"
	;;

	10) # --config
	# config creation for MySQL, MySQL Database creation, imap, 
	# 1  MySQL Config creation
	# 2  MySQL Database creation
	# 4  IMAP config creation
	# 5  POP3 config creation
	# 6  qmail config creation
	# 7  create indimail users from system (/etc/passwd,etc)
	# 8  remove indimail users from system (/etc/passwd, etc)
	# 9  create clamd, freschclam config, foxhole_all.cdb
	# 10 create bogofilter config and wordlist.db
	# 11 create CERTS
	# 12 add startup for indimail at boot
	# 13 remove startup for indimail from boot
	# 14 enable selinux module

	# Check that we're a privileged user
	[ `id -u` = 0 ] || exit 4
	case $config_name in
		mysql)
		if [ " $mysqlPrefix" = " " ] ; then
			echo "MySQL Installation Prefix directory not specified" 1>&2
			usage 1
		elif [ " $databasedir" = " " ] ; then
			echo "Database directory not specified" 1>&2
			usage 1
			exit 1
		fi
		if [ " $mysql_port" = " " ]; then
			mysql_port=3306
		fi
		if [ " $mysql_socket" = " " ]; then
			if [ -d /run/mysqld ] ; then
				mysql_socket=/run/mysqld/mysqld.sock
			elif [ -d /var/run/mysqld ] ; then
				mysql_socket=/var/run/mysqld/mysqld.sock
			elif [ -d /var/lib/mysql ] ; then
				mysql_socket=/var/lib/mysql/mysql.sock
			else
				mysql_socket=$mysqlSocket
			fi
		fi
		if [ -x $mysqlPrefix/libexec/mysqld ] ; then
			mysqld=libexec/mysqld
		elif [ -x $mysqlPrefix/sbin/mysqld ] ; then
			mysqld=sbin/mysqld
		elif [ -x $mysqlPrefix/bin/mysqld ] ; then
			mysqld=bin/mysqld
		else
			echo "mysqld: No such File or directory" 1>&2
			return 1
		fi
		conf_file="$DESTDIR"$sysconfdir/indimail.cnf
		mysql_version=`$mysqlPrefix/$mysqld --version 2>&1 | grep Ver | awk '{print $3}'`
		echo "creating mysql config MySQL version $mysql_version"
		create_mysql_config > /tmp/config.cnf.$$
		conf_dir=`dirname $conf_file`
		if [ ! -d $conf_dir ] ; then
			mkdir -p $conf_dir
		fi
		change_config $conf_file /tmp/config.cnf.$$
		echo $mysql_version |grep MariaDB > /dev/null 2>&1
		if [ $? -eq 0 ] ; then
			mysql_version=`echo $mysql_version|cut -d- -f1`
			mariadb=1
		else
			mariadb=0
		fi
		if [ $mariadb -eq 1 ] ; then
			if [ -d /etc/my.cnf.d ] ; then
				/bin/ln -sf $sysconfdir/indimail.cnf /etc/my.cnf.d/indimail.cnf
				if [ -f /etc/my.cnf ] ; then
					grep '^!includedir /etc/my.cnf.d' /etc/my.cnf > /dev/null 2>&1
					if [ $? -ne 0 ] ; then
						echo '!includedir /etc/my.cnf.d' >> /etc/my.cnf
					fi
				fi
			elif  [ -d /etc/mysql ] ; then
				/bin/ln -sf $sysconfdir/indimail.cnf /etc/mysql/indimail.cnf
				if [ -f /etc/my.cnf ] ; then
					grep '^!includedir /etc/mysql' /etc/my.cnf > /dev/null 2>&1
					if [ $? -ne 0 ] ; then
						echo '!includedir /etc/mysql' >> /etc/my.cnf
					fi
				fi
			else
				/bin/ln -sf $sysconfdir/indimail.cnf /etc/indimail.cnf
			fi
		else
			if [ -d /etc/my.cnf.d -a ! -d /etc/mysql -a ! -h /etc/mysqlf ] ; then
				/bin/ln -s /etc/my.cnf.d /etc/mysql
				/bin/ln -sf $sysconfdir/indimail.cnf /etc/my.cnf.d/indimail.cnf
				if [ -f /etc/my.cnf ] ; then
					grep '^!includedir /etc/my.cnf.d' /etc/my.cnf > /dev/null 2>&1
					if [ $? -ne 0 ] ; then
						echo '!includedir /etc/my.cnf.d' >> /etc/my.cnf
					fi
				fi
			elif  [ -d /etc/mysql ] ; then
				/bin/ln -sf $sysconfdir/indimail.cnf /etc/mysql/indimail.cnf
				if [ -f /etc/my.cnf ] ; then
					grep '^!includedir /etc/mysql' /etc/my.cnf > /dev/null 2>&1
					if [ $? -ne 0 ] ; then
						echo '!includedir /etc/mysql' >> /etc/my.cnf
					fi
				fi
			else
				/bin/ln -sf $sysconfdir/indimail.cnf /etc/indimail.cnf
			fi
		fi
		if [ -d /etc/security/limits.d -a ! -f /etc/security/limits.d/51-mysql.conf ] ; then
			echo "mysql hard nproc unlimited" > /etc/security/limits.d/51-mysql.conf
		fi
		;;

		mysqldb)
		if [ " $mysqlPrefix" = " " ] ; then
			echo "MySQL Installation Prefix directory not specified" 1>&2
			usage 1
		elif [ " $databasedir" = " " ] ; then
			echo "Database directory not specified" 1>&2
			usage 1
			exit 1
		elif [ " $base_path" = " " ] ; then
			echo "Base Path not specified" 1>&2
			usage 1
			exit 1
		elif [ " $default_domain" = " " ] ; then
			echo "default domain not specified" 1>&2
			exit 1
		fi
		if [ " $mysql_socket" = " " ]; then
			if [ -d /run/mysqld ] ; then
				mysql_socket=/run/mysqld/mysqld.sock
			elif [ -d /var/run/mysqld ] ; then
				mysql_socket=/var/run/mysqld/mysqld.sock
			elif [ -d /var/lib/mysql ] ; then
				mysql_socket=/var/lib/mysql/mysql.sock
			else
				mysql_socket=$mysqlSocket
			fi
		fi
		create_mysql_db "$databasedir" "$mysql_socket"
		;;

		ssl_rsa)
		if [ " $certdir" = " " ] ; then
			echo "Certificate directory not specified" 1>&2
			usage 1
			exit 1
		fi
		echo "Creating MariaDB SSL/TLS Certificates"
		mariadb_ssl_rsa_setup "$ca_path" "$DESTDIR"$certdir
		;;

		indimail)
		default_indimail_control
		;;

		qmail)
		if [ " $postmaster" = " " ] ; then
			echo "postmaster not specified" 1>&2
			exit 1
		fi
		create_qmail_config # calls default_qmail_control
		;;

		users)
		nscd_up=`ps -ax |grep nscd |grep -v grep|wc -l`
		if [ $nscd_up -ge 1 ] ; then
			if [ -x /etc/init.d/nscd ] ; then
				/etc/init.d/nscd stop
			fi
		fi
		create_users
		if [ $nscd_up -ge 1 ] ; then
			if [ -x /etc/init.d/nscd ] ; then
				/etc/init.d/nscd start
			fi
		fi
		;;

		rmusers)
		delUsers
		;;

		clamd)
		if [ ! -d "$DESTDIR"$sysconfdir ] ; then
			/bin/mkdir -p "$DESTDIR"$sysconfdir
		fi
		if [ -f /usr/sbin/clamd ] ; then
			conf_file="$DESTDIR"$sysconfdir/scan.conf
		else
			conf_file="$DESTDIR"$sysconfdir/scan.conf.disabled
		fi
		if [ -d /etc/clamd.d ] ; then
			if [ -f /etc/clamd.d/scan.conf -a ! -L /etc/clamd.d/scan.conf ] ; then
				cat /etc/clamd.d/scan.conf | sed \
					-e 's,#LogClean,LogClean,g' \
					-e 's,#LocalSocket,LocalSocket,g' \
					-e 's,LogSyslog,#LogSyslog,g' \
					-e 's,#DatabaseDirectory.*,DatabaseDirectory /var/indimail/clamd,g' \
					-e 's,LocalSocketGroup.*,LocalSocketGroup qmail,g'  \
					-e 's,#LocalSocketMode,LocalSocketMode,g' \
					-e 's,#FixStaleSocket,FixStaleSocket,g' \
					-e 's,User.*,User qscand,g'  \
					-e 's,#Foreground,Foreground,g' \
					-e '0,/^#Example$/d' > /tmp/config.cnf.$$
				if [ ! -s /tmp/config.cnf.$$ ] ; then
					create_clamd_conf > /tmp/config.cnf.$$
				fi
			elif [ ! -f /etc/clamd.d/scan.conf ] ; then
				create_clamd_conf > /tmp/config.cnf.$$
			fi
		else
			create_clamd_conf > /tmp/config.cnf.$$
		fi
		if [ $? -eq 0 ] ; then
			change_config $conf_file /tmp/config.cnf.$$
		else
			/bin/rm -f /tmp/config.cnf.$$
		fi
		dbd=`grep -w "^DatabaseDirectory" $conf_file | awk '{print $2}'`
		if [ -z "$dbd" ] ; then
			echo "DatabaseDirectory not defined in $conf_file" 1>&2
			exit 1
		fi
		/bin/mkdir -p $dbd
		if [ $? -eq 0 ] ; then
			$chown qscand:qmail $dbd
			if [ $? -ne 0 ] ; then
				exit 1
			fi
		else
			exit 1
		fi
		if [ -f /etc/clamd.d/scan.conf -a ! -L /etc/clamd.conf ] ; then
			mv /etc/clamd.d/scan.conf /etc/clamd.d/scan.conf.BAK
		fi
		if [ -d /etc/clamd.d -a ! -f "$DESTDIR"/etc/clamd.d/scan.conf ] ; then
			if [ ! -d "$DESTDIR"/etc/clamd.d ] ; then
				mkdir -p "$DESTDIR"/etc/clamd.d
			fi
			/bin/ln -sr "$DESTDIR"$sysconfdir/scan.conf \
				"$DESTDIR"/etc/clamd.d/scan.conf 2>/dev/null
			if [ $? -ne 0 ] ; then
				if [ -d "$DESTDIR"/etc/clamd.d ] ; then
					cd "$DESTDIR"/etc/clamd.d
					/bin/ln -s "$DESTDIR"$sysconfdir/scan.conf
				else
					echo "Unable to create "$DESTDIR"$sysconfdir/scan.conf" 1>&2
					exit 1
				fi
			fi
		fi

		if [ -f "$DESTDIR"$QmailBinPrefix/bin/freshclam ] ; then
			conf_file="$DESTDIR"$sysconfdir/freshclam.conf
		else
			conf_file="$DESTDIR"$sysconfdir/freshclam.conf.disabled
		fi
		if [ -f /etc/freshclam.conf -a ! -L /etc/freshclam.conf ] ; then
			cat /etc/freshclam.conf | sed \
				-e 's,#LogClean,LogClean,g' \
				-e 's,LogSyslog,#LogSyslog,g' \
				-e 's,#DatabaseDirectory.*,DatabaseDirectory /var/indimail/clamd,g' \
				-e 's,#DatabaseOwner.*,DatabaseOwner qscand,g'  \
				-e 's,#Foreground,Foreground,g' \
				-e '0,/^#Example$/d' > /tmp/config.cnf.$$
			if [ ! -s /tmp/config.cnf.$$ ] ; then
				create_freshclam_conf > /tmp/config.cnf.$$
			fi
		elif [ ! -f /etc/freshclam.conf ] ; then
			create_freshclam_conf > /tmp/config.cnf.$$
		fi
		if [ $? -eq 0 ] ; then
			change_config $conf_file /tmp/config.cnf.$$
		else
			/bin/rm -f /tmp/config.cnf.$$
		fi
		if [ -f /etc/freshclam.conf -a ! -L /etc/freshclam.conf ] ; then
			mv /etc/freshclam.conf /etc/freshclam.conf.BAK
		fi
		if [ ! -f "$DESTDIR"/etc/freshclam.conf ] ; then
			if [ ! -d "$DESTDIR"/etc ] ; then
				mkdir -p "$DESTDIR"/etc
			fi
			/bin/ln -sr "$DESTDIR"$sysconfdir/freshclam.conf \
				"$DESTDIR"/etc/freshclam.conf 2>/dev/null
			if [ $? -ne 0 ] ; then
				cd "$DESTDIR"/etc/
				/bin/ln -s "$DESTDIR"$sysconfdir/freshclam.conf
			fi
		fi
		if [ -f /usr/lib/tmpfiles.d/clamd.scan.conf ] ; then
			echo "d /run/clamd.scan 0750 qscand qmail" > /usr/lib/tmpfiles.d/clamd.scan.conf
		fi
		;;

		foxhole)
		if [ ! -d "$DESTDIR"$sysconfdir ] ; then
			/bin/mkdir -p "$DESTDIR"$sysconfdir
		fi
		if [ -f "$DESTDIR"$QmailBinPrefix/sbin/clamd ] ; then
			conf_file="$DESTDIR"$sysconfdir/scan.conf
		else
			conf_file="$DESTDIR"$sysconfdir/scan.conf.disabled
		fi
		dbd=`grep -w "^DatabaseDirectory" $conf_file | awk '{print $2}'`
		if [ -z "$dbd" ] ; then
			echo "DatabaseDirectory not defined in $conf_file" 1>&2
			exit 1
		fi
		/bin/mkdir -p $dbd
		if [ $? -eq 0 ] ; then
			$chown qscand:qmail $dbd
			if [ $? -ne 0 ] ; then
				exit 1
			fi
		else
			exit 1
		fi
		if [ -f "$DESTDIR"$sysconfdir/foxhole_all.cdb -a -d $dbd ] ; then
			/bin/cp "$DESTDIR"$sysconfdir/foxhole_all.cdb $dbd/foxhole_all.cdb
			$chown qscand:qmail $dbd/foxhole_all.cdb
		fi
		;;

		bogofilter)
		conf_file="$DESTDIR"$sysconfdir/bogofilter.cf
		create_bogofilter_conf > /tmp/config.cnf.$$
		if [ $? -eq 0 ] ; then
			change_config $conf_file /tmp/config.cnf.$$
		else
			/bin/rm -f /tmp/config.cnf.$$
		fi
		if [ ! -f "$DESTDIR"$sysconfdir/wordlist.db ] ; then
			# create empty wordlist.db
			"$DESTDIR"$QmailBinPrefix/bin/bogoutil -l "$DESTDIR"$sysconfdir/wordlist.db < /dev/null
			$chown indimail:indimail "$DESTDIR"$sysconfdir/wordlist.db
		fi
		;;

		cert)
		if [ ! -x /usr/bin/openssl ] ; then
			echo "/usr/bin/openssl: No such file or directory" 1>&2
			return 1
		fi
		if [ " $postmaster" = " " ] ; then
			echo "postmaster not specified" 1>&2
			exit 1
		fi
		if [ " $common_name" = " " ] ; then
			echo "CN not specified" 1>&2
			exit 1
		fi
		echo "Creating SSL Configuration"
		create_ssl_cnf $postmaster $common_name > /tmp/config.cnf.$$
		/bin/mkdir -p "$DESTDIR"$sysconfdir/certs
		conf_file=$DESTDIR"$sysconfdir/certs/servercert.cnf"
		/bin/rm -f $conf_file
		change_config $conf_file /tmp/config.cnf.$$
		/bin/chmod 640 $conf_file
		$chown indimail:qmail $conf_file
		if [ ! -f "$DESTDIR"$sysconfdir/certs/servercert.pem ] ; then
			/usr/bin/openssl req -new -x509 -nodes -days 366 -out "$DESTDIR"$sysconfdir/certs/servercert.pem \
				-keyout "$DESTDIR"$sysconfdir/certs/servercert.pem -config $conf_file
			if [ $? = 0 ] ; then
				# qmail-smtpd, qmail-remote
				echo "Creating Private Key, Certificate"
				/bin/chmod 640 "$DESTDIR"$sysconfdir/certs/servercert.pem
				$chown indimail:qmail "$DESTDIR"$sysconfdir/certs/servercert.pem
				/bin/ln -sr "$DESTDIR"$sysconfdir/certs/servercert.pem \
					"$DESTDIR"$sysconfdir/certs/clientcert.pem 2>/dev/null
				if [ $? -ne 0 ] ; then
					cd "$DESTDIR"$sysconfdir/certs
					/bin/ln -s servercert.pem clientcert.pem
				fi
				echo "Updating temporary RSA and DH keys"
				"$DESTDIR"$libexecdir/update_tmprsadh --certdir="$DESTDIR"$sysconfdir/certs

				echo "Fixing CERTDIR variable for qmail-smtpd.25 and qmail-smtpd.465"
				for i in /service/qmail-smtpd.25/variables /service/qmail-smtpd.465/variables
				do
					j=`/bin/cat $i/CERTDIR 2>/dev/null`
					if [ ! " $j" = " $sysconfdir/certs" ] ; then
						echo $sysconfdir/certs > $i/CERTDIR
					fi
				done
				echo "Updating certfile as $sysconfdir/certs/servercert.pem"
				for i in `ls /service/*/variables/*CERTFILE 2>/dev/null`
				do
					j=`/bin/cat $i`
					if [ ! " $j" = " $sysconfdir/certs/servercert.pem" ] ; then
						echo "Fixed $i"
						echo "$sysconfdir/certs/servercert.pem" > $i
					fi
				done
				echo "Updating tls cachefile as $sysconfdir/certs/couriersslcache"
				for i in `ls /service/*/variables/TLS_CACHEFILE 2>/dev/null`
				do
					j=`/bin/cat $i`
					if [ ! " $j" = " $sysconfdir/certs/couriersslcache" ] ; then
						echo "Fixed $i"
						echo "$sysconfdir/certs/couriersslcache" > $i
					fi
				done
				# restart services
				for i in `ls /service/*-ssl.* /service/indisrvr.* /service/qmail-poppass.* 2>/dev/null`
				do
					if [ -d $i ] ; then
						echo $QmailBinPrefix/bin/svc -d $i
						"$DESTDIR"$QmailBinPrefix/bin/svc -d $i
						echo $QmailBinPrefix/bin/svc -u $i
						"$DESTDIR"$QmailBinPrefix/bin/svc -u $i
					fi
				done
			else
				echo "Failed to create openssl x509 certificate" 1>&2
				exit 1
			fi
			/usr/bin/openssl x509 -in "$DESTDIR"$sysconfdir/certs/servercert.pem -noout -text
		else
			echo ""$DESTDIR"$sysconfdir/certs/servercert.pem exists. Remove to create new" 1>&2
			exit 1
		fi
		;;

		add-boot)
		[ `id -u` = 0 ] || exit 4
		case "$host" in
			*-*-darwin*)
			if [ -z "$servicedir" ] ; then
				echo "Supervise Directory not specified" 1>&2
				usage 1
			fi
			;;
		esac
		create_startup
		;;

		rm-boot)
		[ `id -u` = 0 ] || exit 4
		remove_startup
		;;

		add-alt)
		[ `id -u` = 0 ] || exit 4
		add_alternatives
		;;
		remove-alt)
		[ `id -u` = 0 ] || exit 4
		remove_alternatives
		;;

		iselinux)
		[ `id -u` = 0 ] || exit 4
		selinux_module $config_name $sysconfdir/indimail
		;;
		qselinux)
		[ `id -u` = 0 ] || exit 4
		selinux_module $config_name $sysconfdir/indimail-mta
		;;

		*)
		echo "Invalid configuration option $optarg" 1>&2
		usage 1
		;;
	esac
	;;

	11) # check install
	# Check that we're a privileged user
	[ `id -u` = 0 ] || exit 4
	if [ " $qbase" = " " ] ; then
		echo "Queue Directory not specified" 1>&2
		usage 1
	elif [ " $qcount" = " " ] ; then
		echo "Queue Count not specified" 1>&2
		usage 1
	elif [ " $qstart" = " " ] ; then
		echo "Start Queue Number not specified" 1>&2
		usage 1
	elif [ " $servicedir" = " " ] ; then
		echo "Supervise Directory not specified" 1>&2
		usage 1
	fi
	check_installation "$qbase" "$qcount" "$qstart" "$servicedir" "$verbose"
	;;

	12) # create_svscan
	# Check that we're a privileged user
	[ `id -u` = 0 ] || exit 4
	if [ " $servicedir" = " " ] ; then
		echo "Supervise Directory not specified" 1>&2
		usage 1
	fi
	grep "svscanboot" /etc/inittab >/dev/null
	if [ $? -ne 0 ]; then
		if [ -f /etc/debian_release ] ; then
			echo "SV:2345:respawn:$libexecdir/svscanboot $servicedir <>/dev/console 2<>/dev/console" >> /etc/inittab
		else
			echo "SV:345:respawn:$libexecdir/svscanboot $servicedir <>/dev/console 2<>/dev/console" >> /etc/inittab
		fi
		create_svscan $servicedir
	else
		grep "svscanboot" /etc/inittab |grep respawn >/dev/null
		if [ $? -ne 0 ]; then
			grep -v "svscanboot" /etc/inittab > /etc/inittab.svctool.$$
			if [ -f /etc/debian_release ] ; then
				echo "SV:345:respawn:$libexecdir/svscanboot $servicedir <>/dev/console 2<>/dev/console" >> /etc/inittab.svctool.$$
			else
				echo "SV:2345:respawn:$libexecdir/svscanboot $servicedir <>/dev/console 2<>/dev/console" >> /etc/inittab.svctool.$$
			fi
			/bin/mv /etc/inittab.svctool.$$ /etc/inittab
			create_svscan $servicedir
		fi
	fi
	;;

	13) # mysqldump
	# Check that we're a privileged user
	[ `id -u` = 0 ] || exit 4
	if [ " $servicedir" = " " ] ; then
		echo "Supervise Directory not specified" 1>&2
		usage 1
	elif [ " $mysqlPrefix" = " " ] ; then
		echo "MySQL Installation Prefix directory not specified" 1>&2
		usage 1
	elif [ " $backupdir" = " " ] ; then
		echo "Backup directory not specified" 1>&2
		usage 1
	fi
	if [ ! -d $backupdir ] ; then
		echo "$backupdir: No such file or directory" 1>&2
		exit 1
	fi
	EXT=`date +'%d%m%y-%H%M%S'`
	tar cf - `sort_backup $servicedir` | gzip -c > $backupdir/indimail-backup.$EXT.tar.gz
	if [ -f $HOME/.mylogin.cnf ] ; then
	$mysqlPrefix/bin/mysqldump --login-path=admin --extended-insert \
		--compress --add-drop-table --extended-insert --flush-logs --lock-tables \
		--verbose -A | gzip -c > $backupdir/dbexport.$EXT.gz
	else
	$mysqlPrefix/bin/mysqldump -u mysql -p$PRIV_PASS --extended-insert \
		--compress --add-drop-table --extended-insert --flush-logs --lock-tables \
		--verbose -A | gzip -c > $backupdir/dbexport.$EXT.gz
	fi
	;;

	14) # repair tables
	if [ " $mysqlPrefix" = " " ] ; then
		echo "MySQL Installation Prefix directory not specified" 1>&2
		usage 1
	fi
	repair_tables
	;;

	15) # reports
	# Check that we're a privileged user
	[ `id -u` = 0 ] || exit 4
	report $report_option
	;;

	16) # create_qscanq
	# Check that we're a privileged user
	[ `id -u` = 0 ] || exit 4
	if [ " $servicedir" = " " ] ; then
		echo "Supervise Directory not specified" 1>&2
		usage 1
	fi
	echo "Creating qscanq virus scanner, Service $servicedir"
	create_qscanq $servicedir
	;;

	17) # --clamd
	# Check that we're a privileged user
	[ `id -u` = 0 ] || exit 4
	if [ " $servicedir" = " " ] ; then
		echo "Supervise Directory not specified" 1>&2
		usage 1
	elif [ " $clamdPrefix" = " " ] ; then
		echo "clamd Installation Prefix directory not specified" 1>&2
		usage 1
	elif [ " $mysysconfdir" = " " ] ; then
		echo "sysconfdir not specified" 1>&2
		usage 1
	fi
	echo "Creating Virus Scanner Service ClamdPrefix $clamdPrefix, Service $servicedir, Sysconf $sysconfdir"
	create_clamd $clamdPrefix $servicedir $mysysconfdir
	;;

	18) # create_poppass
	# Check that we're a privileged user
	[ `id -u` = 0 ] || exit 4
	if [ " $poppass_port" = " " ] ; then
		echo "poppass PORT not specified" 1>&2
		usage 1
	elif [ " $servicedir" = " " ] ; then
		echo "Supervise Directory not specified" 1>&2
		usage 1
	elif [ " $password_cmd" = " " ] ; then
		echo "Setpassword Command not specified" 1>&2
		usage 1
	elif [ $poppass_port -lt 1 ] ; then
		echo "POP3 PORT should be a positive number" 1>&2
		usage 1
	elif [ $use_ssl -eq 1 -a " $certfile" = " " ] ; then
		echo "--ssl option given and Certficate not specified" 1>&2
		usage 1
	fi
	echo "Creating poppass Listener Port $poppass_port, Service $servicedir use_ssl=$use_ssl"
	create_poppass "$servicedir" "$poppass_port" "$password_cmd" "$use_ssl"
	;;

	19) # create_svscan
	# Check that we're a privileged user
	[ `id -u` = 0 ] || exit 4
	if [ " $servicedir" = " " ] ; then
		echo "Supervise Directory not specified" 1>&2
		usage 1
	fi
	echo "Creating svscan log Service Service $servicedir"
	create_svscan $servicedir $svscan_init_cmd
	;;

	20) # create_pwdlookup service
	# Check that we're a privileged user
	[ `id -u` = 0 ] || exit 4
	if [ " $servicedir" = " " ] ; then
		echo "Supervise Directory not specified" 1>&2
		usage 1
	elif [ " $socket_path" = " " ] ; then
		echo "socket path not specified" 1>&2
		usage 1
	elif [ " $thread_count" = " " ] ; then
		echo "Thread Count not specified" 1>&2
		usage 1
	elif [ " $timeout" = " " ] ; then
		echo "Listen Timeout not specified" 1>&2
		usage 1
	elif [ " $mysql_host" = " " ] ; then
		echo "MySQL Host not specified" 1>&2
		usage 1
	elif [ " $mysql_user" = " " ] ; then
		echo "MySQL User not specified" 1>&2
		usage 1
	elif [ " $mysql_pass" = " " ] ; then
		echo "MySQL Passwd not specified" 1>&2
		usage 1
	elif [ " $mysql_port" = " " -a " $mysql_socket" = " " ] ; then
		echo "MySQL Port/Socket not specified" 1>&2
		usage 1
	fi
	echo "Creating pwdLookup Daemon on socket $socket_path, Service $servicedir, Threads $thread_count"
	create_pwdlookup "$socket_path" "$thread_count" "$timeout" "$servicedir" "$mysql_host" "$mysql_user" \
	"$mysql_pass" "$mysql_port" "$mysql_socket"
	;;

	21) # dump config
	if [ " $servicedir" = " " ] ; then
		echo "Supervise Directory not specified" 1>&2
		usage 1
	fi
	# Check that we're a privileged user
	[ `id -u` = 0 ] || exit 4
	dump_config "$servicedir" "$cntrldir"
	;;

	22) # create_greylist
	# Check that we're a privileged user
	[ `id -u` = 0 ] || exit 4
	if [ " $servicedir" = " " ] ; then
		echo "Supervise Directory not specified" 1>&2
		usage 1
	fi
	create_greylist "$servicedir" "$grey_port" "$min_resend_min" " $resend_win_hr" "$timeout_days" "$context_file" "$save_interval" "$hash_size" "$whitelist" "$use_greydaemon"
	;;

	23) # create_qmtp
	# Check that we're a privileged user
	[ `id -u` = 0 ] || exit 4
	if [ " $servicedir" = " " ] ; then
		echo "Supervise Directory not specified" 1>&2
		usage 1
	elif [ " $qmtp_port" = " " ] ; then
		echo "QMTP PORT not specified" 1>&2
		usage 1
	elif [ $qmtp_port -lt 1 ] ; then
		echo "QMTP PORT should be a positive number" 1>&2
		usage 1
	fi
	if [ " $qbase" = " " ] ; then
		echo "Queue Directory not specified" 1>&2
		usage 1
	elif [ " $qcount" = " " ] ; then
		echo "Queue Count not specified" 1>&2
		usage 1
	elif [ " $qstart" = " " ] ; then
		echo "Start Queue Number not specified" 1>&2
		usage 1
	elif [ $qcount -lt 1 ] ; then
		echo "No of Queues should be a positive number" 1>&2
		usage 1
	elif [ $qstart -lt 1 ] ; then
		echo "Start Queue Number should be a positive number" 1>&2
		usage 1
	fi
	echo "Creating QMTP Listener Port $qmtp_port, Service $servicedir, Queue Base $qbase, Queue Count $qcount, Queue Start $qstart"
	create_qmtp_or_qmqp "qmtpd" "$qbase" "$qcount" "$qstart" "$servicedir" "$qmtp_port"
	;;

	24) # create_qmqp
	# Check that we're a privileged user
	[ `id -u` = 0 ] || exit 4
	if [ " $servicedir" = " " ] ; then
		echo "Supervise Directory not specified" 1>&2
		usage 1
	elif [ " $qmqp_port" = " " ] ; then
		echo "QMQP PORT not specified" 1>&2
		usage 1
	elif [ $qmqp_port -lt 1 ] ; then
		echo "QMQP PORT should be a positive number" 1>&2
		usage 1
	fi
	if [ " $qbase" = " " ] ; then
		echo "Queue Directory not specified" 1>&2
		usage 1
	elif [ " $qcount" = " " ] ; then
		echo "Queue Count not specified" 1>&2
		usage 1
	elif [ " $qstart" = " " ] ; then
		echo "Start Queue Number not specified" 1>&2
		usage 1
	elif [ $qcount -lt 1 ] ; then
		echo "No of Queues should be a positive number" 1>&2
		usage 1
	elif [ $qstart -lt 1 ] ; then
		echo "Start Queue Number should be a positive number" 1>&2
		usage 1
	fi
	echo "Creating QMQP Listener Port $qmqp_port, Service $servicedir, Queue Base $qbase, Queue Count $qcount, Queue Start $qstart"
	create_qmtp_or_qmqp "qmqpd" "$qbase" "$qcount" "$qstart" "$servicedir" "$qmqp_port"
	;;

	25) # create_queuedef
	# Check that we're a privileged user
	[ `id -u` = 0 ] || exit 4
	if [ " $queuedef" = " " ] ; then
		echo "queue environment directory not specified" 1>&2
		usage 1
	elif [ " $qbase" = " " ] ; then
		echo "Queue Directory not specified" 1>&2
		usage 1
	elif [ " $qcount" = " " ] ; then
		echo "Queue Count not specified" 1>&2
		usage 1
	elif [ " $qstart" = " " ] ; then
		echo "Start Queue Number not specified" 1>&2
		usage 1
	elif [ $qcount -lt 1 ] ; then
		echo "No of Queues should be a positive number" 1>&2
		usage 1
	elif [ $qstart -lt 1 ] ; then
		echo "Start Queue Number should be a positive number" 1>&2
		usage 1
	fi
	case "$dkverify_option" in
		dkim|dk|both)
		;;
		none|"")
		;;
		*)
		echo "invalid --dkverify=$dkverify_option" 1>&2
		usage 1
		;;
	esac
	case "$dksign_option" in
		dkim|dk|both)
		if [ " $private_key" = " " ] ; then
			echo "--private_key not specfied" 1>&2
			usage 1
		fi
		;;
		none|"")
		;;
		*)
		echo "invalid --dksign=$dksign_option" 1>&2
		usage 1
		;;
	esac
	echo "Creating queue envdir $queuedef"
	create_queuedef "$qbase" "$qcount" "$qstart" "$queuedef"
	;;

	26) # crete_delivery
	# Check that we're a privileged user
	[ `id -u` = 0 ] || exit 4
	if [ " $servicedir" = " " ] ; then
		echo "Supervise Directory not specified" 1>&2
		usage 1
	elif [ " $queue_ident" = " " ] ; then
		echo "Queue IDENT not specified" 1>&2
		usage 1
	fi
	if [ " $qbase" = " " ] ; then
	echo "Queue Directory not specified" 1>&2
		usage 1
	elif [ " $qcount" = " " ] ; then
		echo "Queue Count not specified" 1>&2
		usage 1
	elif [ " $qstart" = " " ] ; then
		echo "Start Queue Number not specified" 1>&2
		usage 1
	elif [ $qcount -lt 1 ] ; then
		echo "No of Queues should be a positive number" 1>&2
		usage 1
	elif [ $qstart -lt 1 ] ; then
		echo "Start Queue Number should be a positive number" 1>&2
		usage 1
	fi
	case "$dkverify_option" in
		dkim|dk|both)
		;;
		none|"")
		;;
		*)
		echo "invalid --dkverify=$dkverify_option" 1>&2
		usage 1
		;;
	esac
	case "$dksign_option" in
		dkim|dk|both)
		if [ " $private_key" = " " ] ; then
			echo "--private_key not specfied" 1>&2
			usage 1
		fi
		;;
		none|"")
		;;
		*)
		echo "invalid --dksign=$dksign_option" 1>&2
		usage 1
		;;
	esac
	echo "Creating delivery only $qcount queues"
	if [ $use_starttls -ne 0 -o $use_ssl -ne 0 ] ; then
		create_delivery "$qbase" "$qcount" "$qstart" "$servicedir" "$queue_ident" "$routes" 1 $utf8
	else
		create_delivery "$qbase" "$qcount" "$qstart" "$servicedir" "$queue_ident" "$routes" 0 $utf8
	fi
	;;

	27) # create_udplogger
	[ `id -u` = 0 ] || exit 4
	if [ " $servicedir" = " " ] ; then
		echo "Supervise Directory not specified" 1>&2
		usage 1
	elif [ " $udp_port" = " " ] ; then
		echo "udplogger PORT not specified" 1>&2
		usage 1
	fi
	create_udplogger "$udp_port" "$servicedir"
	;;

	28) # create_fifologger
	[ `id -u` = 0 ] || exit 4
	if [ " $servicedir" = " " ] ; then
		echo "Supervise Directory not specified" 1>&2
		usage 1
	elif [ " $logfilter" = " " ] ; then
		echo "fifo path not specified" 1>&2
		usage 1
	fi
	echo "Creating fifologger $logfilter in $servicedir"
	create_fifologger $logfilter $servicedir
	;;

	29) # create mrtg
	[ `id -u` = 0 ] || exit 4
	if [ " $servicedir" = " " ] ; then
		echo "Supervise Directory not specified" 1>&2
		usage 1
	elif [ " $htmldir" = " " ] ; then
		echo "your web html dir not specified" 1>&2
		usage 1
	fi
	echo "Creating indimail mrtg $hmtldir in $servicedir"
	create_mrtg $htmldir $servicedir
	;;

	30) # tls certificate check
	[ `id -u` = 0 ] || exit 4
	if [ -z "$cert_file" ] ; then
		tls_cert_check
	else
		tls_cert_check $cert_file
	fi
	;;

	31) # enable service
	shift
	enable_service $*
	;;

	32) # disable service
	shift
	disable_service $*
	;;

	33) # create dane
	# Check that we're a privileged user
	[ `id -u` = 0 ] || exit 4
	if [ " $servicedir" = " " ] ; then
		echo "Supervise Directory not specified" 1>&2
		usage 1
	fi
	create_dane "$servicedir" "$dane_port" "$timeout_days" "$context_file" "$save_interval" "$hash_size" "$whitelist"
	;;

	34) # refresh services
	[ `id -u` = 0 ] || exit 4
	if [ " $servicedir" = " " ] ; then
		echo "Supervise Directory not specified" 1>&2
		usage 1
	fi
	refreshsvc $service
	;;

	35) # set norefresh service flag
	[ `id -u` = 0 ] || exit 4
	if [ " $servicedir" = " " ] ; then
		echo "Supervise Directory not specified" 1>&2
		usage 1
	fi
	norefreshsvc $service
	;;

	*)
	if [ " $option" = " " ] ; then
		echo "No Options Provided" 1>&2
		read key
	else
		echo "Invalid Option [$option]" 1>&2
	fi
	;;
esac

if [ ! " $prog_args" = " " ] ; then
	if [ " $nolog" = " " ] ; then
		if [ ! -d "$DESTDIR"$LOGDIR ] ; then
			/bin/mkdir -p "$DESTDIR"$LOGDIR
		fi
		echo "`date` $prog_args" >> "$DESTDIR"$LOGDIR/services.log
	fi
fi
exit 0
