#!/bin/sh
# the next line restarts using wish \
exec wish "$0" "$@"

# This is the command, executed when playing via /dev/audio
# I use "playwave -r 7200" as my command
#
# playwave is comes with SDL_mixer
# The latest version of this library is available from:
# http://www.devolution.com/~slouken/SDL/projects/SDL_mixer/

#################### END OF CONFIGURABLE SECTION ##########################

set playPID "notyet"
set tkVoice 1
set font {Helvetica 14}

wm title . "tkvoice"


#   READ the user preferences into the program and
#   load in some defaults if the files are not found
proc startup {} {
# read in the paths information
global tkvoicedir voicedir voicein voiceout greeting
  set USERPREF ""
  set FILENAME tkvoicepaths.dat
  cd ~/
  if { [file isdirectory .tkvoice] == 0} {
       catch [exec mkdir .tkvoice] }
  cd ~/.tkvoice
   set datinfo [catch {set file [open $FILENAME r+]}]
   if {$datinfo == 0} {
     while {[gets $file string] >= 0} {
       append USERPREF $string
      }
    close $file} else {
   set USERPREF "/usr/local/tkvoice /var/spool/voice /incoming /messages greeting"
    }
   set tkvoicedir [lindex $USERPREF 0]
   set voicedir   [lindex $USERPREF 1]
   set voicein    [lindex $USERPREF 2]
   set voiceout   [lindex $USERPREF 3]
   set greeting   [lindex $USERPREF 4]

# read in the modem information
global MODEMTYPE MODEMCOMP
  set USERPREF ""
  set FILENAME tkvoicemodem.dat
   set datinfo [catch {set file [open $FILENAME r+]}]
   if {$datinfo == 0} {
     while {[gets $file string] >= 0} {
       append USERPREF $string
      }
    close $file} else {
   set USERPREF ""
    }
   set MODEMTYPE [lindex $USERPREF 0]
   set MODEMCOMP [lindex $USERPREF 1]

# read in the audio information
global playwave tkvoicedir
  set USERPREF ""
  set FILENAME tkvoiceplaywave.dat
   set datinfo [catch {set file [open $FILENAME r+]}]
   if {$datinfo == 0} {
     while {[gets $file string] >= 0} {
       append USERPREF $string
      }
    close $file} else {
   set USERPREF "$tkvoicedir/bin/wavplay -s 7200"
    }
   set playwave $USERPREF

global recordwave
  set USERPREF ""
  set FILENAME tkvoicerecwave.dat
   set datinfo [catch {set file [open $FILENAME r+]}]
   if {$datinfo == 0} {
     while {[gets $file string] >= 0} {
       append USERPREF $string
      }
    close $file} else {
   set USERPREF "$tkvoicedir/bin/wavrec -M -s 7200 -t 10"
    }
   set recordwave $USERPREF
global pvfsamples
  set USERPREF ""
  set FILENAME tkvoicepvfsamples.dat
   set datinfo [catch {set file [open $FILENAME r+]}]
   if {$datinfo == 0} {
     while {[gets $file string] >= 0} {
       append USERPREF $string
      }
    close $file} else {
   set USERPREF "7200"
    }
   set pvfsamples $USERPREF
}
# now run the startup proc or the rest of the script will bomb
startup

#   Process to save the paths preferences
proc savepaths {} {
global tkvoicedir voicedir voicein voiceout greeting
  set USERPREF ""
  set SAVENAME "tkvoicepaths.dat"
  cd ~/
  if { [file isdirectory .tkvoice] == 0} {
       catch [exec mkdir .tkvoice] }
  cd ~/.tkvoice
  if { [file isfile $SAVENAME] == 1} {
       catch [exec rm $SAVENAME] }
  catch [exec touch $SAVENAME]
  set file [open "$SAVENAME" r+]
  foreach x "$tkvoicedir $voicedir $voicein $voiceout $greeting" {
    append USERPREF "$x\ "
  }
  puts $file $USERPREF
  close $file
}

