#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# vim: expandtab sw=4 ts=4 sts=4:
'''
Gammu man page generator
'''
__author__ = 'Michal Čihař'
__email__ = 'michal@cihar.com'
__license__ = '''
Copyright (c) 2003 - 2007 Michal Čihař

This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License version 2 as published by
the Free Software Foundation.

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.,
51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
'''

# Configuration

'''
Path to gammu binary.
'''
BIN_PATH = 'build/gammu/gammu'

'''
Output path where man page will be stored.
'''
OUT_PATH = 'docs/user/gammu.1'


# Man page data

HEADER = '.TH "GAMMU" "1" "%(date)s" "Gammu %(version)s" "Gammu Documentation"\n'
SECTION = '\n.SH "%s"\n'
SUBSECTION = '\n.SS "%s"\n'
PARAGRAPH = '.P\n%s\n'
COMMAND = '.TP\n.BI "%s" " %s"\n%s\n'
COMMAND_NOPARAM = '.TP\n.BI "%s"\n%s\n'

# Fixed parts

SEE_ALSO = '''
.P
README

<http://www.gammu.org/> contains wiki with more user hints and further
documentation

cu(1)

gnokii(1)

wammu(1)

gmobilemedia(1)
'''

AUTHORS = '''
.P 
You can contact authors on <gammu-users@lists.sourceforge.net>.

.P 
\\fIMichal Cihar\\fR
<michal@cihar.com>
is current project maintainer and contributor of most of AT and OBEX
code.

.P 
\\fIMarcin Wiacek\\fR
<marcin@mwiacek.com>
is project iniciator and contributor of most Nokia code.

.P
As this project grew from Gnokii, we would like to thanks all Gnokii
developers, especially \\fIPavel Janik\\fR, \\fIPawel Kot\\fR
and \\fIManfred Jonsson\\fR (see CREDITS from Gnokii for all their
contributor).

.P
Many other people have helped with various features, check ChangeLog for
more details.
'''

FILES = '''
.P 
\\fI~/.gammurc\\fP
.br
\\fI/usr/share/doc/gammu/*\\fP
.br
\\fI/dev/ircomm?\\fP
.br
\\fI/dev/ttyS?\\fP
.br
\\fI/dev/ttyACM?\\fP
'''

EXAMPLES = '''
.P 
To check it out, edit \\fI~/.gammurc\\fP and put there something like

\\fB[gammu]
.br
port = /dev/ttyACM0
.br
connection = at
\\fR

.TP
Save text message up to standard 160 chars:

echo "All your base are belong to us" | gammu savesms TEXT

.TP
Save long text message:

echo "All your base are belong to us" | gammu savesms TEXT \\-maxlen 400

gammu savesms EMS \\-text "All your base are belong to us"

.TP
Save some funky message with predefined sound and animation from 2 bitmaps:

gammu savesms EMS \\-text "Greetings" \\-defsound 1 \\-text "from Gammu"
\\-tone10 axelf.txt \\-animation 2 file1.bmp file2.bmp

.TP
Save protected message with ringtone:

gammu savesms EMS \\-protected 2 \\-variablebitmaplong ala.bmp
\\-toneSElong axelf.txt \\-toneSE ring.txt
'''

NAME = '''
.P
Gammu - Does some neat things with your cellular phone or modem.
'''

DESCRIPTION = '''
.P
This program is a tool for mobile phones. Many vendors and phones
are supported, for actual listing see <http://cihar.com/gammu/phonedb/>.
'''

LICENSE = '''
This program is licensed under GNU/GPL version 2.
'''

BUGS = '''
There are definitely many bugs, reporting to author is welcome. Please include
some useful information when sending bug reports (especially debug logs,
operating system, it's version and phone information are needed).

.P
To generate debug log, either enable in gammurc (alternatively you can
do it on command line, but gammurc way allows separating debug log from
other output):

    logfile = /tmp/gammu.log
    logformat = textall

With this settings, Gammu generates /tmp/gammu.log on each connection to
phone and stores dump of communication there. You can also find some
hints for improving support for your phone in this log.
'''

DEBUG_LEVELS = '''
Parameters, which allow to control debug level:

\\fBnothing\\fR - no debug level
.br
\\fBtext\\fR    - transmission dump in text format
.br
\\fBtextall\\fR - all possible info in text format
.br
\\fBerrors\\fR  - errors in text format
.br
\\fBbinary\\fR  - transmission dump in binary format
'''

# Commands help, initially generated from original gammu man page

