#! /bin/bash
#
# exim-config, Copyright Pierre A. Humblet, 2003-2022.
#
# This file is part of the Cygwin port of exim.
# set -x
set -u
# ======================================================================
# Routine: getvalue
# Get a verified non-empty string in variable "value"
# Prompt with the first argument.
# The 2nd argument if not empty must be -s.
# ======================================================================
getvalue() {
  while true
    do
    if read $2 -p "$1 " value; then
      [ -n "$2" ] && echo 
      if [ -n "${value}" ]; then
          read $2 -p "Reenter: " verify
          [ -n "$2" ] && echo
          [ "${verify}" = "${value}" ] && break
      fi
    else
      echo -e "Quitting.\n"
      exit 1
    fi
  done
  echo
  return 0

} # === End of getvalue() === #

#############################
# Useful subroutine
#############################
request()
{
  while true
  do
    echo -en "$1 (yes/no) "
    if read answer; then
      if [ "${answer}" = "yes" ]; then
	return 0
      elif [ "${answer}" = "no" ]; then
        return 1
      fi
    else
      echo -e "Quitting.\n"
      exit 1
    fi
  done
}
#############################
# Useful subroutine
#############################
getperiod()
{
  while true
    do
    echo -n "Enter the period of the queue runner, in minutes: [15] "
    if read period; then
      if [ -z "${period}" ]; then 
        period=15
	return 0;
      elif echo "${period}" | grep -q '[^0-9]'; then
        echo "The period must be all digits."
      elif [ "${period}" -eq 0 ]; then
        echo "The period must be positive."
      else
        return 0
      fi
    else
      echo -e "Quitting.\n"
      exit 1
    fi
  done
}
#############################
# Useful subroutine
#############################
getcygenv()
{
  default=$*
  while true
    do
    echo -n "Enter the value of CYGWIN for the daemon: [${default}] "
    if read cygenv; then
      if [ -z "${cygenv}" ]; then 
	cygenv="${default}"
      fi
      failed=0
# No checks for now
#      for word in ${cygenv}
#	do
#	[ "$failed" = 0 ] &&
#	failed=1
#	echo "$word" | grep -q '\(no\)\?\(check_case:strict\)\|\(ntsec\)\|\(smbntsec\)\|\(traverse\)' &&
#	failed=0
#      done
#
      [ "$failed" = 0 ] && return
      echo "ERROR: Only [no] \"check_case:strict\" \"ntsec\" \"smbntsec\" \"traverse\" allowed."
    else
      echo -e "Quitting.\n"
      exit 1
    fi
  done
}

# ======================================================================
# Routine: check_mounts
# Issue a warning if a user mount matches an argument
# ======================================================================
check_mounts() {
  USERMOUNTS=$(mount | sed -ne 's%^.*\ on\ \(/.*\)\ type\ [^ ]*\ .*(\([^ ]*,\)\?user\(,[^ ]*\)\?).*$%\1%p')
  ret=0
  OLD_IFS=$IFS
  IFS=$'\n'
  for file in "$@"
    do
    for mount in ${USERMOUNTS}
      do
      if [ "$file" = "$mount" -o "${file#$mount\/}" != "${file}" ]
        then
        ret=1
        echo Warning: "$file" can be modified by user mount "$mount";
      fi
    done
  done
  IFS=$OLD_IFS
  return $ret
}

# ======================================================================
# Routine: get_temp_dir
# Returns a temporary directory
# ======================================================================

get_temp_dir() {
    for dir in "$TEMP" "$TMP" "/tmp" "$PWD" "$HOME"; do
        if [ -d "$dir" ] && [ -w "$dir" ]; then
            mytemp="$dir"
            return
        fi
    done
    echo "ERROR: Cannot find a writable temporary directory."
    mytemp=/tmp
} # === End of get_temp_dir() === #

