######################################################################
### sed scripts to extract the email address, it can handle the following
### blackie@imada.sdu.dk (Jesper Pedersen)
### Jesper Pedersen <blackie@imada.sdu.dk>
### blackie@imada.sdu.dk
######################################################################
set email_full {\
  -n -e '/^[^@]*@[^ ]* *(.*)/ {;s/^\([^@]*@[^ ]*\) *(.*)/\1/p;q;}' \
      -e '/.*<[^@]*@[^ >]*>/ {;s/.*<\([^@]*@[^ >]*\)>/\1/p;q;}'\
      -e '/[^@ ]*@[^ ]*/ s/\([^@ ]*@[^ ]*\)/\1/p'
}
set email_head {\
  -n -e '/^[^@]*@[^ ]* *(.*)/ {;s/^\([^@]*\)@[^ ]* *(.*)/\1/p;q;}' \
      -e '/.*<[^@]*@[^ >]*>/ {;s/.*<\([^@]*\)@[^ >]*>/\1/p;q;}'\
      -e '/[^@ ]*@[^ ]*/ s/\([^@ ]*\)@[^ ]*/\1/p'
  
}
set email_realname {\
  -n -e '/^[^@]*@[^ ]* *(.*)/ {;s/^[^@]*@[^ ]* *(\(.*\))/\1/p;q;}' \
      -e '/.*<[^@]*@[^ >]*>/ {;s/^ *\(.*\)<[^@]*@[^ >]*>/\1/p;q;}'\
}
set Headers {cc content-transfer-encoding content-type from precedence
  reply-to resent-from resent-sender subject sender to date}