HELP = {}
HELP['help'] = '''Output help information and exit.
''' 
HELP['version'] = '''Output version information and exit.
'''
HELP['checkversion'] = '''Checks whether there is newer Gammu version available online 
(if Gammu has been compiled with CURL). If you pass additional parameter stable, only
stable versions will be checked.
'''
HELP['identify'] = '''Show the most important phone data.
''' 
HELP['monitor'] = '''Get phone status and writes continuously to standard output. Press Ctrl+C
to break this state.
'''
HELP['reset'] = '''Make phone reset: soft (without asking for PIN) or hard (with PIN).

\\fINote:\\fR some phones will make hard reset even with \\fBSOFT\\fR option.
'''
HELP['resetphonesettings'] = '''Reset phone settings. \\fIBE CAREFULL !!!!\\fR

.br
\\fBPHONE:\\fR
.br

.br
\\fBDEV:\\fR
.br

.br
\\fBALL:\\fR Clear user settings
.br
* removes or set logos to default
.br
* set default phonebook and other menu settings
.br
* clear T9 words,
.br
* clear call register info
.br
* set default profiles settings 
.br
* clear user ringtones

\\fBUIF:\\fR
.br
* changes like after \\fBALL\\fR
.br
* disables netmon and PPS (all "hidden" menus)

\\fBFACTORY:\\fR
.br
* changes like after \\fBUIF\\fR
.br
* clear date/time
'''
HELP['presskeysequence'] = '''Press specified key sequence on phone keyboard

\\fBmM\\fR - Menu
.br
\\fBnN\\fR - Names key
.br
\\fBpP\\fR - Power
.br
\\fBuU\\fR - Up
.br
\\fBdD\\fR - Down
.br
\\fB+\\-\\fR - +\\-
.br
\\fBgG\\fR - Green
.br
\\fBrR\\fR - Red
.br
\\fB123456789*0#\\fR is numeric keyboard
'''
HELP['getdisplaystatus'] = ''''''
HELP['getprofile'] = ''''''
HELP['setautonetworklogin'] = ''''''
HELP['getsecuritystatus'] = '''Show, if phone wait for security code (like PIN, PUK, etc.) or not
'''
HELP['entersecuritycode'] = '''Allow to enter security code from PC. When code is \\-, it is read from stdin.
'''
HELP['listnetworks'] = '''Show names/codes of GSM networks known for Gammu
'''
HELP['getfmstation'] = '''Show info about FM stations in phone
'''
HELP['getgprspoint'] = ''''''
HELP['getfiles'] = ''''''
HELP['getfilesystem'] = '''Display info about all folders and files in phone memory/memory card. By default there is tree displayed, you can change it:

.B \\-flatall
there are displayed full file/folder details like ID (first parameter in line)

.B \\-flat

Please note, that in some phones (like N6230) content of some folders (with more files) can be cut (only part of files will be displayed) for example on infrared connection. This is not Gammu issue, but phone firmware problem.
'''
HELP['getfolderlisting'] = '''
Display files and folders available in folder with given folder ID. You can get ID's using getfilesystem \\-flatall.

Please note, that in some phones (like N6230) content of some folders (with more files) can be cut (only part of files will be displayed) for example on infrared connection. This is not Gammu issue, but phone firmware problem.
'''
HELP['getrootfolders'] = '''
Display info about drives available in phone/memory card.
'''
HELP['deletefiles'] = ''''''
HELP['addfolder'] = ''''''
HELP['addfile'] = '''Add file with specified name to folder with specified folder ID.

.B \\-type 
- file type was required for filesystem 1 in Nokia phones (current filesystem 2 doesn't need this)

.B \\-readonly, \\-protected, \\-system, \\-hidden
- you can set readonly, protected (file can't be for example forwarded from phone menu), system and hidden (file is hidden from phone menu) file attributes

.B \\-newtime 
- after using it date/time of file modification will be set to moment of uploading 

'''
HELP['nokiaaddfile'] = '''Install the *.jar/*.jad file pair of a midlet in the application or game menu of the phone. You have to give the name without the jar/jad suffix, otherwise you will get the slightly confusing error message Can't open specified file. Read only ?

The option
.I \-overwrite
deletes the application's .jad and .jar files bevor installing, but doesn't delete the application data. Option
.I \-overwriteall
will also delete all data. Both these options work only for Application or Game upload.

\\fIExample:\\fR gammu nokiaaddfile Application Alien will read Alien.JAD and Alien.JAR and add to Applications

\\fIExample:\\fR gammu nokiaaddfile Tones file.mid will read file.mid and add to Tones folder
''' 
HELP['getdatetime'] = '''Get date and time from phone
''' 
HELP['setdatetime'] = '''Set date and time in phone to date and time set in computer. Please 
note, that this option doesn't show clock on phone screen. It only set
date and time.

\\fITIP:\\fR you can make such synchronization each time, when will connect
your phone and use Gammu. See \\fBgammurc\\fR for details.
''' 
HELP['getalarm'] = '''Get alarm from phone, if no location is specified,
1 is used.
'''
HELP['setalarm'] = '''Sets repeating alarm in phone on selected time.''' 
HELP['getmemory'] = '''Get memory location from phone. Numerate locations from 1.

\\fBDC\\fR = Dialled calls
.br
\\fBMC\\fR = Missed calls
.br
\\fBRC\\fR = Received calls
.br
\\fBON\\fR = Own numbers
.br
\\fBVM\\fR = voice mailbox
.br
\\fBSM\\fR = SIM phonebook
.br
\\fBME\\fR = phone internal phonebook
.br
\\fBFD\\fR = fixed dialling
.br
\\fBSL\\fR = sent SMS log
'''
HELP['searchmemory'] = ''''''
HELP['deleteallmemory'] = '''Deletes all entries from specified memory type.'''
HELP['deletememory'] = '''Deletes entries in specified from specified memory type.'''
HELP['listmemorycategory'] = ''''''
HELP['senddtmf'] = '''Plays DTMF sequence. In some phones available only during calls
'''
HELP['getspeeddial'] = '''''' 
HELP['getsms'] = '''Get SMS. Locations are numerated from 1.

When give folder 0, sms is given from "flat" memory (all sms from all
folders have unique numbers). It's sometimes emulated by Gammu.
You can use it with all phones.

When give folder 1, 2, etc. sms are taken from Inbox, Outbox, etc.
and each sms has unique number in his folder. Name of folders can
depend on your phone (the most often 1="Inbox", 2="Outbox", etc.).
This method is not supported by all phones (for example, not supported
by Nokia 3310, 5110, 6110). If work with your phone, use
\\fBgetsmsfolders\\fR to get folders list.
''' 
HELP['deletesms'] = '''Delete SMS from phone. See description for \\fBgetsms\\fR for info about
sms folders naming convention. Locations are numerated from 1.
'''
HELP['deleteallsms'] = '''Delete all SMS from specified SMS folder.
'''
HELP['getallsms'] = '''Get all SMS from phone. In some phones you will have also SMS templates
and info about locations used to save Picture Images. With each sms you
will see location. If you want to get such sms from phone alone, use
\\fBgammu getsms 0 location\\fR
'''
HELP['geteachsms'] = '''Similiary to \\fBgetallsms\\fR. Difference is, that links all contacenated sms
'''
HELP['getsmsc'] = '''Get SMSC settings from SIM card. Numerate locations from 1.
''' 
HELP['getsmsfolders'] = '''Get names for SMS folders in phone
'''
HELP['smsd FILES'] = '''SMS Deaemon. See smsdrc config file for more options
'''
HELP['getphoneringtone'] = '''
Get one of "default" ringtones and saves into file
'''
HELP['playsavedringtone'] = '''
Play one of "built" ringtones. This option is available for DCT4 phones. For getting ringtones list use getringtoneslist.
'''
HELP['getringtoneslist'] = '''
Get list of sounds 
'''
HELP['getringtone'] = '''Get ringtone from phone in RTTL or BINARY format. Locations are numerated from 1.
'''
HELP['setringtone'] = '''Set ringtone in phone. When don't give location, it will be written
"with preview" (in phones supporting this feature like 61xx or 6210).
When use RTTL ringtones, give location and use \\fB\\-scale\\fR, there will be written
scale info with each note. It will avoid scale problems available during
editing ringtone in composer from phone menu (for example, in N33xx).

\\fITIP:\\fR when use ~ char in ringtone name, in some phones (like 33xx)
name will blink later in phone menus
'''
HELP['copyringtone'] = '''Copy source ringtone to destination.
'''
HELP['playringtone'] = '''Play aproximation of ringtone over phone buzzer. File can be in RTTL or BINARY (Nokia DCT3) format.
'''
HELP['getringtoneslist'] = ''''''
HELP['nokiacomposer'] = '''Show, how to enter RTTL ringtone in composer existing in many Nokia phones
(and how should it look like).
''' 
HELP['dialvoice'] = '''Make voice call from SIM card line set in phone.
''' 
HELP['maketerminatedcall'] = '''Make voice call from SIM card line set in phone which will 
be terminated after \\fBlength\\fR seconds.
''' 
HELP['answercall'] = '''Answer incoming call.
'''
HELP['cancelcall'] = '''Cancel incoming call
'''
HELP['gettodo'] = ''''''
HELP['deletetodo'] = ''''''
HELP['getcalendarnotes'] = '''Get calendar notes from phone. In Nokia 3310 and 3330 they're named
"Reminders" and have some limitations (they depends on phone firmware version).
'''
HELP['getcategory'] = ''''''
HELP['getallcategies'] = ''''''
HELP['getwapbookmark'] = '''Get WAP bookmark(s) from phone. Locations are numerated from 1.
'''
HELP['deletewapbookmark'] = '''Delete WAP bookmark(s) from phone. Locations are numerated from 1.
'''
HELP['getwapsettings'] = '''Get WAP settings from phone. Locations are numerated from 1.
'''
HELP['getmmssettings'] = ''''''
HELP['getbitmap STARTUP'] = '''Get static startup logo from phone. Allow to save it in file.
'''
HELP['getbitmap CALLER'] = '''Get caller group logo from phone. Locations 1-5.
'''
HELP['getbitmap OPERATOR'] = '''Get operator logo (picture displayed instead of operator name) from phone.
''' 
HELP['getbitmap PICTURE'] = '''Get Picture Image from phone.
'''
HELP['getbitmap'] = '''Get startup text from phone.
'''
HELP['getbitmap'] = '''In some models it's possible to save dealer welcome note - text displayed
during enabling phone, which can't be edited from phone menu.  Here you can
get it.
'''
HELP['setbitmap STARTUP'] = '''Set startup logo in phone. It can be static (then you will have to give file
name) or one of predefined animated (only some phones like Nokia 3310 or 3330
supports it)
'''
HELP['setbitmap COLOURSTARTUP'] = ''''''
HELP['setbitmap WALLPAPER'] = '''''' 
HELP['setbitmap CALLER'] = '''Set caller logo.
''' 
HELP['setbitmap OPERATOR'] = '''Set operator logo in phone. When won't give file and netcode, operator logo
will be removed from phone. When will give only filename, operator logo will
be displayed for your current GSM operator. When give additionaly network
code, it will be displayed for this operator: \\fBgammu setbitmap OPERATOR file "260 02"\\fR
'''
HELP['setbitmap COLOUROPERATOR'] = '''''' 
HELP['setbitmap PICTURE'] = '''''' 
HELP['setbitmap TEXT'] = '''''' 
HELP['setbitmap DEALER'] = '''''' 
HELP['copybitmap'] = '''Allow to convert logos files to another. When give ONLY inputfile, output will
be written to stdout using ASCII art. When give output file and format, in
some file formats (like NLM) will be set indicator informing about logo type
to given.
'''
HELP['savefile CALENDAR'] = ''''''
HELP['savefile TODO'] = ''''''
HELP['savefile'] = '''''' 
HELP['savesms TEXT'] = '''Take text from stdin and save as text SMS into SIM/phone memory.

\\fB\\-folder number\\fR - save to specified folder. Numerate folders from 1.
The most often folder 1 = "Inbox", 2 = "Outbox",etc. Use \\fBgetsmsfolders\\fR to get folder list.

\\fB\\-unread\\fR - makes message unread. In some phones (like 6210)
you won't see unread sms envelope after saving such
sms. In some phones with internal SMS memory (like
6210) after using it with folder 1 SIM SMS memory will be used

\\fB\\-read\\fR - makes message read. In some phones with internal
SMS memory (like 6210) after using it with folder 1 SIM SMS memory will be used

\\fB\\-unsent\\fR - makes message unsent

\\fB\\-reply\\fR - reply SMSC is set

\\fB\\-sender number\\fR - set sender number (default: "Gammu")

\\fB\\-flash\\fR - Class 0 SMS

\\fB\\-smscset number\\fR - SMSC will be taken from set \\fBnumber\\fR. Default set: 1

\\fB\\-smscnumber number\\fR - SMSC number

\\fB\\-len len\\fR - specify, how many chars will be read. When use this
option and text will be longer than 1 SMS, will be splitted into more
linked SMS

\\fB\\-autolen len\\fR - specify, how many chars will be read. When use this
option and text will be longer than 1 SMS, will be splitted into more
linked SMS.Coding type (SMS default alphabet/Unicode) is set according
to input text

\\fB\\-enablevoice\\fR | \\fB\\-disablevoice\\fR | \\fB\\-enablefax \\fR |
\\fB\\-disablefax \\fR | \\fB\\-enableemail \\fR | \\fB\\-disableemail \\fR -
sms will set such indicators. Text will be cut to 1 sms.

\\fB\\-voidsms\\fR - many phones after receiving it won't display anything,
only beep, vibrate or turn on light. Text will be cut to 1 sms.

\\fB\\-unicode\\fR - SMS will be saved in Unicode format

\\fB\\-inputunicode\\fR - input text is in Unicode.

\\fITIP:\\fR
You can create Unicode file using WordPad in Win32 (during saving select
"Unicode Text Document" format). In Unix can use for example YUdit.

\\fB\\-replacemessages ID\\fR - \\fBID\\fR can be 1..7. When you will use option and
send more single SMS to one recipient with the same ID, each another SMS will
replace each previous with the same ID

\\fB\\-replacefile file\\fR  - when you want, you can make file in such format:
\\fBsrc_unicode_char1, dest_unicode_char1, src_unicode_char2, dest_unicode_char2\\fR
(everything in one line). After reading text for SMS from stdin there will
be made translation and each src char will be converted to dest char. In docs
there is example file (\\fIreplace.txt\\fR), which will change all "a" chars to "1"

\\fITIP:\\fR when use ~ char in sms text and \\fB\\-unicode\\fR option
(Unicode coding required), text of sms after ~ char will blink in some phones
(like N33xx)

\\fIExample:\\fR echo some_text | gammu savesms TEXT
'''
HELP['savesms RINGTONE'] = '''Read RTTL ringtone from file and save as SMS into SIM/phone memory.
Ringtone is saved in Nokia format.

\\fB\\-folder number\\fR - save to specified folder. Numerate forlders from 1.
The most often folder 1 = "Inbox", 2 = "Outbox", etc.

\\fB\\-unread\\fR - makes message unread. In some phones (like 6210) you won't see 
unread sms envelope after saving such sms. In some phones with internal 
SMS memory (like 6210) after using it with folder 1 SIM SMS memory will be used

\\fB\\-read\\fR - makes message read. In some phones with internal
SMS memory (like 6210) after using it with folder 1 SIM SMS memory will be used
\\fB\\-unsent\\fR - makes message unsent

\\fB\\-reply\\fR - reply SMSC is set

\\fB\\-sender number\\fR - set sender number

\\fB\\-flash\\fR - Class 0 SMS

\\fB\\-smscset number\\fR - SMSC will be taken from set \\fBnumber\\fR. Default set: 1

\\fB\\-smscnumber number\\fR - SMSC number

\\fB\\-long\\fR - ringtone is saved using Profile style. It can be longer (and saved
in 2 SMS), but decoded only by newer phones (like 33xx)

\\fB\\-scale\\fR - ringtone will have Scale info for each note. It will allow to edit
it correctly later in phone composer (for example, in 33xx)
'''
HELP['savesms OPERATOR'] = '''Save operator logo as sms (Nokia format - size 72x14 or 78x21 after
using \\fB\\-biglogo\\fR).
'''
HELP['savesms CALLER'] = '''Save caller logo as sms (Nokia format - size 72x14).
'''
HELP['savesms PICTURE'] = '''Save Picture Image as sms (Nokia format - size 72x28).
'''
HELP['savesms MMSINDICATOR'] = ''''''
HELP['savesms BOOKMARK'] = '''Read WAP bookmark from file created by \\fBbackup\\fR option and saves in
Nokia format as SMS
'''
HELP['savesms WAPSETTINGS'] = '''Read WAP settings from file created by \\fBbackup\\fR option and saves in Nokia format as SMS
'''
HELP['savesms MMSSETTINGS'] = '''''' 
HELP['savesms CALENDAR'] = '''Read calendar note from file created by \\fBbackup\\fR option and saves in
VCALENDAR 1.0 format as SMS
'''
HELP['savesms TODO'] = ''''''
HELP['savesms'] = '''Read phonebook entry from file created by \\fBbackup\\fR option and saves in
VCARD 1.0 (only name and default number) or VCARD 2.1 (all entry details with
all numbers, text and name) format as SMS
'''
HELP['savesms PROFILE'] = '''Read ringtone (RTTL) format and bitmap (Picture Image size) and name and save
as Nokia profile.
'''
HELP['savesms EMS'] = '''
Saves EMS sequence. All parameters after \\fB\\-unread\\fR (like \\fB\\-defsound\\fR) can be used few times.

\\fB\\-text\\fR - adds text

\\fB\\-unicodefiletext\\fR - adds text from Unicode file

\\fB\\-defanimation\\fR - adds default animation with ID specified by user.ID for different phones are different.

\\fB\\-animation\\fR - adds "frames" frames read from file1, file2, etc.

\\fB\\-defsound\\fR - adds default sound with ID specified by user. ID for different phones are different.

\\fB\\-tone10\\fR - adds IMelody version 1.0 read from RTTL or other compatible file

\\fB\\-tone10long\\fR - IMelody version 1.0 saved in one of few SMS with UPI. Phones compatible with UPI (like SonyEricsson phones) will read such ringtone as one

\\fB\\-tone12\\fR - adds IMelody version 1.2 read from RTTL or other compatible file

\\fB\\-tone12long\\fR - IMelody version 1.0 saved in one of few SMS with UPI. Phones compatible with UPI (like SonyEricsson phones) will read such ringtone as one

\\fB\\-toneSE\\fR - adds IMelody in "short" form supported by SonyEricsson phones

\\fB\\-tone10long\\fR - SonyEricsson IMelody saved in one or few SMS with UPI

\\fB\\-variablebitmap\\fR - bitmap in any size saved in one SMS

\\fB\\-variablebitmaplong\\fR - bitmap with maximal size 96x128 saved in one or few sms

\\fB\\-fixedbitmap \\fR - bitmap 16x16 or 32x32

\\fB\\-protected\\fR - all ringtones and bitmaps after this parameter (excluding default ringtones and logos) will be "protected" (in phones compatible with ODI like SonyEricsson products it won't be possible to forward them from phone menu)

\\fIExample:\\fR gammu savesms EMS \\-text "Greetings" \\-defsound 1 \\-text "from Gammu" \\-tone10 axelf.txt \\-animation 2 file1.bmp file2.bmp

will create EMS sequence with text "Greetings" and default sound 1 and text "from Gammu" and ringtone axelf.txt and 2 frame animation read from (1'st frame) file1.bmp and (2'nd frame) file2.bmp

\\fIExample:\\fR gammu savesms EMS \\-protected 2 \\-variablebitmaplong ala.bmp \\-toneSElong axelf.txt \\-toneSE ring.txt

ala.bmp and axelf.txt will be "protected"
'''
HELP['sendsms TEXT'] = ''''''
HELP['sendsms RINGTONE'] = ''''''
HELP['sendsms OPERATOR'] = ''''''
HELP['sendsms CALLER'] = '''''' 
HELP['sendsms PICTURE'] = ''''''
HELP['sendsms BOOKMARK'] = ''''''
HELP['sendsms WAPSETTINGS'] = ''''''
HELP['sendsms MMSSETTINGS'] = '''''' 
HELP['sendsms CALENDAR'] = ''''''
HELP['sendsms TODO'] = ''''''
HELP['sendsms'] = '''''' 
HELP['sendsms PROFILE'] = '''''' 
HELP['sendsms EMS'] = '''''' 
HELP['nokiagetoperatorname'] = '''6110.c phones have place for name for one GSM network (of course, with flashing it's
possible to change all names, but Gammu is not flasher ;\\-)). You can get this
name using this option.
''' 
HELP['nokiasetoperatorname'] = ''''''
HELP['nokiadisplayoutput'] = ''''''
HELP['nokiasetvibralevel'] = '''Set vibra power to "level" (given in percent)
'''
HELP['nokiagetvoicerecord'] = '''
Get voice record from location and save to WAV file. File is
coded using GSM 6.10 codec (available for example in win32). Name
of file is like name of voice record in phone.
'''
HELP['nokiasecuritycode'] = '''Get/reset to "12345" security code
''' 
HELP['nokiatests'] = '''Make tests for Nokia DCT3 phones

\\fINOTE:\\fR EEPROM test can show error, when your phone has EEPROM in flash
(like in 82xx/7110/62xx/33xx). The same Clock test will show error
when phone doesn't have internal battery for clock (like 3xxx)
...and for DCT4 (work in progress)
'''
HELP['nokiasetphonemenus'] = '''Enable all (?) possible menus for DCT3 Nokia phones:

1. ALS (Alternative Line Service) option menu
.br
2. vibra menu for 3210
.br
3. 3315 features in 3310 5.45 and higher
.br
4. two additional games (React and Logic) for 3210 5\\.31 and higher
.br
5. WellMate menu for 6150
.br
6. NetMonitor

and for DCT4:

1. ALS (Alternative Line Service) option menu
.br
2. Bluetooth, WAP bookmarks and settings menu, ... (6310i)
.br
3. GPRS Always Online
.br
 ...
'''
HELP['nokianetmonitor'] = '''Takes output or set netmonitor for Nokia DCT3 phones.

\\fITIP:\\fR For more info about this option, please visit
\\fIhttp://www.mwiacek.com\\fR and read netmonitor manual.

\\fITIP:\\fR test \\fB243\\fR enables all tests (after using command
\\fBgammu nokianetmonitor 243\\fR in some phones like 6210 or 9210 have to
reboot them to see netmonitor menu)
''' 
HELP['nokianetmonitor36'] = '''Reset counters from netmonitor test 36 in Nokia DCT3 phones.

\\fITIP:\\fR For more info about this option, please visit
\\fIwww.mwiacek.com\\fR and read netmonitor manual.
'''
HELP['siemensnetmonitor'] = '''''' 
HELP['backup'] = '''Backup your phone to file. It's possible to backup (depends on phone):

* phonebook from SIM and phone memory
.br
* calendar notes
.br
* SMSC settings
.br
* operator logo
.br
* startup (static) logo or startup text
.br
* WAP bookmarks
.br
* WAP settings
.br
* caller logos and groups
.br
* user ringtones
BSLen use text backup files. List can be extended on request.

\\fITIP:\\fR if you will backup settings to Gammu text file, it will be possible to edit
it. It's easy: many things in this file will be written double - once in Unicode,
once in ASCII. When you will remove Unicode version Gammu will use ASCII
on \\fBrestore\\fR (and you can easy edit ASCII text) and will convert it
according to your OS locale. When will be available Unicode version of text,
it will be used instead of ASCII (usefull with Unicode phones - it isn't important,
what locale is set in computer and no conversion Unicode \\-> ASCII and ASCII \\->
Unicode is done).

\\fITIP:\\fR you can use any editor with regular expressions function to edit
backup text file. Example: TextPad 4.2.2 from http://www.textpad.com/
with regular expressions based on POSIX standard P1003.2 is OK for it.
Few examples for it:

.br
* to remove info about voice tags:
.br
FROM: ^Entry\\\\([0\\-9][0\\-9]\\\\)VoiceTag = \\\\(.*\\\\)\\\\n
.br
TO:
.br

* to change all numbers starting from +3620, +3630, +3660, +3670
to +3620
.br
Find: Type = NumberGeneral\\\\nEntry\\\\([0\\-9][0\\-9]\\\\)Text = "\\\\+36\\\\(20\\\\|30\\\\|60\\\\|70\\\\)
.br
Repl: Type = NumberMobile\\\\nEntry\\\\1Text = "\\\\+3620
.br

* to change phone numbers type to mobile for numbers starting from
+3620, +3630,... and removing the corresponding TextUnicode line
.br
F: Type = NumberGeneral\\\\nEntry\\\\([0\\-9][0\\-9]\\\\)Text = "\\\\+36\\\\([2367]0\\\\)\\\\([^\\\\"]*\\\\)"\\\\nEntry\\\\([0\\-9][0\\-9]\\\\)TextUnicode = \\\\([^\\\\n]*\\\\)\\\\n
.br
R: Type = NumberMobile\\\\nEntry\\\\1Text = "\\\\+36\\\\2\\\\3"\\\\n
'''
HELP['backupsms'] = '''Stores all SMSes from phone to file.''' 
HELP['addsms'] = '''Adds SMSes from file (format like backupsms uses) to
selected folder in phone.'''
HELP['restoresms'] = '''Restores SMSes from file (format like backupsms uses) to
selected folder in phone. Please note that this overwrites existing
messages in phone (if it supports it).'''
HELP['restore'] = '''Restore settings written in file created using \\fBbackup option\\fR. All things
backup'ed by \\fBbackup\\fR can be restored (when made backup to Gammu text
file).

Please note that restoring deletes all current content in phone. If you
want only to add entries to phone, use addnew.

In some phones restoring calendar notes will not show error, but won't
be done, when phone doesn't have set clock inside.
'''
HELP['addnew'] = '''Adds settings written in file created using \\fBbackup option\\fR. All things
backup'ed by \\fBbackup\\fR can be restored (when made backup to Gammu text
file).
'''
HELP['clearall'] = '''''' 
HELP['decodesniff'] = '''Option available only, if Gammu was compiled with debug. Allows to decode
sniffs. See \\fI/docs/develop/develop.txt\\fR for more details.
''' 
HELP['decodebinarydump'] = '''After using option \\fBlogfile\\fR with name \\fBbinary\\fR (see \\fI/readme.txt\\fR for
info about this method of reporting bugs) created file can be decoded using
this option. It's available only, if Gammu was compiled with debug.

''' 