# ==================================================================
# Routine: print_file_info
# Argument 1 is a file name, argument 2 suppresses printing
# Returns a code:
#  0 if is not a symlink, 1 if not exist, 2 if not exim, 3 if exim, 
#  4 if other alternative, 5 if exim alternative 
# ==================================================================
print_file_info() {
  local answer
  local offer=0
  local target
  if [ -L "$1" ]; then
    offer=2
    target="$(/bin/ls -l "$1" | sed -e 's/^.*-> *//')"
    if echo "$target" | grep -q ^/etc/alternatives; then
      offer=4 
      target="$(/bin/ls -l "$target" | sed -e 's/^.*-> *//')"
    fi
    answer="is a symbolic link to $target"
    if [ $offer -ge 4 ]; then
      answer="$answer via alternatives"
    fi 
    if [ "$(expr "$target" : '.*exim$' )" -gt 0 ]; then
      offer=$(( offer + 1 ))
    fi
  elif [ -d "$1" ]; then
    answer="is a directory"
  elif [ -e "$1" ]; then
    answer="exists but is not a symbolic link"
  else
    answer="does not exist"
    offer=1
  fi
  if [ -z "${2:-""}" ]; then
  	echo "Currently $1 $answer"
  fi
  return $offer
}

# ======================================================================
# Routine: create_user
# Create a privileged user on Windows 2003
# Returns the names in variable "win_username" and "cyg_username
# and the password in "password"
# ======================================================================
create_user() {
    SYSCONFDIR="/etc"
    first_account=""
    accounts=""
    
    echo
    echo "Finding or creating a privileged user."
    for win_username in cyg_server cron_server sshd_server
    do
      if net user "${win_username}" 1> /dev/null 2>&1; then
	  [ -z "${first_account}" ] && first_account="${win_username}"
	  accounts="${accounts}'${win_username}' "
      fi
    done
    if [ -n "${accounts}" ]; then
	echo "The following accounts were found: ${accounts}."
	win_username="${first_account}"
    else
	echo "No privileged account could be found."
	win_username="cyg_server"
    fi
    echo "This script plans to use account ${win_username}."
    if request "Do you want to use another privileged account name?"; then
	getvalue "Enter the other name:" ""
	win_username="${value}"
    fi
    echo
    
    username_in_sam=
    if net user "${win_username}" >/dev/null 2>&1 ; then
	missing=
	echo "Account $win_username already exists. Checking its privileges."
	for r in SeAssignPrimaryTokenPrivilege SeCreateTokenPrivilege SeServiceLogonRight; do
	    editrights -u "$win_username" -t "$r" && continue
	    missing="$missing $r"
	done
	if [ -n "$missing" ] ; then
	    echo "$win_username is missing $missing"
	    echo "You should choose or create another account."
	    return 1
	else
	    username_in_sam=old
            echo "INFO: $win_username is a valid privileged account."
	    for r in SeInteractiveLogonRight ; do
		editrights -u "$win_username" -t "$r" && \
		    echo "WARNING: $win_username has privilege $r. This is not recommended." 
	    done
	fi
    fi
    ret=0
    if [ -z "$username_in_sam" ]; then
      echo "Account ${win_username} needs a password. It must match"
      echo "the rules in force on your system."
      getvalue "Please enter the password:" "-s"
      password="${value}"
      echo
      net user "${win_username}" "${password}" /add /fullname:"Privileged server" \
          /comment:'<cygwin home="/var/empty" shell="/bin/false" />' > "${mytemp}/nu.$$" 2>&1 && 
	username_in_sam=new
      if [ "${username_in_sam}" != "new" ]; then
	echo "ERROR: Creating the account '${win_username}' failed!  Reason:"
	cat "${mytemp}/nu.$$"
        rm -f "${mytemp}/nu.$$"
        echo
	return 2
      else 
        rm -f "${mytemp}/nu.$$"
	echo "Account '${win_username}' has been created with password '${password}'."
	echo "If you change the password, please keep in mind to change the"
	echo "password for the exim service, too."
      fi
      echo
    
      passwd_has_expiry_flags=$(passwd -v | awk '/^passwd /{print ( $3 >= 1.5 ) ? "yes" : "no";}')
      if [ "${passwd_has_expiry_flags}" != "yes" ]
	then
	echo "WARNING: Account ${win_username} has password expiry set to system default."
	echo "Please check that password never expires or set it to your needs."
	echo
      elif ! passwd -e "${win_username}"
	then
	echo "WARNING: Setting password expiry for account ${win_username} failed!"
	echo "Please check that password never expires or set it to your needs."
	echo
      fi

      _admingroup="$( mkgroup -l | awk -F: '{if ( $2 == "S-1-5-32-544" ) print $1;}' )"
      if [ -z "${_admingroup}" ]; then
	echo "ERROR: Cannot obtain the Administrators group name from 'mkgroup -l'."
	echo
	ret=2
      elif net localgroup "${_admingroup}" | grep -Fixq "${win_username}"; then
	true
      else
	net localgroup "${_admingroup}" "${win_username}" /add > /dev/null 2>&1 && 
	username_in_admingroup=yes
	if [ "${username_in_admingroup}" != "yes" ]
	    then
	    echo "ERROR: Adding account ${win_username} to group ${_admingroup} failed!"
	    echo "Please add ${win_username} to group ${_admingroup} before"
	    echo "starting the smtp service!"
	    echo
	    ret=2
	fi
      fi
    
      if [ ! -x /usr/bin/editrights ]; then
	echo "WARNING: The 'editrights' program cannot be found or is not executable."
	echo"          Unable to insure that ${username} has the appropriate privileges."
	echo
      else
	editrights -a SeAssignPrimaryTokenPrivilege -u "${win_username}" &&
	editrights -a SeCreateTokenPrivilege -u "${win_username}" &&
	editrights -a SeDenyInteractiveLogonRight -u "${win_username}" &&
	editrights -a SeDenyNetworkLogonRight -u "${win_username}" &&
	editrights -a SeDenyRemoteInteractiveLogonRight -u "${win_username}" &&
	editrights -a SeIncreaseQuotaPrivilege -u "${win_username}" &&
	editrights -a SeServiceLogonRight -u "${win_username}" &&
	username_got_all_rights="yes"
	if [ "${username_got_all_rights}" != "yes" ]
	    then
	    echo "ERROR: Assigning the appropriate privileges to account '${win_username}' failed!"
	    echo
	    ret=2
	fi
      fi
    fi

    # Set the /Comment field, existing users may not have it  
    net user "${win_username}" /comment:'<cygwin home="/var/empty" shell="/bin/false" />' > "${mytemp}/nu.$$" 2>&1 &&
        comment_in_sam=yes
    if [ "${comment_in_sam}" != "yes" ]; then
        echo "ERROR: Setting the shell for '${win_username}' failed!  Reason:"
        cat "${mytemp}/nu.$$"
    fi
    rm -f "${mytemp}/nu.$$"
 

    new_entry="$(mkpasswd -l -u "${win_username}" |
                sed -e 's?\(^[^:]*:[^:]*:[^:]*:[^:]*:[^:]*:\).*?\1/var/empty:/bin/false?')"
    if [ -z "$new_entry" ]; then
       echo "ERROR: mkpasswd could not find the account $win_username"
       echo
       return 2
    fi
    cyg_username="${new_entry%%:*}"

    # If the passwd file exists, get the account sid and see if it's already there.
    # If so just adopt the old cygwin name and entry. Else add the new entry. 
    if [ -e  "${SYSCONFDIR}/passwd" ]; then    
        usersid=$(echo "$new_entry" | sed -e 's?^[^:]*:[^:]*:[^:]*:[^:]*:[^:]*\(,S[-0-9]*:\).*$?\1?')
        # old_entry can consist of several lines. cyg_username is from the first.    
    	old_entry="$(grep -i "^[^:]*:[^:]*:[^:]*:[^:]*:[^:]*${usersid}.*$" "${SYSCONFDIR}/passwd")"
	if [ -z "$old_entry" ]; then 
	   echo "${new_entry}" >> "${SYSCONFDIR}/passwd" || ret=1
        else
	   cyg_username="${old_entry%%:*}"
	   echo "INFO: There is already a user in ${SYSCONFDIR}/passwd for account ${win_username}."
        fi
    fi
    echo "INFO: The cygwin user name for account ${win_username} is ${cyg_username}."
    return "${ret}"
}