#   Process to save the Modem preferences
proc savemodem {} {
global MODEMTYPE MODEMCOMP
  set USERPREF ""
  set SAVENAME "tkvoicemodem.dat"
  cd ~/
  if { [file isdirectory .tkvoice] == 0} {
       catch [exec mkdir .tkvoice] }
  cd ~/.tkvoice
  if { [file isfile $SAVENAME] == 1} {
       catch [exec rm $SAVENAME] }
  catch [exec touch $SAVENAME]
  set file [open "$SAVENAME" r+]
  foreach x "$MODEMTYPE $MODEMCOMP" {
    append USERPREF "$x\ "
  }
  puts $file $USERPREF
  close $file
}

#   Process to save the audio command and arguments
# save the playwave command and arguements
proc saveaudio {} {
global playwave
  set USERPREF ""
  set SAVENAME "tkvoiceplaywave.dat"
  cd ~/
  if { [file isdirectory .tkvoice] == 0} {
       catch [exec mkdir .tkvoice] }
  cd ~/.tkvoice
  if { [file isfile $SAVENAME] == 1} {
       catch [exec rm $SAVENAME] }
  catch [exec touch $SAVENAME]
  set file [open "$SAVENAME" r+]
  foreach x "$playwave" {
    append USERPREF "$x\ "
  }
  puts $file $USERPREF
  close $file
global recordwave
  set USERPREF ""
  set SAVENAME "tkvoicerecwave.dat"
  cd ~/.tkvoice
  if { [file isfile $SAVENAME] == 1} {
       catch [exec rm $SAVENAME] }
  catch [exec touch $SAVENAME]
  set file [open "$SAVENAME" r+]
  foreach x "$recordwave" {
    append USERPREF "$x\ "
  }
  puts $file $USERPREF
  close $file
global pvfsamples
  set USERPREF ""
  set SAVENAME "tkvoicepvfsamples.dat"
  cd ~/.tkvoice
  if { [file isfile $SAVENAME] == 1} {
       catch [exec rm $SAVENAME] }
  catch [exec touch $SAVENAME]
  set file [open "$SAVENAME" r+]
  foreach x "$pvfsamples" {
    append USERPREF "$x\ "
  }
  puts $file $USERPREF
  close $file
}

proc play_audio {} {
global fnlist playwave voicedir playPID

  foreach i [.f.list curselection] {
    exec cat [lindex $fnlist $i] | rmdtopvf | pvftowav > $voicedir/tkvoice.tmp 2>/dev/null
    set playPID [eval exec $playwave $voicedir/tkvoice.tmp >/dev/null 2>&1 &] 
    set z [.f.list get $i]
    set l [string length $z]
    if {$l>19} {
      # set t [string range $t 2 $l ]
      set z [string range $z 2 $l ]
      set y "\x3E\x20"
      append t $y $z
      .f.list delete $i
      .f.list insert $i $t
    }
  }
}

proc stop_audio {} {
global playPID
    catch [exec kill -9 $playPID >/dev/null 2>&1]
}

proc record_g {} {
global recordwave voicedir voiceout greeting
    catch [exec ps -ef|grep artsd|grep -v grep|awk {{print $2}} |xargs kill]
    catch [eval exec $recordwave $voicedir/$voiceout/$greeting.wav ]
}

proc listen_g {} {
global playwave voicedir voiceout greeting
    catch [eval exec $playwave $voicedir/$voiceout/$greeting.wav ]
}

proc convert_g {} {
global MODEMTYPE MODEMCOMP pvfsamples voicedir voiceout greeting
    catch [exec cat $voicedir/$voiceout/$greeting.wav | wavtopvf | pvfspeed -s $pvfsamples | pvftormd $MODEMTYPE $MODEMCOMP > $voicedir/$voiceout/$greeting ]
}