SECTION_HELP = {}
SECTION_HELP['sms'] = '''
Sending messages might look a bit complicated on first attempt to use.
But be patient, the command line has been written in order to allow
almost every usage. See EXAMPLES section for some hints on usage.
'''

# Code

import os
import re

SECTION_MATCHER = re.compile(' *([^ ]*) - (.*)')
COMMAND_MATCHER = re.compile('^([^ \n]*) (.*)')
COMMAND_SUBCOMMAND_MATCHER = re.compile('^([^ \n]*) ([A-Z0-9]*) (.*)')
COMMAND_MATCHER_NOPARAM = re.compile('^([^ \n]*)')

def read_help(section):
    pipe = os.popen('%s help %s' % (BIN_PATH, section))
    data = pipe.readlines()
    pipe.close()
    return data

def parse_sections(lines):
    sections = []
    section_data = {}
    for line in lines:
        match = SECTION_MATCHER.match(line)
        if match is None:
            continue
        section = match.groups()[0]
        sections.append(section)
        section_data[section] = match.groups()[1]
    return sections, section_data

def parse_section_help(lines):
    result = {}
    for line in lines:
        match = COMMAND_SUBCOMMAND_MATCHER.match(line)
        if match is None:
            match = COMMAND_MATCHER.match(line)
            if match is None:
                match = COMMAND_MATCHER_NOPARAM.match(line)
                command = match.groups()[0]
                options = ''
            else:
                command = match.groups()[0]
                options = match.groups()[1]
        else:
            command = '%s %s' % (match.groups()[0], match.groups()[1])
            options = match.groups()[2]
        result[command] = options
    return result