#############################
# Start
#############################

name="$(basename "$0")"
if [ "${name}" = "exim" ]; then
  echo "You must run exim-config before running exim."
  echo "Help is available from /usr/share/doc/Cygwin/exim-*.README and \"man exim\"."
  exit 127
elif [ "${name}" != "exim-config" ]; then
  echo "Unexpected script name $name"
  exit 1
fi

#############################
# Introduction
#############################

get_temp_dir
if [ -z "$mytemp" ]; then
  echo "ERROR: Cannot find a writable temporary directory"
  exit 1
fi

echo "************************************************"
echo "This script sets some key parameters of the exim"
echo "installation and starts the exim daemon."
echo "See the details in /usr/share/doc/Cygwin/exim-X-Y.README."
echo
ALIASES=/etc/aliases
# Get NT version
is_wow64=$(/usr/bin/uname | /usr/bin/grep -q 'WOW' && echo 1 || echo 0)

pingpath="$(cygpath -m --sysdir)/ping.exe"


SYSTEMUID=$(getent passwd S-1-5-18 | sed -e 's/[^:]*:[^:]*:\([0-9]*\):.*$/\1/')
if [ -z "$SYSTEMUID" ]; then
    echo "ERROR: The Local SYSTEM SID S-1-5-18 was not found in passwd. Aborting."
    exit