proc fileTemplate {prefix includeHeaderOpt gzip type helpType text default} {
  global __system Headers

  ##################################################
  ###                    Time
  ##################################################
  Radio ${prefix}_timeInfo \
      -text "What Information"\
      -entries {AMPM Hour Minute Seconds}

  Header ${prefix}_timeHead\
      -text "Hour info"

  Radio ${prefix}_hourFormat\
      -text Format:\
      -entries {12 24}\
      -packLabel:side left

  CheckBox ${prefix}_zero\
      -text "Use Leading zero"

  FillOutElm ${prefix}_time\
      -text "Time information"\
      -entries ${prefix}_timeInfo ${prefix}_timeHead \
      ${prefix}_hourFormat ${prefix}_zero\
      -show "
         switch \$${prefix}_timeInfo(index) {
           0 {print {\[AMPM\]}}
           1 {print {\[Hour\]}}
           2 {print {\[Min\]}}
           3 {print {\[Sec\]}}
         }
      "\
      -save "
        print \"`$__system(mailhost,date) +%\"
        switch \[expand ${prefix}_timeInfo index\] {
          0 {print p}
          1 {
            switch \"\[expand ${prefix}_hourFormat index\] \[expand ${prefix}_zero\]\" {
              {0 0} {print l}
              {0 1} {print I}
              {1 0} {print k}
              {1 1} {print H}
            }
          }
          2 {print M}
          3 {print S}
        }
        print \"`\"
      "\
      -change "
			  if {\$${prefix}_timeInfo(index) == 1} {
          Enable ${prefix}_timeHead ${prefix}_hourFormat ${prefix}_zero
	      } else {
          Disable ${prefix}_timeHead ${prefix}_hourFormat ${prefix}_zero
        }
      "


  ##################################################
  ###         Help for Time
  ##################################################
  Help ${prefix}_timeInfo \
      "What sort of time information should be extracted?\n AMPM -"\
      "either AM or PM\n Hour - the current Hour\n Minute - the current"\
      "minute\n Seconds - the current seconds"
  Help ${prefix}_hourFormat\
      "Should we use the 12 hour or the 24 hour system?\n Ie. should 5 PM be"\
      "represented as 5 or 17."
  Help ${prefix}_time \
      "Here you may extract the \"current\" time"
  
  
  ##################################################
  ###                   Date
  ##################################################
  dateWidget $prefix

  FillOutElm ${prefix}_date\
      -text "Date information"\
      -entries ${prefix}_dateInfo ${prefix}_datel1 ${prefix}_digit \
      ${prefix}_datel2 ${prefix}_monthFormat ${prefix}_datel3\
      ${prefix}_dayFormat\
      -show "
			  switch \$${prefix}_dateInfo(index) {
          0 {print {\[Year\]}}
          1 {print {\[Month\]}}
          2 {print {\[Day\]}}
          3 {print {\[Week\]}}
        }
      "\
      -save "
        print \"`$__system(mailhost,date) +%\"
        switch \[expand ${prefix}_dateInfo index\] {
          0 {print \[lindex {y Y} \[expand ${prefix}_digit index\]\]}
          1 {print \[lindex {m b B} \[expand ${prefix}_monthFormat index\]\]}
          2 {print \[lindex {A a w e} \[expand ${prefix}_dayFormat index\]\]}
          3 {print U}
        }
        print {`}
      "\
      -change "
        Disable ${prefix}_digit ${prefix}_monthFormat ${prefix}_dayFormat
	      Enable \[lindex \"${prefix}_digit ${prefix}_monthFormat ${prefix}_dayFormat ${prefix}_dateInfo\" \$${prefix}_dateInfo(index)\]
      "

  Help ${prefix}_date\
    "Here you may extract information about the \"current\" day,"\
    "either as year, month, day, or week."


  ##################################################
  ###              Header
  ##################################################
  if {$includeHeaderOpt} {
    ComboBox ${prefix}_field \
        -text "Header field to extract"\
        -entries $Headers
    
    Line ${prefix}_line1
    CheckBox ${prefix}_address \
        -text "Is the header field an email address?"
    
    Radio ${prefix}_whichPart \
        -text "Which part of the email address should be extracted"\
        -entries {"whole email address" "email address without domain"\
                      "real name"}

    Entry ${prefix}_alt \
        -text "Alternative to use if no real name was found"

    Line ${prefix}_line2

    ##################################################
    ###        Date
    ##################################################
    CheckBox ${prefix}_isdate \
      -text "Is the header field a date?"
    dateWidget ${prefix}2
    
    Window ${prefix}_formatDate -text "Format of date" -entries\
      ${prefix}2_dateInfo ${prefix}2_datel1 ${prefix}2_digit \
      ${prefix}2_datel2 ${prefix}2_monthFormat ${prefix}2_datel3\
      ${prefix}2_dayFormat

    Label ${prefix}_dateLabel -text "(" -textafter ")"
    Frame ${prefix}_dateFrame -entries ${prefix}_formatDate ${prefix}_dateLabel
		Entry ${prefix}_dateAlt -text "Text to use if date info not found"
    
    ##################################################
    Line ${prefix}_line3
    
    TextBox ${prefix}_pipe \
        -text "Pipe header value through pipe"
  
    FillOutElm ${prefix}_header \
      -text "Content of a header field"\
      -entries ${prefix}_field ${prefix}_line1 ${prefix}_address\
      ${prefix}_whichPart ${prefix}_alt ${prefix}_line2\
      ${prefix}_isdate ${prefix}_dateFrame ${prefix}_dateAlt ${prefix}_line3 ${prefix}_pipe\
        -show "
          print <\$${prefix}_field
          if {\$${prefix}_isdate} {
            print \$${prefix}_dateLabel
          }
          print >     
        "\
        -pageEnd "
          if {\$${prefix}_field == {}} {
            error {No value given to field!}
          }
          if {!\[string match \"*:\" \$${prefix}_field\]} {
            append ${prefix}_field \":\"
          }
        "\
        -change "
          if {\$changeElm == \"${prefix}_address\" && \$${prefix}_address} {
            set ${prefix}_isdate 0
          }
          if {\$changeElm == \"${prefix}_isdate\" && \$${prefix}_isdate} {
            set ${prefix}_address 0
          }
          if {\$changeElm == \"${prefix}_address\" || \$changeElm == \"${prefix}_isdate\"} {
            eval \[pick \$${prefix}_address Enable Disable\] ${prefix}_whichPart ${prefix}_alt
            eval \[pick \$${prefix}_isdate Enable Disable\] ${prefix}_formatDate ${prefix}_dateLabel
          }
          if {\$changeElm == \"${prefix}_whichPart\"} {
            if {\$${prefix}_whichPart(index) == 2} {
              Enable ${prefix}_alt
            } else {
              Disable ${prefix}_alt
            }
          }
          if {\[string first ${prefix}2 \$changeElm\] != -1 || \$changeElm == \"${prefix}_isdate\"} {
            Disable ${prefix}2_digit ${prefix}2_monthFormat ${prefix}2_dayFormat
     	      Enable \[lindex \"${prefix}2_digit ${prefix}2_monthFormat ${prefix}2_dayFormat ${prefix}2_dateInfo\" \$${prefix}2_dateInfo(index)\]
            set ${prefix}_dateLabel \[lindex \"Year Month Day Week\"  \$${prefix}2_dateInfo(index)\]
          }
        "\
        -save "
          global VAR VARS
          if {\[info exists VARS\]} {
         		incr VAR
            append VARS \"\tVAR\$VAR = \
              `$__system(mailhost,formail) -zx \[expand ${prefix}_field\]`\n\"
  				  if {\[expand ${prefix}_address\]} {
              switch \[expand ${prefix}_whichPart index\] {
                0 {append VARS \"\tVAR\$VAR = \
                  `$__system(mailhost,echo) \\\$VAR\$VAR |$__system(mailhost,sed) \$email_full`\n\"
                }
                1 {append VARS \"\tVAR\$VAR = \
                  `$__system(mailhost,echo) \\\$VAR\$VAR |$__system(mailhost,sed) \$email_head`\n\"
                }
                2 {append VARS  \"\tVAR\$VAR = \
                  `$__system(mailhost,echo) \\\$VAR\$VAR |$__system(mailhost,sed) \$email_realname\"
                   append VARS \" -e 's/.*/\$${prefix}_alt/p'`\n\"
                }
              }
            }
            if {\[expand ${prefix}_isdate\]} {
              set _res \"\tVAR\$VAR = `$__system(mailhost,date) --date \\\"\\\$VAR\$VAR\\\" +%\" 
	            switch \[expand ${prefix}2_dateInfo index\] {
  			        0 {append _res \[lindex {y Y} \[expand ${prefix}2_digit index\]\]}
        			  1 {append _res \[lindex {m b B} \[expand ${prefix}2_monthFormat index\]\]}
			          2 {append _res \[lindex {A a w e} \[expand ${prefix}2_dayFormat index\]\]}
      			    3 {append _res U}
			        }
              append VARS \$_res \"`\n\"
							append VARS \"\tVAR\$VAR = `$__system(mailhost,echo) \\\$VAR\$VAR | $__system(mailhost,sed) -e '/^\\\$/ {;s//\$${prefix}_dateAlt/;}'`\n\"
            }
            if {\$${prefix}_pipe != {}} {
              regsub -all -- \"\n\" (\$${prefix}_pipe) \"; \\\\\\n\\t\" com
              append VARS \"\tVAR\$VAR = `$__system(mailhost,echo) \\\$VAR\$VAR | \$com`\n\"
            }
					  print \\\$VAR\$VAR
          }
        "

    TextBox ${prefix}_command \
        -text Shell Command -width 60

    FillOutElm ${prefix}_com \
        -text "Output from command"\
        -entries ${prefix}_command\
        -pageend "
           if {\$${prefix}_command == {}} {
             error {No command!}
           }"\
        -show {print \[Command\]}\
        -save "
           global VAR VARS
           if {\[info exists VARS\]} {
         		 incr VAR
             regsub -all -- \"\n\" (\$${prefix}_command) \"; \\\\\\n\\t\" com
             append VARS \"\tVAR\$VAR = `\$com`\n\"
             print \\\$VAR\$VAR
           }"
    ##################################################
    ###  Help for extract header
    ##################################################
    if {$includeHeaderOpt} {
      Help ${prefix}_field\
          "Here you may select one of the fields in the header.  More header"\
          "fields exist than those listed here, so you may enter your own"
      
      Help ${prefix}_address\
          "If the header you have selected is an email address, and you"\
          "wish to extract just the email address (ie. not the name),"\
          "select this check box.  The email address format may look"\
          "like one of the following:\n Jesper Pedersen"\
          "<blackie@imada.sdu.dk>\n blackie@imada.ou.dk (Jesper Pedersen)\n"\
          "blackie@imada.sdu.dk"
      
      Help ${prefix}_whichPart\
          "How much of the email address do you wish to extract:\n 1) The"\
          "whole email address (ie blackie@imada.sdu.dk) or\n 2) Just the username"\
          "(ie. blackie)"
      
      Help ${prefix}_pipe\
          "If you are in a situation, where you wish to extract some"\
          "part of a header field, you may send it through a filter. This"\
          "filter is a program, which takes the header field at standard"\
          "input, and writes the part you wish selected on standard"\
          "output. Each line is appended to one long shell line, with a"\
          "semicolon between"
      
      Help ${prefix}_header\
          "With this element, you can select some part of a header field.  A"\
          "header field is a field in the header of each message.  All fields"\
          "start with it's name then a colon and then the value.  Examples of header"\
          "fields are To, From, Subject etc.  Note the header fields are"\
          "case insensitive."

      foreach elm "${prefix}_command ${prefix}_com" {
        Help $elm\
            "You may run a shell command to get information, that you wish"\
            "to use.  This shell command may read the header on standard"\
            "input.  Each line is concatenated to one long line, separated"\
            "with semicolons."
      }
    }

    ##################################################
    ###                    Size
    ##################################################
    Radio ${prefix}_size \
        -entries {
          "Size of message in bytes"
          "Lines in body (incl blanks)"
          "Lines in body (excl blanks)"
        }\
        -count 1

    FillOutElm ${prefix}_count \
        -entries ${prefix}_size\
        -text Size\
        -show {print \[Size\]}\
        -save "
          global VAR VARS
          if {\[info exists VARS\]} {
          incr VAR
  				  switch \$${prefix}_size(index) {
            0 {
              append VARS \"\t:0\n\"
              append VARS \"\t* 1^1>1\n\"
            }
            1 {
              append VARS \"\t:0B\n\"
              append VARS \"\t* 1^1 ^(.|\\\$)\n\"
            }
            2 {
              append VARS \"\t:0B\n\"
              append VARS \"\t* 1^1 ^.\n\"
            }
          }
          append VARS \"\t{\n\"
          append VARS \"\t\tVAR\$VAR = \\\$=\n\"
          append VARS \"\t}\n\"
          print \\\$VAR\$VAR
        }
      "
            

    ##################################################
    ###            help for size
    ##################################################
    Help ${prefix}_count\
        "Here you may extract information about the size of the message"\
        "either in bytes or in lines of the body."
    
    FillOut ${prefix}_file \
        -text $text\
        -tp $type\
        -entries ${prefix}_time ${prefix}_date ${prefix}_header\
        ${prefix}_com ${prefix}_count\
        -listbox:width 60\
        -default $default \
        -listbox:height 6
  } else {
    FillOut ${prefix}_file \
        -text $text\
        -entries ${prefix}_time ${prefix}_date\
        -listbox:width 60\
        -default $default
  }

  if {$gzip && $__system(mailhost,gzip) != ""} {
    CheckBox ${prefix}_gzip \
        -text "Keep file gziped"\
        -help \
        "If you select this option the file will be kept as a"\
        "compressed file.  This is very useful if it's just a backup, or"\
        "if from a mailling list with many messages per day.  It's"\
        "drawback is that most mail readers do not know how to read the"\
        "content of a compressed file, which means that you have to"\
        "uncompress the file every time you need to read a message from it"\
  }

  if {$helpType == "file"} {
    Help ${prefix}_file \
        "In this fillout element, you may specify a file name.  This"\
        "file name may be determined from the year, the month, and"\
        "sometimes even the value of some header fields.  If you do not"\
        "specify a full path, the filename will be relative to the"\
        "directory, that you specify on the \"General Setup\" page."
  } elseif {$helpType == "value"} {
    Help ${prefix}_file \
        "In this fillout element, you may specify the value for the"\
        "header.  This value may include information about the"\
        "current day/month/year or the value from other header fields."
  }
}
