### Copyright (C) 1995-97 Jesper K. Pedersen
### This program is free software; you can redistribute it and/or modify
### it under the terms of the GNU General Public License as published by
### the Free Software Foundation; either version 2 of the License, or
### (at your option) any later version.
###
### This program is distributed in the hope that it will be useful,
### but WITHOUT ANY WARRANTY; without even the implied warranty of
### MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
### GNU General Public License for more details.
###
### You should have received a copy of the GNU General Public License
### along with this program; if not, write to the Free Software
### Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

Save {
  set recipeCode ""
  set thisCmds {}
  set VAR 0; # variable counter
  set recipeCount 0
  forevery recipes {
    incr recipeCount
    set lastCmds $thisCmds
    set thisCmds {}

    print "\#\#\# Recipe number $recipeCount"
    if {$recipeName != ""} {
      print "\#\#\# Name: $recipeName"
    }
    if {$description != ""} {
      print "\#\#\#"
      foreach line [splitMessage $description] {
        print "\#\#\# $line"
      }
    }

    if {!$enable} {
      print "\#\#\# This recipe has been disabled!\n\n"
      continue
    }
    
    if {!$cont && $reply_act && !$forw_act && !$save_act && !$pipe_act} {
      set answer [tk_dialog .error "Warning" "with the recipe named \"$recipeName\", you will reply to the user, but you will not save or recieve the message yourself.  Maybe you should enable the continue button for this recipe.  Should I do it for you?" error 0 Yes No]
      if {$answer == 0} {
        set cont 1
      }
    }


    ### If extended diagnosticts is on, print the recipe name
    ### to the log file before each recipe.
    if {${general@extlog}} {
      if {$recipeName != ""} {
        print "RECIPE = \"\n----------------------------------------------------------------------\n$recipeName\n----------------------------------------------------------------------\n\""
      } else {
        print "RECIPE = \"\n----------------------------------------------------------------------\nrecipe number $recipeCount\n----------------------------------------------------------------------\n\""
      }
    }

    ##################################################
    ### calculate the conditions and flags
    ##################################################
    set flags ""
    set conds ""
    set preconds ""
    forevery conditions {
      ### Test cond_size here to optimize PageEnd
      if {![regexp {^[0-9]*$} $cond_size]} {
        if {$recipeName != ""} {
          error "In recipe named \"$recipeName\", is the size not a number!"
        } else {
          error "In recipe no. $recipeCount, is the size not a number!"
        }
      }

      ### size
      if {$cond_size != "" } {
        if {$cond_sizetp(index) == 0} {
          if {$cond_neg} {
            append conds "* > $cond_size\n"
          } else {
            append conds "* < $cond_size\n"
          }
        } else {
          ### size in lines
          if {$preconds == ""} {
            set preconds "MATCH = 1\n"
          }
          append preconds ":0B\n"
          append preconds "* MATCH ?? 1\n"
          if {!$cond_neg} {
            append preconds "* -${cond_size}^0\n"
            append preconds "* 1^1 ^(.|\$)\n"
          } else {
            append preconds "* ${cond_size}^0\n"
            append preconds "* -1^1 ^(.|\$)\n"
          }
          append preconds "{\n"
          append preconds "\tMATCH = 0\n"
          append preconds "}\n"
        }
      }

      if {$cond_neg} {
        set n "* !"
      } else {
        set n "* "
      }

      ### Header
      if {$cond_head != ""} {
        switch $cond_head {
          "Body of message" {
            append flags B
            append conds "$n$cond_pattern\n"
          }
          "Sendmail from" {
            append flags H
            append conds "${n}^from +$cond_pattern\n"
          }
          TO -
          FROM_DAEMON -
          FROM_MAILER {
            append flags H
            append conds "$n^$cond_head$cond_pattern\n"
          }
          default {
            append flags H
            append conds "$n^$cond_head: *$cond_pattern\n"
          }
        }
      } else {
        if {$cond_pattern != ""} {
          error "In recipe named \"$recipeName\": No header field given, though information exists in the pattern field!"
        }
      }

      ## output from command
      set VARS ""
      set pipe $cond_com_file
      if {$VARS != ""} {
        print $VARS
      }
      set pipe [string trim $pipe "\n\t "]
      if {$pipe != ""} {
        regsub -all -- "\n" $pipe "; \\\n\t" head
        if {!$cond_exit_header && !$cond_exit_body} {
          set head "$__system(mailhost,cat) - > /dev/null; $head"
        }
        if {$cond_exit_header || !$cond_exit_body} {
          append flags H
        } else {
          append flags B
        }
        append conds "$n? $head\n"
      }
    }


    ##################################################
    ### Now print the recipe header and conditions
    ##################################################
    if {$preconds != ""} {
      print $preconds\n
    }
    
    if {$cont} {set c cw} else {set c ""}
    if {!$reply_act && !$forw_act && !$save_act && !$pipe_act &&
        ($predesigned_filter_act || $handmade_filter_act)} {
      set c ""
    }
    print ":0$c$flags"
    if {$preconds != ""} {
      print "* MATCH ?? 1"
    }
    if {$conds != ""} {
      print [string range $conds 0 [expr [string length $conds]-2]]
    }
    
    ### start the action part
    if {$act_usePrev && $recipeCount == 1} {
      error "You can not set \"Use previous command\" on the first recipe."
    }


    print "{"

    ##################################################
    ###                  Backup
    ##################################################
    if {[set backup@delivered(index)] == 0 || $backupThisOne} {
      print "\t\#\#\# Backup delivered mail"
      print "\t:0cw"
      print "\t{"

      ### create the direcory if it doesn't exists.
      print "\t\t\#\#\# test if the directory exists"
      print "\t\tFILE = [convertTilde ${backup@delivered_file}]"
      print "\t\tFILE = `$__system(mailhost,echo) \$FILE | $__system(mailhost,sed) -e 'y/ /_/'`"
      print "\t\tDIR = `$__system(mailhost,dirname) \$FILE`"
      print "\t\t:0 icw"
      print "\t\t* !? test -d \$DIR"
      print "\t\t| $MODULEPATH/mkdirhier \$DIR\n"
      
      print "\t\t:0hf"
      if {$recipeName != ""} {
        print \
          "\t\t| $__system(mailhost,formail) -i 'X-deliveredBy:[protect $recipeName]'"
      } else {
        print "\t\t| $__system(mailhost,formail) -i 'X-deliveredBY:No. $recipeCount'"
      }
      print "\t\t:0:"
      if {$__system(mailhost,gzip) != "" && ${backup@delivered_gzip}} {
        print "\t\t| $__system(mailhost,gzip) >> \$FILE.gz"
      } else {
        print \t\t\$FILE\n
      }
      print "\t}"
    }

    ##################################################
    ###        use previous commands
    ##################################################
    if {$act_usePrev} {
      print $lastCmds
    }

    ##################################################
    ###                  Filter
    ##################################################
    if {$predesigned_filter_act} {
      printSave "\t\#\#\# Predesigned filter command"

      ### Add headers
      forevery filter_appHeader {
        switch $filter_exists(index) {
          0 {set flag "-I"}
          1 {set flag "-a"}
          2 {set flag "-i"}
          3 {set flag "-A"}
        }
        set VARS ""
        set head $filter_file
        if {$VARS != ""} {
          printSave $VARS
        }
        unset VARS
        printSave "\t:0hf"
        printSave "\t| $__system(mailhost,formail) $flag\"$filter_headname $head\""
      }
      
      ### Delete Headers
      forevery filter_delheads {
        printSave "\t:0hf"
        printSave "\t| $__system(mailhost,formail) -I\"$filter_delhead\""
      }

      ##############################
      #### Remove Signatures
      ##############################
      if {$filter_removeSig} {
        ### check wether the directory exists.
        set dir $filter_sigDir
        if {![file exists $dir]} {
          set answer [tk_dialog .error "Directory does not exixt" "The directory \"$dir\" does not exists. It is crucial for procmail that this directory exist, shall I create it?" error 0 Yes No]
          if {$answer == 0} {
            createDir $dir
          }
        }
        set dir [file dirname $filter_logfile]
        if {![file exists $dir]} {
          set answer [tk_dialog .error "Directory does not exixt" "The directory \"$dir\" does not exists. It is crucial for procmail that this directory exist, shall I create it?" error 0 Yes No]
          if {$answer == 0} {
            createDir $dir
          }
        }
        set log 0
        if {$filter_level1} {incr log 1}
        if {$filter_level2} {incr log 2}
        if {$filter_level3} {incr log 4}
        if {$filter_level4} {incr log 8}
        
        printSave "\t\#\#\# Remove Signature"
        printSave "\tFROM = `$__system(mailhost,formail) -zx From:`"
        printSave "\tLETTERID = `$__system(mailhost,formail) -zx Message-ID:`"
        printSave "\t:0Bbf:lock"
        printSave "\t* !^-----BEGIN PGP SIGNED MESSAGE-----$"
        printSave "\t| $MODULEPATH/filter $filter_sigDir $log $filter_logfile \$LETTERID \$FROM"
      }
    }
    
    if {$handmade_filter_act} {
      printSave "\t\#\#\# Handmade filter command"

      ### filter header
      set VARS ""
      set com $filter_comHead_file
      if {$VARS != ""} {
        printSave $VARS
      }
      unset VARS
      set com [string trim $com " \\\n\t"]
      if {$com != ""} {
        regsub -all -- "\n" $com "; \\\n\t" head
        if {$filter_edit_header(index) == 0} {
          set head "$__system(mailhost,cat) - > /dev/null; $head"
        }
        printSave "\t\#\#\# Pipe header through a filter"
        printSave "\t:0hf:"
        printSave "\t| $head"
      }
      
      ### filter body
      set VARS ""
      set com $filter_comBody_file
      if {$VARS != ""} {
        printSave $VARS
      }
      unset VARS
      set com [string trim $com " \\\n\t"]
      if {$com != ""} {
        regsub -all -- "\n" $com "; \\\n\t" body
        if {$filter_edit_body(index) == 0} {
          set body "$__system(mailhost,cat) - > /dev/null; $body"
        }
        printSave "\t\#\#\# Pipe body through a filter"
        printSave "\t:0bf:"
        printSave "\t| $body"
      }
    }
    


    ##################################################
    ###                    reply
    ##################################################
    if {$reply_act} {
      set VARS ""
      set mes [protectForQuoting $reply_message_file]
      if {$VARS != ""} {
        printSave $VARS
      }
      if {$mes == ""} {
        error "Message in reply is empty!"
      }
      printSave "\t\#\#\# Reply to mail"
      if {$reply_period(index) != 0} {
        printSave "\tUSER = `$__system(mailhost,formail) -zx From:`"
        printSave "\t:0ciW:lock"
      } else {
        printSave "\t:0c"
      }
      printSave "\t* !^FROM_DAEMON"
      printSave "\t* !^X-Loop: ${general@loginName}"

      ### test if the person already has got a reply
      if {$reply_period(index) == 1} {
        printSave "\t| $MODULEPATH/logcheck ${general@mailDir}/$reply_log once \$USER"
      } elseif {$reply_period(index) == 2} {
        printSave "\t| $MODULEPATH/logcheck ${general@mailDir}/$reply_log $reply_howOld \$USER"
      }
      if {$reply_period(index) != 0} {
        printSave "\n\t:0 ehc"
      }

      ### now write the actual message 
      printSave "\t|($__system(mailhost,formail) -rA\"Precedence: junk\"\\"
      printSave "\t-A\"X-Loop: ${general@loginName}\";\\"
      foreach line [split $mes \n] {
        printSave "\t$__system(mailhost,echo) \"$line\";\\"
      }
      if {$reply_sig} {
        printSave "\t$__system(mailhost,cat) [convertTilde $reply_sigfile] -;\\"
      }
      if {$reply_advertisment} {
        printSave "\t$__system(mailhost,echo) \"---------\";\\"
        printSave "\t$__system(mailhost,cat) $MODULEPATH/TDG-advertisment -;\\"
      }
      printSave "\t) | \$SENDMAIL -oi -t\n"
    }
    ##################################################
    ###                    forward
    ##################################################
    if {$forw_act} {
      set forws ""
      forevery forwards {
        append forws " $forward"
      }
      if {$forws != {}} {
        printSave "\t\#\#\# Forward mail"
        printSave "\t:0c"
        printSave "\t* ! ^X-loop: ${general@loginName}"
        printSave "\t{"

        ### Add loopback header
        printSave "\t\t:0hf"
        printSave "\t\t| $__system(mailhost,formail) -A\"X-loop: ${general@loginName}\""
        
        printSave "\t\t:0"
        printSave "\t\t! $forws"
        printSave "\t}\n"
      }
    }

    ##################################################
    ###                    save
    ##################################################
    if {$save_act} {
      printSave "\t\#\#\# Save to file"
      forevery save_files {
        ### First write all constants
        set VARS ""; # list of vars to set
        set file [convertTilde $save_file]
        if {$VARS != ""} {
          printSave $VARS
        }
        unset VARS

        ### create the direcory if it doesn't exists.
        printSave "\t\#\#\# test if the directory exists"
        printSave "\tFILE = [convertTilde $file]"
        printSave "\tFILE = `$__system(mailhost,echo) \$FILE | $__system(mailhost,sed) -e 'y/ /_/'`"
        printSave "\tDIR = `$__system(mailhost,dirname) \$FILE`"
        printSave "\t:0 icw"
        printSave "\t* !? test -d \$DIR"
        printSave "\t| $MODULEPATH/mkdirhier \$DIR\n"

        printSave "\t:0c:"
        if {$__system(mailhost,gzip) != "" && $save_gzip} {
          printSave "\t|$__system(mailhost,gzip) >> \$FILE.gz\n"
        } else {
          printSave \t\$FILE\n
        }
      }
    }
    
    
    ##################################################
    ###                Pipe
    ##################################################
    if {$pipe_act} {
      set VARS ""
      set pipe [string trimright $pipe_pipe_file]
      if {$VARS != ""} {
        printSave $VARS
      }
      if {$pipe != ""} {
        set flags ":0c"
        if {!$pipe_header && !$pipe_body} {
          append flags "i"
        }
        if {$pipe_body} {
          append flags "b"
        }
        if {$pipe_header || !$pipe_body} {
          append flags "h"
        }
        if {$pipe_lock} {
          append flags ":lock"
        }
        printSave "\t$flags"
        regsub -all -- "\n" $pipe "; \\\n\t" command
        printSave "\t|$command"
      }
    }

    ##################################################
    ### stop the action part
    ##################################################
    if {!($predesigned_filter_act || $handmade_filter_act) || $forw_act ||
        $pipe_act || $save_act || $reply_act}  {
      print "\t\#\#\# Now stop this action."
      if {$__system(mailhost,false) != ""} {
        print "\t:0i"
        print "\t| $__system(mailhost,false)"
      } else {
        print "\t:0"
        print "\t/dev/null"
      }
    }
    print "}\n\n"
  }

  ##################################################
  ### backup undelivered mail
  ##################################################
  if {${backup@undelivered}} {
    print "\#\#\# Backup of undelivered mail"

    ### create the direcory if it doesn't exists.
    print "\#\#\# test if the directory exists"
    print "FILE = [convertTilde ${backup@undelivered_file}]"
    print "FILE = `$__system(mailhost,echo) \$FILE | $__system(mailhost,sed) -e 'y/ /_/'`"
    print "DIR = `$__system(mailhost,dirname) \$FILE`"
    print ":0 icw"
    print "* !? test -d \$DIR"
    print "| $MODULEPATH/mkdirhier \$DIR\n"

    print ":0c:"
    if {$__system(mailhost,gzip) != "" && ${backup@undelivered_gzip}} {
      print "| $__system(mailhost,gzip) >> \$FILE.gz"
    } else {
      print \$FILE
    }
  }
#   print $recipeCode
}