fi

ADMINSGID=$(getent group S-1-5-32-544 | sed -e 's/[^:]*:[^:]*:\([0-9]*\):.*$/\1/')
if [ -z "$ADMINSGID" ]; then
    echo "ERROR: The Local Administrators SID S-1-5-32-544 was not found in group. Aborting"
    exit
elif id -G | grep -qE '(^| )'"$ADMINSGID"'( |$)'
    then true
else
    echo
 #   echo "*************************************************************************************"
    echo "*************************************************************************************"
 #   echo    
    echo "WARNING: You are not currently in the Local Administrators group."
    echo "This script may fail to set file ownership and permissions, to create users,"
    echo "and to create or start services."
    echo
    echo "It is recommended that you execute the script from a shell running as Administrator"
 #   echo 
    echo "*************************************************************************************"
 #   echo "*************************************************************************************"
    if ! request "Do you want to continue?"; then
        exit
    fi
fi

#########################################
# Check if local usernames contain spaces
#########################################
mkpasswd -l | grep -o -e '^[^:]* [^:]*:[^:]*:[^:]*:[^:]*:'
if [ "$?" -eq 0 ]; then
  echo -e "\nWARNING: The usernames displayed above contain spaces."
  echo "    They cannot receive mail nor appear in ${ALIASES}."
  echo "    If necessary edit /etc/passwd and use names without spaces."
else
  echo "OK. No local usernames contain spaces."  
fi
echo

#############################
# Get the postmaster name
#############################
if grep -iqs \^postmaster: "${ALIASES}"; then
  echo "OK. The ${ALIASES} file contains \"postmaster\"."
else
  while true
    do
    echo -n "Who is the local postmaster? [${USER}] "
    if read postmaster; then
      [ -z "${postmaster}" ] && postmaster="$USER"
      if echo "${postmaster}" | grep -Fq " "; then
        echo "ERROR. The postmaster name cannot contain spaces."
      elif [ ! -z "$(getent passwd "${postmaster}")" ] ; then
        echo "postmaster: ${postmaster}" >> "${ALIASES}"
          chmod 0664 "${ALIASES}"
          echo "OK. The ${ALIASES} file was updated and given mode 0664."
          if [ -n "${SYSTEMUID}" -a -n "${ADMINSGID}" ]; then
            chown "${SYSTEMUID}:${ADMINSGID}" "${ALIASES}" &&
              echo "OK. The ${ALIASES} file has owner ${SYSTEMUID} and group $ADMINSGID."
          fi 
        break
      else
        echo "ERROR: User ${postmaster} does not exist."
      fi
    else
      echo -e "Quitting.\n"
      exit 1
    fi
  done
fi
echo 

#############################
# Create exim.conf
#############################

CONF=/etc/exim.conf
CONF_DEF=/etc/defaults/etc/exim.conf
setowner=
if [ ! -e "${CONF}" ]; then
  if cp "${CONF_DEF}" "${CONF}"; then
    echo "OK. ${CONF} created from ${CONF_DEF}."
    setowner=yes
  else
    echo "ERROR: Cannot create ${CONF} from ${CONF_DEF}."
    exit 1
  fi
  echo
fi

###########################
# Set the primary host name
###########################