def get_command_help(command):
    try:
        return HELP[command]
    except KeyError:
        return ''

def write_section(output, name):
    output.write(SECTION % name)

def write_subsection(output, name):
    output.write(SUBSECTION % name)

def write_para(output, text):
    output.write(PARAGRAPH % text)

def write_command(output, name, params, help):
    if params == '':
        output.write(COMMAND_NOPARAM % (name, help))
    else: 
        output.write(COMMAND % (name, 
                params.replace('][', '] ['), 
                help))

def format_man_page(output, data):
    keys = data.keys()
    keys.sort()
    for command in keys:
        write_command(output, command, data[command].replace('-', '\\-'), get_command_help(command))

def main():
    text = read_help('')
    result = re.match('\[Gammu version ([0-9.]*) built [0-9:]* on (.*) using.*\]', text[0])
    build_date = result.groups()[1]
    version = result.groups()[0]
    syntax = text[2]

    syntax_help = []
    syntax_help.append(text[4] + text[5] + text[6])
    syntax_help.append(text[8])

    output = file(OUT_PATH, 'w')
    output.write(HEADER % {'version' : version, 'date' : build_date})

    write_section(output, 'NAME')
    output.write(NAME)

    write_section(output, 'SYNTAX')
    write_para(output, syntax.replace('[', '[\\fI').replace(']', '\\fP]'))

    write_section(output, 'DESCRIPTION')

    write_para(output, DESCRIPTION)

    write_section(output, 'OPTIONS')

    for line in syntax_help:
        write_para(output, line.replace('-', '\\-'))

    write_subsection(output, 'Debug levels')
    write_para(output, DEBUG_LEVELS)

    sections, section_data = parse_sections(text[12:])
    for section in sections:
        section_text = read_help(section)
        write_subsection(output, section_data[section])
        try:
            write_para(output, SECTION_HELP[section])
        except KeyError:
            pass
        data = parse_section_help(section_text[4:])
        format_man_page(output, data)

    write_section(output, 'FILES')
    output.write(FILES)

    write_section(output, 'EXAMPLES')
    output.write(EXAMPLES)

    write_section(output, 'LICENSE')
    output.write(LICENSE)

    write_section(output, 'BUGS')
    output.write(BUGS)

    write_section(output, 'AUTHORS')
    output.write(AUTHORS)

    write_section(output, 'SEE ALSO')
    output.write(SEE_ALSO)

    output.close()

if __name__ == '__main__':
    main()