proc delete_it {} {
global fnlist
  foreach i [lsort -integer -decreasing [.f.list curselection]] {
    exec rm -f [lindex $fnlist $i]
    set fnlist [lreplace $fnlist $i $i]
    .f.list delete $i
  }
}

proc get_files {} {
global voicedir voicein fnlist
  
 # clear the contents of listbox
 .f.list delete 0 1000
  set fnlist {}
  # puts "fnlist=$fnlist"
  if {[file exists $voicedir/.timestamp]} {
    set lastplay [file mtime $voicedir/.timestamp]
  } else {
    set lastplay -1
  }
  foreach n [glob -nocomplain $voicedir/$voicein/*.rmd] {
    set f [exec ls -l --full-time $n | awk {{print $6, $7, $8, $9, $10}}]
    set h [exec date -d $f "+* %a %b %e, %Y %l:%M%p  "]
    set g [exec ls $n | awk -F "-" {{print $4}} | awk -F "." {{print $1}}]
    if [string match O $g ] {
        set g "Not Available"
       } else {
	set acode [string range $g 0 2]
        set prefx [string range $g 3 5]
        set tailn [string range $g 6 9]
        set g "($acode)$prefx-$tailn"
       }
    set t ""
    append t $h $g
    lappend fnlist $n
    if {$lastplay>0} {
      if {[file mtime $n]>$lastplay} {set t "$t\N"}
    }
      .f.list insert end $t
  }
}

proc timestamp {} {
global voicedir voicein

  set do_stamp 1
  for {set i 0} {$i<[.f.list size]} {incr i} {
    if {[string length [.f.list get $i]]>19} {set do_stamp 0}
  }
  if {$do_stamp} {
    exec touch $voicedir/$voicein/.timestamp
    exec rm -f $voicedir/$voicein/.flag
  }
}

##############################################
# Under Greeting
##############################################
# Play Greeting
proc play_g {} {
global playwave voicedir voiceout greeting playPID
    exec rmdtopvf $voicedir/$voiceout/$greeting | pvftowav > $voicedir/tkvoice.tmp 2>/dev/null
    set playPID [eval exec $playwave $voicedir/tkvoice.tmp >/dev/null 2>&1 &]

    tk_messageBox -icon info -type ok -title "tkVoice Out-Going Greeting" -message "Now listening to your:\n\nOUT-GOING GREETING"
}

#---------------------------------------------
# Record Greeting
proc record {} {
global tkVoice tkvoicedir voicedir voiceout greeting MODEMTYPE MODEMCOMP
  uplevel [list source [file join $tkvoicedir/tkvrecord.tcl]]
}


##############################################
# Under Options
##############################################
# Path setup
proc paths {} {
global tkVoice tkvoicedir voicedir greeting
 uplevel [list source [file join $tkvoicedir/tkvpaths.tcl]]
}
#---------------------------------------------
# Modem setup
proc modem {} {
global tkVoice tkvoicedir MODEMTYPE MODEMCOMP
 uplevel [list source [file join $tkvoicedir/tkvmodem.tcl]]
}
#---------------------------------------------
# Audio setup
proc audio {} {
global tkVoice tkvoicedir playwave recordwave pvfsamples
 uplevel [list source [file join $tkvoicedir/tkvaudio.tcl]]
}
#---------------------------------------------

##############################################
# Under Help
proc aboutBox {} {
# -icon error, info, question, warning
    tk_messageBox -icon question -type ok -title "About tkVOICE" -message \
"tkvoice is a frontend for:\ \ \ \ \ \  \"vgetty\"\
which is freely available via www at http:\ 
//alpha.greenie.net/vgetty/ \t\t
\"TkVoice\" is writen by Peter Bruley and is based on code taken from \"xvoicetool\" "
}

# positionWindow --
# Arguments:
# w -           The name of the window to position.
 
proc positionWindow w {
    wm geometry $w +300+300
}
##### End of subs

##### Start of Frames

# Create the menu bar at the top of the window.
 
frame .menu -relief raised -borderwidth 2
pack .menu -side top -fill x
 
# Under the File button
 
menubutton .menu.file -text File -menu .menu.file.m -underline 0
menu .menu.file.m
global fstype
.menu.file.m add command -label "Exit" -underline 1 \
        -command "destroy ."
# Under the Greeting button
 
menubutton .menu.greeting -text Greeting -menu .menu.greeting.m -underline 0
menu .menu.greeting.m
 
.menu.greeting.m add command -label "Listen to Greeting" -underline 0 \
        -command {play_g}
.menu.greeting.m add command -label "Record Greeting" -underline 0 \
        -command {record}

# Under the Option button
 
menubutton .menu.option -text Options -menu .menu.option.m -underline 0
menu .menu.option.m
.menu.option.m add command -label "Paths Setup" -underline 7 \
        -command {paths}
.menu.option.m add command -label "Modem Setup" -underline 7 \
        -command {modem}
.menu.option.m add command -label "Audio Setup" -underline 7 \
        -command {audio}

# Under the Help button
 
menubutton .menu.help -text Help -menu .menu.help.m -underline 0
menu .menu.help.m
.menu.help.m add command -label "About tkVOICE" -underline 0 \
        -command {aboutBox}
 
pack .menu.file .menu.greeting .menu.option -side left
pack .menu.help -side right
 
# GIF frame on left of list
frame .gif -relief raised -borderwidth 2
pack .gif -side top -fill x

# tkvoice image
catch {image delete tkvoice}
image create photo tkvoice -file [file join $tkvoicedir/image/tkvoice.gif]
label .gif.tkvoice -image tkvoice -bd 1 -relief sunken

catch {image delete linux}
image create photo linux -file [file join $tkvoicedir/image/linux.gif]
label .gif.linux -image linux -bd 1 -relief sunken

catch {image delete phone}
image create photo phone -file [file join $tkvoicedir/image/phone.gif]
label .gif.phone -image phone -bd 1 -relief sunken

catch {image delete penguin}
image create photo penguin -file [file join $tkvoicedir/image/penguin.gif]
label .gif.penguin -image penguin -bd 1 -relief sunken

pack .gif.phone -side left 
pack .gif.tkvoice -side left -expand 1 -fill x
pack .gif.linux -side right 
pack .gif.penguin -side right

# list box frame
frame .f


listbox .f.list -relief sunken -font {fixed 14} -width 42 -height 10
scrollbar .f.scroll
image create photo exit -file [file join $tkvoicedir/image/exit.gif]
button .quit  -image exit -anchor center -command "timestamp; destroy ."
image create photo play -file [file join $tkvoicedir/image/play.gif]
button .playa -text "Play" -image play -anchor center -command play_audio
image create photo stop -file [file join $tkvoicedir/image/stop.gif]
button .stop -text "Stop" -image stop -anchor center -command stop_audio
image create photo reload -file [file join $tkvoicedir/image/reload.gif]
button .reload -text "Refresh" -image reload -anchor center -command "timestamp;get_files"
image create photo del -file [file join $tkvoicedir/image/del.gif]
button .del   -image del -anchor center -command delete_it

pack .f -padx 3 -pady 3
pack .quit  -side right -expand 1 -fill x -padx 3 -pady 3
pack .playa -side right -expand 1 -fill x -padx 3 -pady 3
pack .stop -side right -expand 1 -fill x -padx 3 -pady 3
pack .reload   -side right -expand 1 -fill x -padx 3 -pady 3
pack .del   -side right -expand 1 -fill x -padx 3 -pady 3
pack .f.list -side left
pack .f.scroll -side left -fill y -expand 1
get_files

bind .f.list <Double-Button-1> play_audio
wm protocol . WM_DELETE_WINDOW "timestamp; destroy ."
wm iconbitmap . @$tkvoicedir/image/icon

tkwait window .