# Check if primary_hostname is already defined
hostname="$(sed -ne '/^[ \t]*primary_hostname[ \t]*=/{
  s/[^=]*=[ \t]*\(.*\)/\1/p
  q
}' "${CONF}")"
if [ -z "${hostname}" ]; then
  echo "Looking for the fully qualified primary hostname."
  # Check if the fqhn can be found in one step
  host="$(uname -n)"
  # Make sure we can find the Windows ping 
  if [ ! -x "$pingpath" ]; then 
    echo "ERROR: $pingpath is not executable. Trying ping."
    pingpath=ping
  fi
  pingout="$(eval "$pingpath" -n 1 "${host}" 2> /dev/null)"
  # Get the fqhn and the ip address
  fqhn1="$(echo "${pingout}" | sed -ne '2{
    s/^Pinging \([^ ]*\).*/\1/
    y/ABCDEFGHIKLMNOPQRSTUVWXYZ/abcdefghiklmnopqrstuvwxyz/
    p
  }')"
  [ -z "${fqhn1}" ] && fqhn1="${host}"
  if request "Is it \"${fqhn1}\"?"; then
    echo "OK. Exim will autodiscover that name."
  else 
    address="$(echo "${pingout}" |  sed -ne '2s/.*\[\(.*\)\].*/\1/p')"
    # Get the fqhn from the ip address, excluding numerical forms.
    if [ -n "${address}" ]; then
      fqhn2="$("$pingpath" -n 1 -a "${address}" | sed -ne '2{
        s/^Pinging \([^ ]*\).*/\1/
        s/^[0-9.]*$//
        y/ABCDEFGHIKLMNOPQRSTUVWXYZ/abcdefghiklmnopqrstuvwxyz/
        p
       }')"
      if [ "${fqhn1}" != "${fqhn2}" -a -n "${fqhn2}" ]; then
        request "Is it \"${fqhn2}\"?" && hostname="${fqhn2}"
      fi
    fi
    while [ -z "${hostname}" ]
      do
      echo "Enter your fully qualified hostname."
      if read hostname; then
        if echo "${hostname}" | grep -q '[^a-zA-Z0-9.-]'; then
          echo "ERROR: The hostname contains invalid characters."
          hostname=""
        fi
      else 
        echo -e "Quitting.\n"
        exit 1
      fi	
    done
    # Look for the commented line '# primary_hostname = '
    if sed -e 's/^ *# *primary_hostname *= *$/primary_hostname = '"${hostname}"'/' "${CONF}" > "${mytemp}/exim.conf" && \
       grep -Fqm 1 "primary_hostname = ${hostname}" "${mytemp}/exim.conf" && \
       mv -f "${mytemp}/exim.conf" "${CONF}"
      then
      echo "OK. The hostname ${hostname} was saved in ${CONF}."
      setowner=yes
    else
      echo "WARNING: The script could not set the primary hostname in ${CONF}."
      echo "Please edit that file to set the primary hostname."
    fi
  fi
else
  echo "OK. The primary hostname ${hostname}"
  echo "    is already defined in ${CONF}."
fi
echo

###########################
# Verify ipv6 disabling
###########################

# Check ipv6 status
echo "INFO: This version of Exim supports ipv6."
disable_ipv6=$(sed -ne '/^[ \t]*disable_ipv6[ \t]*=/{
  s/[^=]*=[ \t]*\([a-z]*\)/\1/p
  q
}' "${CONF}")

if [ -z "${disable_ipv6}" ]; then
  echo "      To disable it insert \"disable_ipv6 = true\" in ${CONF}"
elif [ "${disable_ipv6}" = "true" -o "${disable_ipv6}" = "false" ]; then
  if [ "${disable_ipv6}" = "true" ]; then
    v6_switch=false
    v6_val=disabled	
  else   
    v6_switch=true
    v6_val=enabled
  fi	
  echo "      This feature is currently ${v6_val} in ${CONF}."
  if request "Do you want to change that setting?"; then 
    if
      sed -e '/^[ \t]*disable_ipv6[ \t]*=/ s/'"${disable_ipv6}"/"${v6_switch}"/ ${CONF} > "${mytemp}/exim.conf" &&
      mv -f "${mytemp}/exim.conf" "${CONF}"
    then
      echo "OK. The setting was changed."
      setowner=yes
    else
      echo "WARNING: The script could not set disable_ipv6 in ${CONF}."
      echo "         Please edit that file to set disable_ipv6 as you wish."
    fi
  fi
else
  echo "    disable_ipv6 is currently set to ${disable_ipv6}"
  echo "    You can edit ${CONF} to set it as you wish".
fi
echo

