#!/bin/bash

#  This script interviews a new user of edbrowse,
#  and creates an initial version of the .ebrc config file.
#  The config file can be edited thereafter.

#  Abort if an error occurs
set -e

question=
#  default answer
defans=

shellknown=n
if [ $SHELL = /bin/bash ]
then
shellknown=y
shellstart=.bash_login
shellfns=.bashrc
fi

function response()
{
echo -n "$question"
if [ -n "$defans" ]
then
echo -n " [$defans]"
fi
echo -n ": "
read answer
if [ -z "$answer" ]
then
answer=$defans
fi
}

function responsenumber()
{
while true
do
response
if [ -z "${answer/[0-9]*/}" ]
then
break
fi
echo "Please enter a number."
done
}

function responserange()
{
start=$1
end=$2
while true
do
responsenumber
if [ $answer -ge $start -a $answer -le $end ]
then
break
fi
echo "Please enter a number between $start and $end."
done
}

#  respond with a certain letter
function responselrs()
{
lrs=$1
while true
do
response
answer=${answer:0:1}
if [ -z "${answer/[$lrs]/}" ]
then
break
fi
echo "Please enter one of the letters $lrs."
done
}

function responseyn()
{
while true
do
response
answer=${answer:0:1}
if [ "$answer" = y -o "$answer" = n ]
then
break
fi
echo "Please enter y or n."
done
}

function hitreturn()
{
question="Hit return to continue"
defans=
response
}

#  edbrowse config file
ebcf=$HOME/.ebrc
function configstart()
{
if [ ! -f $ebcf ]
then
echo "I am creating your edbrowse config file in $ebcf.
I will write text into this file as we go along.
This file contains passwords, and should not be readable by others.
I will set the permissions accordingly; please leave it at 600.
"

echo '#  edbrowse configuration file.
#  You can edit this file via edbrowse -c.

#  autosetup 1' >$ebcf
chmod 600 $ebcf

sleep 3
echo "File created successfully.
"
sleep 2
fi

lastline=`tail -1 $ebcf`
level=${lastline:13}
prelevel=${lastline:3:9}
}

configstart

if [ "$prelevel" != autosetup ]
then
echo "You already have an edbrowse config file in place;
I will be working with the file $ebcf.new.
When we're done, you can move this back to $ebcf, but beware,
you will lose all the configuration information that you currently have in that file.
"
sleep 2
ebcf=$ebcf.new

configstart
fi

if [ "$prelevel" != autosetup ]
then
echo "Your .ebrc.new file seems to be complete, or corrupted.
I cannot safely update either of these files.
Please remove one or both of them, and start this script again."
exit 1
fi

if [ $level = 1 ]
then
echo "*** level 1, default behaviors ***
"

echo "The debug level determines the amount of output you will receive.
0 is silent, except for errors.
1 prints the size of each file as it is read or written.
2 prints the different urls as you are redirected from one website to another.
Higher levels crank out more output, but you probably don't want to see that.
Most people like level 1."
question="Enter debug level"
defans=1
responserange 0 4
dblev=$answer
echo

echo "When a simple error occurs, I usually print out a question mark,
and nothing more.  I can however print the error message every time.
Most people like the quick question marks for simple typos."
question="Do you want to read the error message every time"
defans=n
responseyn
Hon=$answer
echo

echo "When scanning through a directory, it is readonly by default.
This means you cannot delete a file, simply by deleting the corresponding line.
You can change this behavior so that deleted files are moved
to your trash bin, or deleted altogether.
r = directories are readonly.
m = deleted files move to your trash bin.
x = deleted files go away forever."
question="How should deletes in directory mode behave"
defans=m
responselrs rmx
dmode=dw
if [ "$answer" = r ]
then
dmode=dr
fi
if [ "$answer" = x ]
then
dmode=dx
fi
echo

echo "When you edit a directory, some files are hidden by default.
These are the files that begin with a dot, like .ebrc."
question="Do you want to see these files"
defans=n
responseyn
hf=$answer
echo

echo "When a line is listed with the l command,
I can put ^ at the beginning of the line and $ at the end.
Or I can do this all the time.
o = end markers off.
l = end markers on listed lines.
p = end markers every time I print a line."
question="When do you want ^ $ markers to appear"
defans=o
responselrs olp
endmarks=eo
if [ "$answer" = l ]
then
endmarks=el
fi
if [ "$answer" = p ]
then
endmarks=ep
fi
echo