#####################################
# Verify exim.conf ownership and mode
####################################
if [ -n "${SYSTEMUID}" -a -n "${ADMINSGID}" ]; then
  if [ -z "${setowner}" ]; then
    ls="$(/bin/ls -ln ${CONF})" 
    case "$ls" in
      -r??r???-?\ *1\ *${SYSTEMUID}\ *${ADMINSGID}\ *)
        true;;
      *)
        echo -e "WARNING: The ${CONF} file has unusual mode, owner or group:\n${ls}"
	if request "Do you want to set them to standard values?"
          then
          setowner=yes
          else
          setowner=no
        fi;;
    esac
  fi
  if [ "${setowner}" = "yes" ]; then
    chmod 664 "${CONF}"
    chown "${SYSTEMUID}:${ADMINSGID}" "${CONF}" &&
      echo "OK. The mode and ownership of the ${CONF} file are now:" &&
      /bin/ls -l "${CONF}"
  fi
  if [ -n "${setowner}" ]; then
    echo
  fi
fi

##################################
# Look for /usr/bin/exim.exe
##################################
# A /usr/bin/exim.exe symlink will mask
# the /usr/bin/exim symlink.
# Its existence has been reported but is not explained.
# It is perhaps due to bad ln .exe magic.

if [ -L /usr/bin/exim.exe ]; then
   echo "WARNING: The symbolic link /usr/bin/exim.exe to $(/bin/ls -l /usr/bin/exim.exe | sed -e 's/^.*-> *//')"
   echo "    will be deleted as it masks the /usr/bin/exim symlink."
   rm -f /usr/bin/exim.exe && echo "OK. Done."
   echo
elif [ -e /usr/bin/exim.exe ] ; then
   echo "WARNING: The file /usr/bin/exim.exe masks the /usr/bin/exim symlink."
   echo "    In normal installations, delete that file."
   echo
fi

#####################
# Link exim if needed
#####################
# When exim points to exim-config, it returns 127
# This is the exit value reported by a shell when
# a program cannot be found or is not executable
exim=127
if [ -x /usr/bin/exim ]; then
  /usr/bin/exim 1> /dev/null 2>&1
  exim="$?"
fi

# Return 127 is explained above.
# 126 is when a file with executable permissions
# isn't really executable  
if [ "$exim" = 126 -o "$exim" = 127 ]; then
  for file in $(echo /usr/bin/exim-*.exe)
   do
   exim="${file}"
  done
  
  if [ -z "${exim}" ]; then
    echo "ERROR: Cannot find exim executable."
    exit 1
  elif ln -sf "${exim}" /usr/bin/exim; then
    echo "OK. /usr/bin/exim points to ${exim}."
  else
    echo "ERROR: Cannot point /usr/bin/exim to ${exim}" 
    exit 1
  fi
  echo
fi
    
######################################
# Alternatives links
######################################
echo "INFO: Some programs expect /usr/sbin/sendmail to handle mail."
print_file_info /usr/sbin/sendmail
ret=$?
dolink=
if [ $ret -eq 0 ]; then
  echo "If you wish it to be a link to exim, you'll need to do so by hand,"
  echo "preferably by using /usr/sbin/alternatives".
elif [ "$ret" -eq 5 ]; then  # Verify alternatives slaves are setup correctly
  echo "Checking that all the other alternatives links are still correct."
  for file in /usr/lib/sendmail /usr/bin/mailq /usr/bin/newaliases; do
     print_file_info $file 1 # 2nd arg suppresses printing
     [ "$?" -ne 5 ] && dolink=yes && echo "     $file alternatives slave is not setup properly"
  done
  if [ -z "$dolink" ]; then
    echo "OK."
  else
    echo "Links will now be set correctly."
  fi
fi
if [ "$ret" -eq 3 ]; then
  echo "/usr/sbin/sendmail points directly to exim. That is fine and can be left that way."
  echo "Cygwin is now also offering to use the alternatives package to create the links"
  echo "in a way that will support multiple MTAs in the distribution."
  request "Do you want to use alternatives to point /usr/sbin/sendmail to /usr/bin/exim ?" && dolink=yes 
elif [ "$ret" -ne 5 ]; then # Not already exim    
  echo "You now have the ability to link /usr/sbin/sendmail, as well as /usr/lib/sendmail,"
  echo "/usr/bin/mailq and /usr/bin/newaliases to /usr/bin/exim, using the alternatives package."
  echo "Doing so is not necessary for exim to function correctly, it is for the benefit of others."
  request "Do you want /usr/sbin/sendmail & al. to be links to /usr/bin/exim ?" && dolink=yes
fi
if [ "$dolink" = yes ]; then
  [ "$ret" -gt 1 -a "$ret" -lt 4 ] && rm -f /usr/sbin/sendmail
  command="--install /usr/sbin/sendmail mta /usr/bin/exim 0"
  
  echo "Other programs will also be linked to exim."

  echo "/usr/lib/sendmail is expected by some programs to point to a mailer"
  print_file_info /usr/lib/sendmail
  ret=$?
  if [ "$ret" -eq 0 ]; then
    echo "If you wish it to be a link to exim, you'll need to do so by hand,"
    echo "preferably by using /usr/sbin/alternatives".
  else
    [ "$ret" -gt 1 -a "$ret" -lt 4 ] && rm -f /usr/lib/sendmail
    command="$command --slave /usr/lib/sendmail mta-sendmail /usr/bin/exim" 
  fi

  echo "/usr/bin/mailq can point to exim to serves as "exim -bp" shortcut"
  print_file_info /usr/bin/mailq
  ret=$?
  if [ "$ret" -eq 0 ]; then
    echo "If you wish it to be a link to exim, you'll need to do so by hand,"
    echo "preferably by using /usr/sbin/alternatives".
  else
    [ "$ret" -gt 1 -a "$ret" -lt 4 ] && rm -f /usr/bin/mailq
    command="$command --slave /usr/bin/mailq mta-mailq /usr/bin/exim"
  fi

  echo "Some scripts expect /usr/bin/newaliases to point to a mailer"
  print_file_info /usr/bin/newaliases
  ret=$?
  if [ $ret -eq 0 ]; then
    echo "If you wish it to be a link to exim, you'll need to do so by hand,"
    echo "preferably by using /usr/sbin/alternatives".
  else
    [ "$ret" -gt 1 -a "$ret" -lt 4 ] && rm -f /usr/bin/newaliases
    command="$command --slave /usr/bin/newaliases mta-newaliases /usr/bin/exim"
  fi

  /usr/sbin/alternatives $command
  /usr/sbin/alternatives --set mta /usr/bin/exim
  echo -e "OK. Links created with alternatives."
fi 
echo


#############################
# Install a service?
#############################
service="job"
password=
echo "The exim daemon can run as a service or as a job. The latter is not recommended" 
if [ ! -e /usr/bin/cygrunsrv.exe ]; then 
  echo "WARNING: Download cygrunsrv to start the mailer daemon as a service."
  servtest=no
else
  cygrunsrv -Q exim > /dev/null 2>&1
  servtest=$?
fi
  