(
echo "#  The init function is run when edbrowse is started.
#  It can be used to establish the settings you want,
#  or preload common files such as your bookmarks etc.
function+init {
#  debug level is 0 at the start, to avoid a lot of messages at startup
db0
#  end markers for listed lines
$endmarks"
if [ $hf = y ]
then
echo "#  Show hidden files in a directory
hf"
fi
echo "#  Manage deleted files in directory mode
$dmode"
if [ $Hon = y ]
then
echo "#  Show the error messages every time.
H"
fi
if [ $dblev != 0 ]
then
echo "#  set the debug level
db$dblev"
fi
echo '}

#  autosetup 2'
) >>$ebcf

level=2
fi

if [ $level = 2 ]
then
echo "*** level 2, special edbrowse files ***
"

echo "Many people put their bookmarks, email addresses, certificates, etc in an edbrowse directory.
Enter a directory now, or just hit return for the default."
question="Edbrowse system directory"
defans=$HOME/.eb
response
ebdir=$answer
if [ ! -d $ebdir ]
then
mkdir $ebdir
fi
if [ ! -d $ebdir ]
then
echo "$ebdir is not a directory"
exit 1
fi
echo

echo "It is convenient to have a file of bookmarks, also known as favorites
in the Windows world.
It isn't strictly necessary, but if you have this set up,
I can create some aliases and functions that will make it easier
to access, and add to, your bookmarks."
question="Enter the location of your bookmarks file"
defans=$ebdir/bookmarks
response
ebbm=$answer
touch $ebbm
if [ ! -s $ebbm ]
then
echo "<html>
<!-- Bookmark file, compatible with edbrowse.
A bookmark typically consists of 3 lines.
    URL
    description
    close anchor
This is created by the A command.
Of course this file can be viewed by any browser.
It's just html.
-->

<A HREF=http://www.eklhad.net>
Karl Dahlke home page
</A>
<A HREF=http://www.mathreference.com>
MathReference.com
</A>
<A HREF=http://www.space.com>
space.com
</A>" > $ebbm
fi
echo

#  put bookmark variables in the shell files?
bmvar=n

if [ $shellknown = y ]
then
echo "I can create, in your $shellstart file, a variable like this:
export bookmarks=$ebbm
so you can access your bookmarks from anywhere.
I can also put an alias in your $shellfns file
alias ebm='edbrowse \$bookmarks'
so you can type in ebm and edet or access your bookmarks from anywhere.
(You will need to log out and log back in for this alias to take effect.)"
question="Would you like me to create this alias"
defans=y
responseyn
bmvar=$answer
echo
fi

echo "I will create, in your config file, a function wbm that you can invoke via
<wbm
This will add the contents of your current buffer to your bookmarks.
Usually this follows the A command, which builds your bookmark.
Check it out in your config file when this program is over."
hitreturn
echo

echo "It is convenient to have a file of email addresses,
i.e. your address book.
It isn't strictly necessary, but if you have this set up,
I can create some aliases and functions that will make it easier
to access, and add to, your address book."
question="Enter the location of your address book"
defans=$ebdir/adbook
response
ebad=$answer
touch $ebad
if [ ! -s $ebad ]
then
echo "#  Address book, compatible with edbrowse.

#  relatives

#friends

#  work

#  internet contacts
eklhad:eklhad@gmail.com:home phone:cell phone:anything else you like
" > $ebad
fi
echo

#  put address book variables in the shell files?
advar=n

if [ $shellknown = y ]
then
echo "I can create, in your $shellstart file, a variable like this:
export adbook=$ebad
so you can access your address book from anywhere.
I can also put an alias in your $shellfns file
alias eab='edbrowse \$adbook'
so you can type in eab and edet or access your email addresses from anywhere.
(You will need to log out and log back in for this alias to take effect.)"
question="Would you like me to create this alias"
defans=y
responseyn
advar=$answer
echo
fi

echo "I need a file for cookies.
If you don't know what cookies are, don't worry about it.
It's just something I need to browse certain websites."
question="Enter the location of your cookie jar"
defans=$ebdir/cookies
response
ebcook=$answer
touch $ebcook
#  Some cookies contain passwords.
chmod 600 $ebcook
echo

echo "I need a file for secure certificates.
These are used for secure transactions on the web, such as amazon.com."
lynxcert=/etc/ssl/cert.pem
ebcert=
if [ -f $lynxcert ]
then
echo "I see you already have such a file, $lynxcert,
which is used by lynx.
Would you like edbrowse to use the same file,
so that lynx and edbrowse share the same certificates?"
question="Share with $lynxcert"
defans=y
responseyn
if [ $answer = y ]
then
ebcert=$lynxcert
fi
fi

if [ -z "$ebcert" ]
then
question="Enter the location of your certificate file"
defans=$ebdir/cert
response
ebcert=$answer
touch $ebcert

if [ ! -s $ebcert ]
then
echo "Would you like me to retrieve a file of certificates from the internet?
You must be on line for this to work."
question="Fetch from internet"
defans=y
responseyn
if [ $answer = y ]
then
wget -q -O $ebcert http://the-brannons.com/edbrowse/ssl-certs
echo "got it."
else
echo "Ok, you can get a certificate file later."
fi
fi
echo "Later on, when you are logged in as root, you may want to move this
to $lynxcert, so that your certificates can be shared among
edbrowse, lynx, and other browsers."
fi
echo

echo "I need a file to store IP addresses that usually generate spam.
This file can be empty for now; as long as it exists.
We'll worry about how to populate it later."
question="List of suspect IP addresses"
defans=$ebdir/ipblack
response
ebip=$answer
touch $ebip
echo

echo "When edbrowse fetches your mail, it automatically moves to a directory
that you can think of as your in-box."
question="Enter mail directory"
defans=$HOME/mbox
response
ebinbox=$answer
if [ ! -d $ebinbox ]
then
mkdir $ebinbox
fi
echo

if [ $shellknown = y ]
then
#  It's really stupid that bash doesn't call .bashrc after invoking .bash_login.
#  So you should call .bashrc from insinde .bash_login.
#  Do you?
callbashrc=n
if grep -q "^\. *$shellfns" $shellstart
then
callbashrc=y
fi
fi

if [ $bmvar = y ]
then
echo "
export bookmarks=$ebbm" >> $shellstart
echo "
alias ebm='edbrowse $ebbm'" >> $shellfns
if [ $callbashrc = n ]
then
echo "
alias ebm='edbrowse $ebbm'" >> $shellstart
fi
fi

if [ $advar = y ]
then
echo "
export adbook=$ebad" >> $shellstart
echo "
alias eab='edbrowse $ebad'" >> $shellfns
if [ $callbashrc = n ]
then
echo "
alias eab='edbrowse $ebad'" >> $shellstart
fi
fi

echo "#  My address book.
adbook = $ebad

#  The cookie jar
jar = $ebcook

#  secure certificates for https
certfile = $ebcert

#  ip addresses in the blacklist
ipblack = $ebip

#  Write spam messages here.  I use a file in my trash bin,
#  so I know it gets cleaned out every week.
spamcan = $HOME/.Trash/spamcan

#  Function to write a bookmark to your list of favorites.
#  Best to use this function every time, because it appends.
#  If you do it manually you might accidentally write without append,
#  and clobber all the bookmarks you have accumulated.
function+wbm {
w+ $ebbm
}

#  Move to this directory when fetching mail.
maildir = $ebinbox

#  autosetup 3" >> $ebcf

level=3
fi

if [ $level = 3 ]
then
echo "*** level 3, mail accounts ***

It's time to configure your mail accounts,
so that edbrowse can act as a mail client, retrieving and sending mail
over the Internet.  I only need to know about direct mail accounts.
If you have a mail account, such as hotmail.com, that you access
through your browser, as a website, I don't need to know about that.
I only need to know about mail accounts that you access through a mail client
like Outlook, Pine, Eudora, etc."
question="Do you have any of these mail accounts"
defans=y
responseyn
echo

#  Build the mail string as we go.
#  I'll turn & into newline later.
mst="#  Mail accounts.&#  These are the direct mail accounts, web based email is not needed here.&"

if [ $answer = n ]
then
mst="$mst&#  No mail accounts at the present time.&"

else

echo "Great.  Here is what you will need for each mail account.
1. The machine that you get your mail from, and send your mail to.
These are often the same machine, such as mail.somedomain.com,
but sometimes they are different, such as pop3.somedomain.com
and smtp.somedomain.com.
2. Whether these connections are secure/encrypted.
Local mail, offered by your ISP, is usually not.
Distant mail, such as Google mail, usually is, since your personal email
travels across the Internet to get to and from the server.
3. Your email address relative to this account.
This takes the form: username@somedomain.com.
4. Login, usually the same as username.
5. Password.  This is the secret that keeps others from accessing your mail.
6. Full name.  This appears in your emails.
Of course you know what your name is, but you may want different names
for different accounts.
Home account, work account, your child's account, etc.
So I give you the chance to enter a different name with each account.
You need all this information at hand, for each account, before we proceed."
hitreturn
echo

mailnum=1

fullname=
while true
do
if [ $mailnum = 1 ]
then
echo "Enter your first mail account.
This should be the primary account, the one offered by your ISP.
For technical reasons, this will become the default account.
If you just type sm, without specifying an account,
I will use this account to send your mail."
hitreturn
echo
else
question="Do you have another mail account"
defans=n
responseyn
echo
if [ $answer = n ]
then
break
fi
fi

echo "Enter the email address.
This looks like user@somedomain.com."
question="Email address"
defans=
response
reply=$answer
user=${answer/@*/}
domain=${answer/*@/}

question="Enter user name"
defans=$user
response
user=$answer

question="Enter password"
defans=
response
password=$answer

question="Enter the full name associated with this account"
defans=$fullname
response
fullname=$answer

question="Enter the machine where you get your mail"
defans="mail.$domain"
response
pop=$answer

question="Enter the machine where you send your mail"
defans=$pop
defans=${defans/#pop3./smtp.}
defans=${defans/#pop./smtp.}
response
smtp=$answer

question="Is this a secure/encrypted connection"
defans=n
responseyn
secure=$answer

mst="$mst&mail {&inserver = $pop&outserver = $smtp"
if [ $mailnum = 1 ]
then
mst="$mst&default"
fi
if [ $secure = y ]
then
mst="$mst&inport = *995&outport = *465"
else
mst="$mst&inport = 110&outport = 25"
fi
mst="$mst&login = $user&password = $password&from = $fullname&reply = $reply&}&"

echo "You may want to create an alias for convenient access to this account.
alias whatevermail='edbrowse -m$mailnum'
I'll leave that to you.
"
mailnum=$((mailnum+1))
done

fi

echo "$mst&#  autosetup 4" |
tr '&' '\12' >> $ebcf

level=4
fi

if [ $level = 4 ]
then
echo "*** level 4, filters ***

I will place a from filter block in your config file.
This directs email from certain people, by name or by email address,
into certain files.
I'm only creating the fromfilter { } block at this time.
You can edit your config file and fill in the details later.
Remember that every line in your address book becomes its own from filter,
so you don't have to duplicate all those entries.  For instance,
fred:fred.flintstone@cartoons.com
will save any message from fred.flintstone@cartoons.com to a file called fred.
But Fred might have a work email down at the Cave Construction Company,
so you might want to filter him by name as well.
    Fred Flintstone > fred
I will add an entry for myself, by name, in case you get email from me
in the future, from any of my numerous email accounts.
    Karl Dahlke > eklhad
That will be the only entry in your fromfilter block, for now."
hitreturn
echo

echo "I will create a subject filter block, which saves emails into files
based on subject, and a to filter block, which saves emails into files
based on the email address it was sent to.
Again, these blocks will be empty."
hitreturn
echo

echo "I will create a last spamm function, <lspam, that will retrieve the last
message that was placed in your spam area.
Similarly, <bspam steps back to the previous spam message, and so on.
You should really review your spam emails, because my source IP
test is really quite crude, and there are plenty of false positives."
hitreturn
echo

echo "#  to, from, and subject filters

tofilter {
}

fromfilter {
Karl Dahlke > eklhad
}

subjfilter {
}

#  Function to read the last spam message.
function+lspam {
e /home/eklhad/.Trash/spamcan
?={70}?+,\$w2
e2
b
1z20
}

#  Back up to the previous spam message.
function +bspam {
e1
?={70}?X
-kb
?={70}?X
+s/^[RD]/&/
.,'bw2
e2
b
1z20
}

#  Sometimes javascript does nothing more than deliver advertisements,
#  and edbrowse javascript is not the greatest,
#  so turn it off for certain domains.
nojs = space.com

#  autosetup 5" >> $ebcf

level=5
fi

if [ $level = 5 ]
then
echo "*** level 5, audio files ***

Enter the program, with parameters, that plays wave, voc, and audio files."
playloc=`whereis -b play`
playloc=${playloc/#play:/}
playloc=${playloc/# /}
if [ -n "$playloc" ]
then
echo "Audio player found in $playloc,
but you can use another player if you wish."
defans="play -t * -"
else
echo "Leave blank if you have no player installed."
defans=
fi
question="Audio player"
response
playprog=$answer
echo

echo "Enter the program, with parameters, that plays mp3 files."
mpgloc=`whereis -b mpg123`
mpgloc=${mpgloc/#mpg123:/}
mpgloc=${mpgloc/# /}
if [ -n "$mpgloc" ]
then
echo "MP3 player found in $mpgloc,
but you can use another player if you wish."
defans="mpg123 -q -"
else
echo "Leave blank if you have no mp3 player installed."
defans=
fi
question="MP3 player"
response
mpgprog=$answer
echo

echo "Enter the program, with parameters, that plays streaming audio.
This is RealPlayer audio, not Windows Media or Quicktime;
those are not supported yet."
trloc=`whereis -b trplayer`
trloc=${trloc/#trplayer:/}
trloc=${trloc/# /}
if [ -n "$trloc" ]
then
echo "Streaming audio player found in $trloc,
but you can use another player if you wish."
defans="trplayer"
else
echo "Leave blank if you have no streaming audio player installed."
defans=
fi
question="Streaming audio player"
response
trprog=$answer
echo

(
echo "#  Describe the mime types and the programs to run them.
"

if [ -n "$playprog" ]
then
echo "mime {
type = audio/basic
desc = audio file in a wave format
suffix = wav,voc,au
#  The star is replaced with the suffix at runtime
program = $playprog
}
"
fi

if [ -n "$mpgprog" ]
then
echo "mime {
type = audio/mp3
desc = audio file in mp3 format
suffix = mp3
program = $mpgprog
}
"
fi

if [ -n "$trprog" ]
then
echo "mime {
#  the < forces it to be a stream, hence the url is passed to the program
type = <audio/x-pn-realaudio
desc = streaming audio real player
suffix = rm,ra,ram
protocol = rtsp,pnm
program = $trprog
}
"
fi

echo "#  autosetup 6"
) >> $ebcf

level=6
fi

if [ $level = 6 ]
then
echo "*** level 6, sample functions ***

Perhaps the two most useful sites on the Internet are google and wikipedia.
I will create two functions that make it easy to access these sites.
They are similar to shortcuts in the desktop world.
To search for kangaroo in google, type <gg kangaroo.
To search for kangaroo in wikipedia, type <wk kangaroo.
These functions will also show you, by example,
how to write your own functions with parameters etc.
Please review your config file and look for the functions gg and wk."
hitreturn
echo

cat <<'!' >>$ebcf
#  User defined functions, macros, and shortcuts.

#  Access wikipedia
function+wk {
b http://www.wikipedia.org/search-redirect.php?search=~0&language=en&go=%3E&go=Go
}

#  Access google
function+gg {
b www.google.com/search?q=~0&hl=n&btnG=Google+Search&meta=
#  invoke the google cleanup routine
<ggc
}

#  strip the trash off of a google page.
#  This can become out of date if google changes its page layout.
function:ggc {
#  get rid of pdf warnings
g/^Your browser may not have a PDF reader available.$/d
g/^{Similar pages}$/d
#  trailing lines, after "search next", can go away
/^{search Next}$/+,$d
#  initial lines and stats can go away
1,/seconds)$/d
#  move the "did you mean" line to the end; we need to keep this one
/^Did you mean:$/,/^Did you mean:$/+2m$
#  more stuff at the start that we don't need
1,/^Tip: Save time by hitting/+d
#  put the "did you mean" line back to the top, if it's there
/^Did you mean:$/,$m0
}

!

#  Get rid of the autosetup lines.
ed $ebcf <<! >/dev/null 2>&1
g/^#  autosetup [0-9]$/d
w
q
!

echo "Congratulations, your config file $ebcf is complete."

fi

exit 0