if [ "${servtest}" = "0" ]; then
  winUsername="$(cygrunsrv -VQ Exim | sed -n -e 's/^Account[ :]*//p')"
  echo "Exim is already installed as a service under account '${winUsername}'."
  otherpath="$(cygrunsrv -VQ Exim | sed -n -e 's/^Service[^(]*(\(.*\))$/\1/p')"
  if [ -n "$otherpath" ]; then
      echo "$otherpath is not for this instance of Cygwin." 
      echo "You must remove and reinstall the service to run in this instance."
  fi

  if request "Do you want to remove or reinstall it?"; then
    cygrunsrv -R exim && echo "OK. The exim service was removed." && otherpath=
  else
    service="service"
    servtest=no
  fi
  if [ -n "$otherpath" ]; then
    echo "Quitting due to other install."
    exit 1
  fi	

  domainname=${winUsername%\\*}   # Unused for now
  winUsername=${winUsername#*\\}  # Unused for now
  echo
fi

if [ "${servtest}" = "no" ]; then
  true
elif request "Do you want to install the exim daemon as a service?"; then
  if check_mounts /etc /bin /usr/bin /var/spool/mail /var/spool/exim /var/log/exim; then
    true
  else
    echo -e "WARNING: This could compromise your system."
    if request "Do you want to proceed?"; then
      true
    else
      exit 1;
    fi
  fi
  getperiod
  getcygenv

  winUsername=""
  cyg_username=""

  if [ ${is_wow64} = 1 ]; then
       echo  
       echo "To run multiple users, exim must change user context without knowing"
       echo "  the passwords."
       echo "You need to have or to create a privileged account."
       echo "  This script will help you do so."
       echo

	   create_user
	   c=$?
	   [ "$c" -eq 1 ] && continue
	   if [ "$c" -eq 2 ]; then 
	       echo "There was a serious problem creating a privileged user."
	       request "Do you want to proceed anyway?" || exit 1
	   fi
  fi

  for file in /var/log/exim/cygrunsrv_out.log /var/log/exim/cygrunsrv_err.log; do
       [ -f "${file}" ] && chgrp "${ADMINSGID}" "${file}" && chmod g+w "${file}"
  done
  if [ -n "${cyg_username}" ]; then
    if [ -z "${password}" ]; then
      getvalue "Please enter the password for user ${cyg_username}:" "-s"
      password=${value}
    fi

    if cygrunsrv -I exim -p /usr/bin/exim -e CYGWIN="${cygenv}" \
          -a "-bdf -q${period}m" -d "Exim" -f "Mail Transfer Agent" \
          -1 /var/log/exim/cygrunsrv_out.log -2 /var/log/exim/cygrunsrv_err.log \
	  --dep Tcpip -u "${cyg_username}" -w "${password}"
    then
      service="service"
    else
      service="off"
    fi
  else
    if cygrunsrv -I exim -p /usr/bin/exim -e CYGWIN="${cygenv}" \
          -a "-bdf -q${period}m" -d "Exim" -f "Mail Transfer Agent" \
          -1 /var/log/exim/cygrunsrv_out.log -2 /var/log/exim/cygrunsrv_err.log \
          --dep Tcpip
    then
      service="service"
    else
      service="off"
    fi
  fi
else
  echo "WARNING: If running exim as a job, it will stop when you log out."
fi
echo
 
#############################
# Start the daemon?
#############################
if ps -es | grep -Fqi 'exim-'; then
  echo "INFO: An exim process is already running."
elif [ "${service}" != "off" ]; then
  rm -f /var/spool/exim/exim-daemon.pid
  if request "Do you want to start the exim daemon as a ${service} now?"; then
    if [ "${service}" = "job" ]; then
      [ -z "${period}" ] && getperiod
      /usr/bin/exim -bd -q${period}m
    else
      cygrunsrv -S exim
    fi
    if [ $? -eq 0 ]; then
      echo "OK. The mail daemon is now accepting mail."
      echo "    You can test it with \"telnet localhost 25\"."
    else
      echo "ERROR: Could not start the daemon".
    fi
  elif [ "${service}" = "job" ]; then
    echo "OK. Type \"/usr/bin/exim -bd -q15m\" to start the exim daemon job."
  else
    echo "OK. Type \"cygrunsrv -S exim\" to start the exim daemon service."
    echo "    It will restart automatically at each reboot."
  fi
fi
echo

#############################
# Check exim user
#############################
if [ ! -z "$(getent passwd exim)" ] ; then
  echo "WARNING: An \"exim\" user exists."
  echo "This is a trouble prone feature, do not use it initially."
  echo -e "See requirements in /usr/share/doc/Cygwin/exim-X-Y.README.\n"
fi

#############################
# Cleanup
#############################
if [ -e /usr/local/bin/exim ]; then
  echo "You have an old installation of exim in /usr/local/bin."
  if request "Do you want to delete the executables? (recommended)"; then
    cd /usr/local/bin
    rm -f exim.exe exim exim-*.exe exim_dumpdb.exe exim_fixdb.exe exim_tidydb.exe exinext exiwhat
    rm -f exim_dbmbuild.exe exicyclog exigrep eximstats exiqsumm exim_lock.exe exim_checkaccess
    echo "OK."
  fi
  echo
fi

#############################
# End
#############################
echo "INFO: The exim log files are in /var/log/exim."
echo
echo "WARNING: The default file permissions are only suitable for a casual environment."
echo "    See /usr/share/doc/Cygwin/exim-X-Y.README for how to adjust them."
echo 
echo "When everything else fails,"
echo "    read /usr/share/doc/Cygwin/exim-X-Y.README,"
echo "    or look up the documentation on www.exim.org."
echo "Many happy mailings :)"
echo 
echo
