Imported Debian patch 2.4.4p3-2
[debian/amanda] / changer-src / chg-zd-mtx.sh.in
1 #!/bin/sh 
2 #
3 # Exit Status:
4 # 0 Alles Ok
5 # 1 Illegal Request
6 # 2 Fatal Error
7 #
8 # Contributed by Eric DOUTRELEAU <Eric.Doutreleau@int-evry.fr>
9 # This is supposed to work with Zubkoff/Dandelion version of mtx
10 #
11 # Modified by Joe Rhett <jrhett@isite.net>
12 # to work with MTX 1.2.9 by Eric Lee Green http://mtx.sourceforge.net
13 #
14 # Modified by Jason Hollinden <jhollind@sammg.com> on 13-Feb-2001
15 # to work with MTX 1.2.10, >9 slots, has barcode support, and works with
16 # multiple configs at once.
17 # NOTE:  Only tested the 2 additions with an ADIC Scalar 100.
18
19 ################################################################################
20 # Here are the things you need to do and know to configure this script:
21 #
22 #   * Figure out what the robot device name is and what the tape drive
23 #     device name is.  They will be different!
24 #
25 #     You cannot send robot commands to a tape drive and vice versa.
26 #     Both should respond to "mtx -f /dev/... inquiry".  Hopefully,
27 #     that output will make it obvious which is which.
28 #
29 #     For instance, here is what mtx has to say about my current robot:
30 #
31 #       Product Type: Medium Changer
32 #       Vendor ID: 'ATL     '
33 #       Product ID: 'ACL2640 206     '
34 #       Revision: '2A5A'
35 #       Attached Changer: No
36 #
37 #     and here is what it says about a tape drive:
38 #
39 #       Product Type: Tape Drive
40 #       Vendor ID: 'Quantum '
41 #       Product ID: 'DLT4000         '
42 #       Revision: 'CD50'
43 #       Attached Changer: No
44 #
45 #     Note the "Product Type" value makes it clear which is which.
46 #
47 #     If it is not obvious, "mf -f /dev/... rewind" should be happy when
48 #     talking to a (loaded) tape drive but the changer should give some
49 #     kind of error.  Similarly, "mtx -f /dev/... status" should show good
50 #     results with the changer but fail with a tape drive device name.
51 #
52 #     Once you have this figured out, set "changerdev" in amanda.conf
53 #     to the changer device and "tapedev" to the tape device.
54 #
55 #   * Find out what the first and last storage slots are.  Running
56 #     "mtx -f /dev/... status" should give you something like this
57 #     (although the output will vary widely based on the version of mtx
58 #     and the specifics of your robot):
59 #
60 #         Storage Changer /dev/changer:1 Drives, 9 Slots ( 0 Import/Export )
61 #       Data Transfer Element 0:Empty
62 #             Storage Element 1:Full :VolumeTag=SR0001
63 #             Storage Element 2:Full :VolumeTag=SR0002
64 #             Storage Element 3:Full :VolumeTag=SR0003
65 #             Storage Element 4:Full :VolumeTag=SR0004
66 #             Storage Element 5:Full :VolumeTag=SR0005
67 #             Storage Element 6:Full :VolumeTag=SR0006
68 #             Storage Element 7:Full :VolumeTag=SR0007
69 #             Storage Element 8:Full :VolumeTag=SR0008
70 #             Storage Element 9:Full :VolumeTag=SR0009
71 #
72 #     This says the first storage slot (element) is "1" and the last
73 #     is "9".  If you allocate the entire robot to Amanda, you do not need
74 #     to set the "firstslot" or "lastslot" configuration file variables --
75 #     the script will compute these values for you.
76 #
77 #     You do not have to allocate all of the slots for Amanda use,
78 #     but whatever slots you use must be contiguous (i.e. 4 through 9
79 #     in the above would be OK but 1, 2, 5, 6, 9 would not).  The one
80 #     exception to this is that if one of the slots contains a cleaning
81 #     cartridge, it may be in any slot (Amanda will just skip over it if
82 #     it is between firstslot and lastslot).
83 #
84 #   * Speaking of cleaning cartridges, if you have a storage slot dedicated
85 #     to one, figure out what slot it is in.  That slot number will go in
86 #     the "cleanslot" variable.
87 #
88 #     Also, decide if you want the changer script to automatically run
89 #     the cleaning tape through the drive after every so many mounts,
90 #     and how many mounts you want to do between cleanings.  If you
91 #     want the script to do this, set the "autoclean" variable to 1 and
92 #     the "autocleancount" to the number of mounts between cleanings.
93 #     If you do not want to do automatic cleanings (including not having
94 #     a cleaning cartridge in the robot), set "autoclean" to 0.
95 #
96 #     Note that only a count of mounts is used to determine when it is
97 #     time to clean.  The script does not try to detect if the drive is
98 #     requesting cleaning, or how much the drive was used on a given
99 #     mount.
100 #
101 #   * If you tell Amanda about a cleaning cartridge, whether for automatic
102 #     operation or manual (amtape <config> clean), you must also tell
103 #     the script how long it takes to run the cleaning cycle.  It is
104 #     impossible for the script to determine when the cleaning operation
105 #     is done, so the "cleancycle" variable is the number of seconds
106 #     the longest cleaning operation takes (you'll just have to figure
107 #     this out by watching it a few times, or maybe finding it in a tape
108 #     drive hardware manual).  The script will sleep for this length of
109 #     time whenever the cleaning tape is referenced.  The default is 120
110 #     seconds (two minutes).
111 #
112 #   * Figure out the drive slot number.  By default, it is set to 0.
113 #     In the example above, the tape drive ("Data Transfer Element")
114 #     is in slot 0. If your drive slot is not 0, you
115 #     need to set the drive slot number with the "driveslot" variable.
116 #
117 #   * Figure out whether your robot has a barcode reader and whether
118 #     your version of mtx supports it.  If you see "VolumeTag" entries
119 #     in the "mtx -f /dev/xxx status" output you did above, you have
120 #     a reader and mtx can work with it, so you may set the "havereader"
121 #     variable to 1.  The default is 0 (do not use a reader).
122 #
123 #   * Pick any tape to load and then determine if the robot can put it
124 #     away directly or whether an "offline" must be done first.
125 #
126 #     With the tape still mounted and ready, try to put the tape away
127 #     with "mtx".  If you get some kind of error, which is the most
128 #     common response, try "mt -f /dev/... offline", wait for the drive
129 #     to unload and make sure the robot takes no action on its own to
130 #     store the tape.  Assuming it does not, try the "mtx" command again
131 #     to store the tape.
132 #
133 #     If you had to issue the "mt -f /dev/... offline" before you could
134 #     use "mtx" to store the tape, set the "offline_before_unload"
135 #     variable to 1.  If "mtx" unloaded the drive and put the tape away
136 #     all by itself, set it to 0.
137 #
138 #   * Some drives and robots require a small delay between unloading the
139 #     tape and instructing the robot to move it back to storage.
140 #     For instance, if you try to grab the tape too soon on an ATL robot
141 #     with DLT tape drives, it will rip the leader out of the drive and
142 #     require sincerely painful hardware maintenance.
143 #
144 #     If you need a little delay, set the "unloadpause" variable to
145 #     the number of seconds to wait before trying to take a tape from
146 #     a drive back to storage.  The default is 0.
147 #
148 #   * Some drives also require a short pause after loading, or the drive
149 #     will return an I/O error during a test to see if it's online (which
150 #     this script uses "mt rewind" to test).  My drives don't recover from
151 #     this, and must be reloaded before they will come online after failing
152 #     such a test.  For this reason there is an "initial_poll_delay"
153 #     variable which will pause for a certain number of seconds before
154 #     looping through the online test for the first time.  The default is 0.
155 ####
156
157 ####
158 # Now you are ready to set up the variables in the changer configuration
159 # file.
160 #
161 # All variables are in "changerfile".conf where "changerfile" is set
162 # in amanda.conf.  For example, if amanda.conf has:
163 #
164 #       changerfile="/etc/amanda/Dailyset1/CHANGER"
165 #
166 # the variables must be in "/etc/amanda/Dailyset1/CHANGER.conf".
167 #
168 # If "changerfile" is a relative path, it is relative to the directory
169 # that contains amanda.conf.  That also happens to be the directory Amanda
170 # makes current before running this script.
171 #
172 # Here is a commented out example file with all the variables and showing
173 # their default value (if any):
174 ####
175 # firstslot=?               #### First storage slot (element) -- required
176 # lastslot=?                #### Last storage slot (element) -- required
177 # cleanslot=-1              #### Slot with cleaner tape -- default is "-1"
178 #                           #### Set negative to indicate no cleaner available
179 # driveslot=0               #### Drive slot number.  Defaults to 0
180 #                           #### Use the 'Data Transfer Element' you want
181 #
182 #   # Do you want to clean the drive after a certain number of accesses?
183 #   # NOTE - This is unreliable, since 'accesses' aren't 'uses', and we
184 #   #        have no reliable way to count this.  A single amcheck could
185 #   #        generate as many accesses as slots you have, plus 1.
186 #   # ALSO NOTE - many modern tape loaders handle this automatically.
187 #
188 # autoclean=0               #### Set to '1' or greater to enable
189 #
190 # autocleancount=99         #### Number of access before a clean.
191 #
192 # cleancycle=120            #### Time (seconds) to clean drive (default 120)
193 #
194 # havereader=0              #### If you have a barcode reader, set to 1.
195 #
196 # offline_before_unload=0   #### Does your robot require an
197 #                           #### 'mt offline' before mtx unload?
198 #
199 # poll_drive_ready=NN       #### Time (seconds) between tests to see if
200 #                           #### the tape drive has gone ready (default: 3).
201 #
202 # max_drive_wait=NN         #### Maximum time (seconds) to wait for the
203 #                           #### tape drive to become ready (default: 120).
204 #
205 # initial_poll_delay=NN     #### initial delay after load before polling for
206 #                           #### readiness
207 ####
208
209 ####
210 # Now it is time to test the setup.  Do all of the following in the
211 # directory that contains the amanda.conf file, and do all of it as
212 # the Amanda user.
213 #
214 #   * Run this:
215 #
216 #       .../chg-zd-mtx -info
217 #       echo $?             #### (or "echo $status" if you use csh/tcsh)
218 #
219 #     You should get a single line from the script like this (the actual
220 #     numbers will vary):
221 #
222 #       5 9 1 1
223 #
224 #     The first number (5) is the "current" slot.  This may or may not be
225 #     the slot actually loaded at the moment (if any).  It is the slot
226 #     Amanda will try to use next.
227 #
228 #     The second number (9) is the number of slots.
229 #
230 #     The third number will always be "1" and indicates the changer is
231 #     capable of going backward.
232 #
233 #     The fourth number is optional.  If you set $havereader to 1, it
234 #     will be "1", otherwise it will not be present.
235 #
236 #     The exit code ($? or $status) should be zero.
237 #
238 #   * Run this:
239 #
240 #       .../chg-zd-mtx -reset
241 #       echo $?
242 #
243 #     The script should output a line like this:
244 #
245 #       1 /dev/rmt/0mn
246 #
247 #     The number at the first should match $firstslot.  The device name
248 #     after that should be your tape device.
249 #
250 #     The exit code ($? or $status) should be zero.
251 #
252 #   * Run this:
253 #
254 #       .../chg-zd-mtx -slot next
255 #       echo $?
256 #
257 #     The script should output a line like this:
258 #
259 #       2 /dev/rmt/0mn
260 #
261 #     The number at the first should be one higher than $firstslot.
262 #     The device name after that should be your tape device.
263 #
264 #     The exit code ($? or $status) should be zero.
265 #
266 #   * Run this:
267 #
268 #       .../chg-zd-mtx -slot current
269 #       echo $?
270 #
271 #     Assuming the tape is still loaded from the previous test, the
272 #     robot should not move and the script should report the same thing
273 #     the previous command did.
274 #
275 #   * If you continue to run "-slot next" commands, the robot should load
276 #     each tape in turn then wrap back around to the first when it
277 #     reaches $lasttape.  If $cleanslot is within the $firstslot to
278 #     $lastslot range, the script will skip over that entry.
279 #
280 #   * Finally, try some of the amtape commands and make sure they work:
281 #
282 #       amtape <config> reset
283 #       amtape <config> slot next
284 #       amtape <config> slot current
285 #
286 #   * If you set $havereader non-zero, now would be a good time to create
287 #     the initial barcode database:
288 #
289 #       amtape <config> update
290 ####
291
292 ################################################################################
293 # To debug this script, first look in @AMANDA_DBGDIR@.  The script
294 # uses one of two log files there, depending on what version of Amanda
295 # is calling it.  It may be chg-zd-mtx.YYYYMMDD*.debug, or it may be
296 # changer.debug.driveN where 'N' is the drive number.
297 #
298 # If the log file does not help, try running the script, **as the Amanda
299 # user**, in the amanda.conf directory with whatever set of args the log
300 # said were used when you had a problem.  If nothing else useful shows up
301 # in the output, try running the script with the DEBUG environment variable
302 # set non-null, e.g.:
303 #
304 #       env DEBUG=yes .../chg-zd-mtx ...
305 ################################################################################
306
307 ################################################################################
308 # You may need to customize these things
309 ################################################################################
310
311 MT=@MT@
312 MTF=@MT_FILE_FLAG@
313 MTX=@MTX@
314
315 ################################################################################
316 # No user-level customization should be required beyond this point.
317 ################################################################################
318
319 test -n "$DEBUG" && set -x
320 TMPDIR="@AMANDA_TMPDIR@"
321 DBGDIR="@AMANDA_DBGDIR@"
322
323 argv0=$0
324 myname=`expr "$argv0" : '.*/\(.*\)'`
325
326 config=`pwd 2>/dev/null`
327 config=`expr "$config" : '.*/\(.*\)'`
328
329 ###
330 # Functions to write a new log file entry and append more log information.
331 ###
332
333 ds=`date '+%H:%M:%S' 2>/dev/null`
334 if [ $? -eq 0  -a  -n "$ds" ]; then
335         logprefix=`echo "$ds" | sed 's/./ /g'`
336 else
337         logprefix=""
338 fi
339
340 LogAppend() {
341         if [ -z "$logprefix" ]; then
342                 echo "$@" >> $DBGFILE
343         else
344                 echo "$logprefix" "$@" >> $DBGFILE
345         fi
346 }
347
348 Log() {
349         if [ -z "$logprefix" ]; then
350                 echo "===" "`date`" "===" >> $DBGFILE
351                 echo "$@" >> $DBGFILE
352         else
353                 ds=`date '+%H:%M:%S' 2>/dev/null`
354                 echo "$ds" "$@" >> $DBGFILE
355         fi
356 }
357
358 ###
359 # Common exit function.
360 #
361 #   $1 = exit code
362 #   $2 = slot result
363 #   $3 = additional information (error message, tape devive, etc)
364 ###
365
366 internal_call=0
367 Exit() {
368         if [ $internal_call -gt 0 ]; then
369                 call_type=Return
370         else
371                 call_type=Exit
372         fi
373         code=$1
374         shift
375         exit_slot=$1
376         shift
377         exit_answer="$@"
378         Log $call_type "($code)" "->" "$exit_slot" "$@"
379         echo "$exit_slot" "$@"
380         if [ $call_type = Return ]; then
381                 return $code
382         fi
383         amgetconf$SUF dbclose.$argv0:$DBGFILE > /dev/null 2>&1
384         exit $code
385 }
386
387 ###
388 # Function to run another command and log it.
389 ###
390
391 Run() {
392         Log Running: "$@"
393         rm -f $stdout $stderr
394         "$@" > $stdout 2> $stderr
395         exitcode=$?
396         Log Exit code: $exitcode
397         if [ -s $stdout ]
398         then
399                 LogAppend Stdout:
400                 cat $stdout >> $DBGFILE
401         fi
402         if [ -s $stderr ]
403         then
404                 LogAppend Stderr:
405                 cat $stderr >> $DBGFILE
406         fi
407         cat $stdout
408         cat $stderr 1>&2
409         return $exitcode
410 }
411
412 ###
413 # Return success if the arg is numeric.
414 ###
415
416 IsNumeric() {
417         test -z "$1" && return 1
418         x="`expr "$1" : '\([-0-9][0-9]*\)' 2>/dev/null`"
419         return `expr X"$1" != X"$x"`
420 }
421
422 ###
423 # Run $MTX status unless the previous output is still valid.
424 ###
425
426 mtx_status_valid=0
427 get_mtx_status() {
428         test -n "$DEBUG" && set -x
429         if [ $mtx_status_valid -ne 0 ]; then
430                 return 0
431         fi
432         rm -f $mtx_status
433         Run $MTX status > $mtx_status 2>&1
434         status=$?
435         if [ $status -eq 0 ]; then
436                 mtx_status_valid=1
437         fi
438         return $status
439 }
440
441 ###
442 # Determine the slot currently loaded.  Set $loadedslot to the slot
443 # currently loaded, or "-1", and $loadedbarcode to the corresponding
444 # barcode (or nothing).
445 ###
446
447 get_loaded_info() {
448         test -n "$DEBUG" && set -x
449         get_mtx_status
450
451         set x `sed -n '
452 /^Data Transfer Element:Empty/                          {
453     s/.*/-1/p
454     q
455 }
456 /^Data Transfer Element '$driveslot':Empty/             {
457     s/.*/-1/p
458     q
459 }
460 /^Data Transfer Element:Full.*:VolumeTag/               {
461     s/.*(Storage Element \([0-9][0-9]*\) Loaded):VolumeTag *= *\([^     ]*\)/\1 \2/p
462     q
463 }
464 /^Data Transfer Element '$driveslot':Full.*:VolumeTag/  {
465     s/.*(Storage Element \([0-9][0-9]*\) Loaded):VolumeTag *= *\([^     ]*\)/\1 \2/p
466     q
467 }
468 /^Data Transfer Element:Full/                           {
469     s/.*(Storage Element \([0-9][0-9]*\) Loaded)\(.*\)/\1/p
470     q
471 }
472 /^Data Transfer Element '$driveslot':Full/              {
473     s/.*(Storage Element \([0-9][0-9]*\) Loaded)\(.*\)/\1/p
474     q
475 }
476 ' < $mtx_status 2>&1`
477         shift                                   # get rid of the "x"
478         loadedslot=$1
479         loadedbarcode=$2
480
481         if [ -z "$loadedslot" ]; then
482                 Exit 2 "<none>" "could not determine current slot, are you sure your drive slot is $driveslot"
483                 return $?                       # in case we are internal
484         fi
485         if IsNumeric "$loadedslot" ; then
486                 :
487         else
488                 Exit 2 \
489                      "<none>" \
490                      "currently loaded slot ($loadedslot) not numeric"
491                 return $?                       # in case we are internal
492         fi
493         Log       "STATUS   -> currently loaded slot = $loadedslot"
494         LogAppend "         -> currently loaded barcode = \"$loadedbarcode\""
495 }
496
497 ###
498 # Get a list of slots between $firstslot and $lastslot, if they are set.
499 # If they are not set, set them to the first and last slot seen on the
500 # assumption the entire robot is to be used (???).
501 ###
502
503 slot_list=
504 get_slot_list() {
505         test -n "$DEBUG" && set -x
506         if [ -n "$slot_list" ]; then
507                 return
508         fi
509         get_mtx_status
510         slot_list=`sed -n '
511 /^Data Transfer Element:Full/                           {
512     s/.*(Storage Element \([0-9][0-9]*\) Loaded)\(.*\)/\1/p
513 }
514 /^Data Transfer Element '$driveslot':Full/              {
515     s/.*(Storage Element \([0-9][0-9]*\) Loaded)\(.*\)/\1/p
516 }
517 /^[     ]*Storage Element \([0-9][0-9]*\):Full/         {
518     s/.*Storage Element \([0-9][0-9]*\):.*/\1/p
519 }
520 ' < $mtx_status 2>&1 | grep -v "^${cleanslot}\$" | sort -n`
521         slot_list=`echo $slot_list`             # remove the newlines
522         if [ $firstslot -lt 0 -o $lastslot -lt 0 ]; then
523                 last=$lastslot
524                 for slot in $slot_list; do
525                         if [ $firstslot -lt 0 ]; then
526                                 Log "SLOTLIST -> firstslot set to $slot"
527                                 firstslot=$slot
528                         fi
529                         if [ $lastslot -lt 0 ]; then
530                                 last=$slot
531                         fi
532                 done
533                 if [ $lastslot -lt 0 -a $last -ge 0 ]; then
534                         Log "SLOTLIST -> lastslot set to $last"
535                         lastslot=$last
536                 fi
537                 if [ $firstslot -lt 0 ]; then
538                         Exit 2 \
539                              "<none>" \
540                              "cannot determine first slot"
541                         return $?               # in case we are internal
542                 elif [ $lastslot -lt 0 ]; then
543                         Exit 2 \
544                              "<none>" \
545                              "cannot determine last slot"
546                         return $?               # in case we are internal
547                 fi
548         fi
549         amanda_slot_list=
550         for slot in $slot_list; do
551                 if [ $slot -ge $firstslot -a $slot -le $lastslot ]; then
552                         amanda_slot_list="$amanda_slot_list $slot"
553                 fi
554         done
555         if [ -z "$amanda_slot_list" ]; then
556                 Exit 2 \
557                      "<none>" \
558                      "no slots available"
559                 return $?                       # in case we are internal
560         fi
561         slot_list="$amanda_slot_list"
562 }
563
564 # Paths
565 prefix=@prefix@
566 exec_prefix=@exec_prefix@
567 sbindir=@sbindir@
568 libexecdir=@libexecdir@
569
570 # try to hit all the possibilities here
571 PATH=$sbindir:$libexecdir:/usr/bin:/bin:/usr/sbin:/sbin:/usr/ucb:/usr/local/bin
572 export PATH
573
574 USE_VERSION_SUFFIXES="@USE_VERSION_SUFFIXES@"
575 if test "$USE_VERSION_SUFFIXES" = "yes"; then
576         SUF="-@VERSION@"
577 else
578         SUF=
579 fi
580
581 DBGFILE=`amgetconf$SUF dbopen.$argv0 2>/dev/null | grep -v BUGGY`
582 if [ -z "$DBGFILE" ]
583 then
584         DBGFILE=/dev/null                       # will try this again below
585 fi
586
587 changerfile=`amgetconf$SUF changerfile 2>/dev/null | grep -v BUGGY`
588 if [ -z "$changerfile" ]; then
589         Exit 2 \
590              "<none>" \
591              "changerfile must be specified in amanda.conf"
592 fi
593
594 tape=`amgetconf$SUF tapedev 2>/dev/null | grep -v BUGGY`
595 if [ -z "$tape" ]; then
596         Exit 2 \
597              "<none>" \
598              "tapedev may not be empty"
599 elif [ $tape = "/dev/null" -o `expr "$tape" : 'null:'` -eq 5 ]; then
600         Exit 2 \
601              "<none>" \
602              "tapedev ($tape) may not be the null device"
603 fi
604 TAPE=`amgetconf$SUF changerdev 2>/dev/null | grep -v BUGGY`
605 if [ -z "$TAPE" ]; then
606         Exit 2 \
607              "<none>" \
608              "changerdev may not be empty"
609 elif [ $TAPE = "/dev/null" ]; then
610         Exit 2 \
611              "<none>" \
612              "changerdev ($TAPE) may not be the null device"
613 fi
614 export TAPE                                     # for mtx command
615
616 #### Set up the various config files.
617
618 configfile=$changerfile.conf
619 cleanfile=$changerfile-clean
620 accessfile=$changerfile-access
621 slotfile=$changerfile-slot
622 labelfile=$changerfile-barcodes
623 [ ! -s $cleanfile ] && echo 0 > $cleanfile
624 [ ! -s $accessfile ] && echo 0 > $accessfile
625 [ ! -s $slotfile ] && echo -1 > $slotfile
626 [ ! -f $labelfile ] && > $labelfile
627 cleancount=`cat $cleanfile`
628 accesscount=`cat $accessfile`
629
630 #### Dig out of the config file what is needed
631
632 varlist=
633 varlist="$varlist firstslot"
634 varlist="$varlist lastslot"
635 varlist="$varlist cleanslot"
636 varlist="$varlist cleancycle"
637 varlist="$varlist OFFLINE_BEFORE_UNLOAD"        # old name
638 varlist="$varlist offline_before_unload"
639 varlist="$varlist unloadpause"
640 varlist="$varlist AUTOCLEAN"                    # old name
641 varlist="$varlist autoclean"
642 varlist="$varlist autocleancount"
643 varlist="$varlist havereader"
644 varlist="$varlist driveslot"
645 varlist="$varlist poll_drive_ready"
646 varlist="$varlist initial_poll_delay"
647 varlist="$varlist max_drive_wait"
648
649 for var in $varlist
650 do
651         val="`cat $configfile 2>/dev/null | sed -n '
652 # Ignore comment lines (anything starting with a #).
653 /^[     ]*#/d
654 # Find the first var=val line in the file, print the value and quit.
655 /^[     ]*'$var'[       ]*=[    ]*\([^  ][^     ]*\).*/ {
656         s/^[    ]*'$var'[       ]*=[    ]*\([^  ][^     ]*\).*/\1/p
657         q
658 }
659 '`"
660         eval $var=\"$val\"
661 done
662
663 # Deal with driveslot first so we can get DBGFILE set if we are still
664 # using the old amgetconf.
665
666 if [ -z "$driveslot" ]; then
667         driveslot=0;
668 fi
669
670 # Get DBGFILE set if it is not already.
671
672 if [ $DBGFILE = /dev/null ]; then
673         if [ -d "$DBGDIR" ]; then
674                 DBGFILE=$DBGDIR/changer.debug.drive$driveslot
675         else
676                 DBGFILE=/dev/null
677         fi
678         Log === Start "`date`" ===
679 fi
680 if [ -z "$driveslot" ]; then
681         Exit 2 \
682              "<none>" \
683              "cannot determine drive slot from $tape"
684 fi
685
686 stdout=$TMPDIR/$myname.1.$$
687 stderr=$TMPDIR/$myname.2.$$
688 mtx_status=$TMPDIR/$myname.status.$$
689 trap "rm -f $stdout $stderr $mtx_status" 0      # exit cleanup
690
691 Log "Using config file $configfile"
692
693 # Log the argument list.
694
695 Log "Arg info:"
696 LogAppend "\$# = $#"
697 i=0
698 LogAppend "\$$i = \"$argv0\""
699 for arg in "$@"; do
700         i=`expr $i + 1`
701         LogAppend "\$$i = \"$arg\""
702 done
703
704 # Set the default config values for those not in the file.  Log the
705 # results and make sure each is valid (numeric).
706
707 firstslot=${firstslot:-'-1'}                            # default: mtx status
708 lastslot=${lastslot:-'-1'}                              # default: mtx status
709 cleanslot=${cleanslot:-'-1'}                            # default: -1
710 cleancycle=${cleancycle:-'120'}                         # default: two minutes
711 if [ -z "$offline_before_unload" -a -n "$OFFLINE_BEFORE_UNLOAD" ]; then
712         offline_before_unload=$OFFLINE_BEFORE_UNLOAD    # (old name)
713 fi
714 offline_before_unload=${offline_before_unload:-'0'}     # default: 0
715 unloadpause=${unloadpause:-'0'}                         # default: 0
716 if [ -z "$autoclean" -a -n "$AUTOCLEAN" ]; then
717         autoclean=$AUTOCLEAN                            # (old name)
718 fi
719 autoclean=${autoclean:-'0'}                             # default: 0
720 autocleancount=${autocleancount:-'99'}                  # default: 99
721 havereader=${havereader:-'0'}                           # default: 0
722 poll_drive_ready=${poll_drive_ready:-'3'}               # default: three seconds
723 initial_poll_delay=${initial_poll_delay:-'0'}           # default: zero zeconds
724 max_drive_wait=${max_drive_wait:-'120'}                 # default: two minutes
725
726 get_slot_list
727
728 Log "Config info:"
729 for var in $varlist; do
730         if [ $var = "OFFLINE_BEFORE_UNLOAD" ]; then
731                 continue                        # old name
732         elif [ $var = "AUTOCLEAN" ]; then
733                 continue                        # old name
734         fi
735         eval val=\"'$'$var\"
736         if [ -z "$val" ]; then
737                 Exit 2 \
738                      "<none>" \
739                      "$var missing in $configfile"
740         fi
741         if IsNumeric "$val" ; then
742                 :
743         else
744                 Exit 2 \
745                      "<none>" \
746                      "$var ($val) not numeric in $configfile"
747         fi
748         LogAppend $var = \"$val\"
749 done
750
751 # Run the rest of the config file sanity checks.
752
753 if [ $firstslot -gt $lastslot ]; then
754         Exit 2 \
755              "<none>" \
756              "firstslot ($firstslot) greater than" \
757              "lastslot ($lastslot) in $configfile"
758 fi
759 if [ $autoclean -ne 0 -a $cleanslot -lt 0 ]; then
760         Exit 2 \
761              "<none>" \
762              "autoclean set but cleanslot not valid ($cleanslot)"
763 fi
764
765 # Set up the current slot
766
767 currentslot=`cat $slotfile`
768 if IsNumeric "$currentslot" ; then
769         if [ $currentslot -lt $firstslot ]; then
770                 Log "SETUP    -> current slot $currentslot" \
771                                  "less than $firstslot ..." \
772                                  "resetting to $firstslot"
773                 currentslot=$firstslot
774         elif [ $currentslot -gt $lastslot ]; then
775                 Log "SETUP    -> current slot $currentslot" \
776                                  "greater than $lastslot ..." \
777                                  "resetting to $lastslot"
778                 currentslot=$lastslot
779         fi
780 else
781         Log "SETUP    -> contents of $slotfile ($currentslot) invalid," \
782                          "setting current slot to first slot ($firstslot)"
783         currentslot=$firstslot
784 fi
785
786 found_current=0
787 first_slot_in_list=-1
788 next_slot_after_current=-1
789 for slot in $slot_list; do
790         if [ $first_slot_in_list -lt 0 ]; then
791                 first_slot_in_list=$slot        # in case $firstslot is missing
792         fi
793         if [ $slot -eq $currentslot ]; then
794                 found_current=1
795                 break
796         elif [ $slot -gt $currentslot ]; then
797                 next_slot_after_current=$slot   # $currentslot is missing
798                 break
799         fi
800 done
801 if [ $found_current -eq 0 ]; then
802         if [ $next_slot_after_current -lt 0 ]; then
803                 new_currentslot=$first_slot_in_list
804         else
805                 new_currentslot=$next_slot_after_current
806         fi
807         Log "WARNING  -> current slot $currentslot not available," \
808                          "setting current slot to next slot ($new_currentslot)"
809         currentslot=$new_currentslot
810 fi
811
812 # More routines.
813
814 ###
815 # Eject the current tape and put it away.
816 ###
817
818 eject() {
819         test -n "$DEBUG" && set -x
820         Log "EJECT    -> ejecting tape from $tape"
821         get_loaded_info 
822         if [ $loadedslot -gt 0 ]; then
823                 Log "EJECT    -> moving tape from drive $driveslot" \
824                                  "to storage slot $loadedslot"
825                 if [ $offline_before_unload -ne 0 ]; then
826                         Run $MT $MTF $tape offline > /dev/null 2>&1
827                 fi
828                 sleep $unloadpause
829                 result=`Run $MTX unload $loadedslot $driveslot 2>&1`
830                 status=$?
831                 Log "         -> status $status, result \"$result\""
832                 mtx_status_valid=0
833                 if [ $status -ne 0 ]; then
834                         answer="$result"
835                         code=2
836                 else
837                         answer="$tape"
838                         code=0
839                 fi
840         else
841                 answer="Drive was not loaded"
842                 code=1
843         fi
844         Exit $code "$loadedslot" "$answer"
845         return $?                               # in case we are internal
846 }
847
848 ###
849 # Reset the robot back to the first slot.
850 ###
851
852 reset() {
853         test -n "$DEBUG" && set -x
854         Log "RESET    -> loading tape from slot $firstslot" \
855                          "to drive $driveslot ($tape)"
856         # Call loadslot without doing it as an internal and let it finish
857         # things up.
858         loadslot $firstslot
859         # NOTREACHED
860         Exit 2 "<none>" "reset: should not get here"
861         return $?                               # in case we are internal
862 }
863
864 ###
865 # Unload the current tape (if necessary) and load a new one (unless
866 # "advance").  If no tape is loaded, get the value of "current" from
867 # $slotfile.
868 ###
869
870 loadslot() {
871         test -n "$DEBUG" && set -x
872         if [ $# -lt 1 ]; then
873                 Exit 2 "<none>" "Missing -slot argument"
874                 return $?                       # in case we are internal
875         fi
876         whichslot=$1
877         Log "LOADSLOT -> load drive $driveslot ($tape) from slot $whichslot"
878
879         numeric=`echo $whichslot | sed 's/[^0-9]//g'`
880         case $whichslot in
881         current|prev|next|advance)
882                 find_slot=$currentslot
883                 ;;
884         first)
885                 find_slot=$firstslot
886                 ;;
887         last)
888                 find_slot=$lastslot
889                 ;;
890         $numeric)
891                 find_slot=$numeric
892                 ;;
893         clean)
894                 find_slot=$cleanslot
895                 ;;
896         *)
897                 Exit 2 "<none>" "Illegal slot: \"$whichslot\""
898                 return $?                       # in case we are internal
899                 ;;
900         esac
901
902         # Find the requested slot in the slot list.  By loading the "set"
903         # command with multiple copies, we guarantee that if the slot is
904         # found, we can look both forward and backward without running
905         # off the end.  Putting $cleanslot at the end allows us to find
906         # that slot since it is not in $slot_list.
907         get_slot_list
908         set x $slot_list $slot_list $slot_list $cleanslot
909         shift                                   # get rid of the "x"
910         prev_slot=$1
911         shift
912         while [ $# -gt 0 ]; do
913                 if [ $1 -eq $find_slot ]; then
914                         break
915                 fi
916                 prev_slot=$1
917                 shift
918         done
919         if [ $# -le 0 ]; then
920                 Exit 2 \
921                      "<none>" \
922                      "Cannot find slot $find_slot" \
923                      "in slot list ($slot_list)"
924                 return $?                       # in case we are internal
925         fi
926
927         # Determine the slot to load.
928         case $whichslot in
929         next|advance)
930                 shift
931                 loadslot=$1
932                 ;;
933         prev)
934                 loadslot=$prev_slot
935                 ;;
936         *)
937                 loadslot=$find_slot
938         esac
939
940         # If the desired slot is already loaded, we are done.  Only update
941         # current slot if this is not the cleaning slot.
942         get_loaded_info
943         if [ $loadslot = $loadedslot ]; then
944                 if [ $loadslot -ne $cleanslot ]; then
945                         rm -f $slotfile
946                         echo $loadslot > $slotfile
947                 fi
948                 Exit 0 "$loadedslot" "$tape"
949                 return $?                       # in case we are internal
950         fi
951
952         # If we are loading the cleaning tape, bump the cleaning count
953         # and reset the access count.  Otherwise, bump the access count
954         # and see if it is time to do a cleaning.
955         if [ $loadslot = $cleanslot ]; then
956                 rm -f $cleanfile $accessfile
957                 expr $cleancount + 1 > $cleanfile
958                 echo 0 > $accessfile
959         else
960                 rm -f $accessfile
961                 expr $accesscount + 1 > $accessfile
962                 if [ $autoclean -ne 0 -a $accesscount -gt $autocleancount ]
963                 then
964                         internal_call=`expr $internal_call + 1`
965                         loadslot clean > /dev/null 2>&1
966                         status=$?
967                         internal_call=`expr $internal_call - 1`
968                         if [ $status -ne 0 ]; then
969                                 Exit $status "$loadslot" "$exit_answer"
970                                 return $?       # in case we are internal
971                         fi
972
973                         # Slot $cleanslot might contain an ordinary tape
974                         # rather than a cleaning tape.  A cleaning tape
975                         # *MIGHT* auto-eject; an ordinary tape does not.
976                         # We therefore have to read the status again to
977                         # check what actually happened.
978                         mtx_status_valid=0
979                         get_loaded_info
980                 fi
981         fi
982
983         # Unload whatever tape is in the drive.
984         internal_call=`expr $internal_call + 1`
985         eject > /dev/null 2>&1
986         status=$?
987         internal_call=`expr $internal_call - 1`
988         if [ $status -gt 1 ]; then
989                 Exit $status "$exit_slot" "$exit_answer"
990                 return $?                       # in case we are internal
991         fi
992
993         # If we were doing an "advance", we are done.
994         if [ $whichslot = advance ]; then
995                 if [ $loadslot -ne $cleanslot ]; then
996                         rm -f $slotfile
997                         echo $loadslot > $slotfile
998                 fi
999                 Exit 0 "$loadslot" "/dev/null"
1000                 return $?                       # in case we are internal
1001         fi
1002
1003         # Load the tape, finally!
1004         Log "LOADSLOT -> loading tape from slot $loadslot" \
1005                          "to drive $driveslot ($tape)"
1006         result=`Run $MTX load $loadslot $driveslot 2>&1`
1007         status=$?
1008         Log "         -> status $status, result \"$result\""
1009         mtx_status_valid=0
1010         if [ $status -ne 0 ]; then
1011                 Exit 2 "$loadslot" "$result"
1012                 return $?                       # in case we are internal
1013         fi
1014
1015         ###
1016         # Cleaning tapes never go "ready", so instead we just sit here
1017         # for "long enough" (as determined empirically by the user),
1018         # then return success.
1019         ###
1020         if [ $loadslot -eq $cleanslot ]; then
1021                 Run sleep $cleancycle
1022                 Exit 0 "$loadslot" "$tape"
1023                 return $?                       # in case we are internal
1024         fi
1025
1026         ###
1027         # Wait for the drive to go online.
1028         ###
1029         waittime=0
1030         ready=0
1031         sleep $initial_poll_delay
1032         while [ $waittime -lt $max_drive_wait ]; do
1033                 result=`Run $MT $MTF $tape rewind 2>&1`
1034                 if [ $? -eq 0 ]; then
1035                         ready=1
1036                         break
1037                 fi
1038                 sleep $poll_drive_ready
1039                 waittime=`expr $waittime + $poll_drive_ready`
1040         done
1041         if [ $ready -eq 0 ]; then
1042                 Exit 2 "$loadslot" "Drive not ready after" \
1043                                    "$max_drive_wait seconds," \
1044                                    "rewind said \"$result\""
1045                 return $?                       # in case we are internal
1046         fi
1047
1048         if [ $loadslot -ne $cleanslot ]; then
1049                 rm -f $slotfile
1050                 echo $loadslot > $slotfile
1051         fi
1052         Exit 0 "$loadslot" "$tape"
1053         return $?                               # in case we are internal
1054 }
1055
1056 ###
1057 # Return information about how the changer is configured and the current
1058 # state of the robot.
1059 ###
1060
1061 info() {
1062         test -n "$DEBUG" && set -x
1063         get_loaded_info
1064         get_slot_list
1065         Log       "INFO     -> first slot: $firstslot"
1066         LogAppend "         -> current slot: $currentslot"
1067         LogAppend "         -> loaded slot: $loadedslot"
1068         LogAppend "         -> last slot: $lastslot"
1069         LogAppend "         -> slot list: $slot_list"
1070         LogAppend "         -> can go backwards: 1"
1071         LogAppend "         -> havereader: $havereader"
1072
1073         ###
1074         # Check if a barcode reader is configured or not.  If so, it
1075         # passes the 4th item in the echo back to amtape signifying it
1076         # can search based on barcodes.
1077         ###
1078         reader=
1079         if [ $havereader -eq 1 ]; then
1080                 reader=1
1081         fi
1082
1083         if [ $currentslot -lt $firstslot -o $currentslot -gt $lastslot ]; then
1084                 currentslot=$firstslot          # what "current" will get
1085         fi
1086         set x $slot_list
1087         shift                                   # get rid of the "x"
1088         numslots=$#
1089         Exit 0 "$currentslot" "$numslots 1 $reader"
1090         return $?                               # in case we are internal
1091 }
1092
1093 ###
1094 # Read the labelfile and scan for a particular entry.
1095 ###
1096
1097 read_labelfile() {
1098         labelfile_entry_found=0
1099         labelfile_label=
1100         labelfile_barcode=
1101
1102         lbl_search=$1
1103         bc_search=$2
1104
1105         line=0
1106         while read lbl bc junk; do
1107                 line=`expr $line + 1`
1108                 if [ -z "$lbl" -o -z "$bc" -o -n "$junk" ]; then
1109                         Log       "ERROR    -> Line $line malformed: $lbl $bc $junk"
1110                         LogAppend "         -> Remove $labelfile" \
1111                                                "and run" \
1112                                                "\"$sbindir/amtape $config update\""
1113                         Exit 2 \
1114                              "<none>" \
1115                              "Line $line malformed in $labelfile: $lbl $bc $junk"
1116                         return $?               # in case we are internal
1117                 fi
1118                 if [ $lbl = "$lbl_search" -o $bc = "$bc_search" ]; then
1119                         if [ $labelfile_entry_found -ne 0 ]; then
1120                                 Log       "ERROR    -> Duplicate entries: $labelfile line $line"
1121                                 LogAppend "         -> Remove $labelfile" \
1122                                                        "and run" \
1123                                                        "\"$sbindir/amtape $config update\""
1124                                 Exit 2 \
1125                                      "<none>" \
1126                                      "Duplicate entries: $labelfile line $line"
1127                                 return $?       # in case we are internal
1128                         fi
1129                         labelfile_entry_found=1
1130                         labelfile_label=$lbl
1131                         labelfile_barcode=$bc
1132                 fi
1133         done
1134 }
1135
1136 ###
1137 # Adds the label and barcode for the currently loaded tape to the
1138 # barcode file.  Return an error if the database is messed up.
1139 ###
1140
1141 addlabel() {
1142         test -n "$DEBUG" && set -x
1143         if [ $# -lt 1 ]; then
1144                 Exit 2 "<none>" "Missing -label argument"
1145                 return $?                       # in case we are internal
1146         fi
1147         tapelabel=$1
1148         if [ $havereader -eq 0 ]; then
1149                 Exit 2 "<none>" "Not configured with barcode reader"
1150                 return $?                       # in case we are internal
1151         fi
1152         get_loaded_info
1153         if [ $loadedslot -lt 0 ]; then
1154                 Exit 1 "<none>" "No tape currently loaded"
1155                 return $?                       # in case we are internal
1156         fi
1157         Log       "LABEL    -> Adding label \"$tapelabel\"" \
1158                                "with barcode \"$loadedbarcode\"" \
1159                                "for slot $loadedslot" \
1160                                "into $labelfile"
1161         read_labelfile "$tapelabel" "$loadedbarcode" < $labelfile
1162         if [ $labelfile_entry_found -ne 0 ]; then
1163                 lf_val=
1164                 if [ "$labelfile_barcode" != "$loadedbarcode" ]; then
1165                         lf_type=label
1166                         lf_val=$tapelabel
1167                         val_type=barcode
1168                         old_val=$labelfile_barcode
1169                         new_val=$loadedbarcode
1170                 elif [ "$labelfile_label" != "$tapelabel" ]; then
1171                         lf_type=barcode
1172                         lf_val=$loadedbarcode
1173                         val_type=label
1174                         old_val=$labelfile_label
1175                         new_val=$tapelabel
1176                 fi
1177                 if [ -n "$lf_val" ]; then
1178                         LogAppend "ERROR    -> !!! Label database corrupted !!!"
1179                         LogAppend "         -> \"$old_val\" conflicts with" \
1180                                                "new $val_type \"$new_val\"" \
1181                                                "for $lf_type \"$lf_val\""
1182                         LogAppend "         -> Remove $labelfile" \
1183                                                "and run" \
1184                                                "\"$sbindir/amtape $config update\""
1185                         Exit 2 \
1186                              "<none>" \
1187                              "$tapelabel: \"$old_val\" conflicts with" \
1188                              "new $val_type \"$new_val\"" \
1189                              "for $lf_type \"$lf_val\""
1190                         return $?               # in case we are internal
1191                 fi
1192                 LogAppend "         -> already synced"
1193         else
1194                 echo "$tapelabel $loadedbarcode" >> $labelfile
1195                 LogAppend "         -> appended $labelfile entry:" \
1196                                        "$tapelabel $loadedbarcode"
1197         fi
1198         Exit 0 "$loadedslot" "$tape"
1199         return $?                               # in case we are internal
1200 }
1201
1202 ###
1203 # Look for a label in the barcode file.  If found, locate the slot it's
1204 # in by looking for the barcode in the mtx output, then load that tape.
1205 ###
1206
1207 searchtape() {
1208         test -n "$DEBUG" && set -x
1209         if [ $# -lt 1 ]; then
1210                 Exit 2 "<none>" "Missing -search argument"
1211                 return $?                       # in case we are internal
1212         fi
1213         tapelabel=$1
1214         if [ $havereader -eq 0 ]; then
1215                 Exit 2 "<none>" "Not configured with barcode reader"
1216                 return $?                       # in case we are internal
1217         fi
1218         Log "SEARCH   -> Hunting for label \"$tapelabel\""
1219         read_labelfile "$tapelabel" "" < $labelfile
1220         if [ $labelfile_entry_found -eq 0 ]; then
1221                 LogAppend "         -> !!! label \"$tapelabel\" not found" \
1222                                        "in $labelfile !!!"
1223                 LogAppend "         -> Remove $labelfile" \
1224                                        "and run" \
1225                                        "\"$sbindir/amtape $config update\""
1226                 Exit 2 \
1227                      "<none>" \
1228                      "$tapelabel: label \"$tapelabel\" not found in $labelfile"
1229                 return $?                       # in case we are internal
1230         fi
1231         LogAppend "         -> barcode is \"$labelfile_barcode\""
1232         get_mtx_status
1233         foundslot=`sed -n '
1234 /VolumeTag *= *'$labelfile_barcode' *$/                 {
1235         s/.*Storage Element \([0-9][0-9]*\).*/\1/p
1236         q
1237 }
1238 ' < $mtx_status`
1239         LogAppend "         -> foundslot is $foundslot"
1240         if [ -z "$foundslot" ]; then
1241                 LogAppend "ERROR    -> !!! Could not find slot" \
1242                                        "for barcode \"$labelfile_barcode\"!!!"
1243                 LogAppend "         -> Remove $labelfile" \
1244                                        "and run" \
1245                                        "\"$sbindir/amtape $config update\""
1246                 Exit 2 \
1247                      "<none>" \
1248                      "barcode \"$labelfile_barcode\"" \
1249                      "not found in mtx status output"
1250                 return $?                       # in case we are internal
1251         fi
1252         # Call loadslot without doing it as an internal and let it finish
1253         # things up.
1254         loadslot $foundslot
1255         # NOTREACHED
1256         Exit 2 "<none>" "searchtape: should not get here"
1257         return $?                               # in case we are internal
1258 }
1259
1260 ###
1261 # Program invocation begins here
1262 ###
1263
1264 if [ $# -lt 1 ]; then
1265         Exit 2 "<none>" "Usage: $myname -command args"
1266 fi
1267 cmd=$1
1268 shift
1269 case "$cmd" in
1270 -slot)
1271         loadslot "$@"
1272         ;;
1273 -info)
1274         info "$@"
1275         ;;
1276 -reset)
1277         reset "$@"
1278         ;;
1279 -eject)
1280         eject "$@"
1281         ;;
1282 -label) 
1283         addlabel "$@"
1284         ;;
1285 -search)
1286         searchtape "$@"
1287         ;;
1288 -clean)
1289         loadslot clean
1290         ;;
1291 *)
1292         Exit 2 "<none>" "unknown option: $cmd"
1293         ;;
1294 esac
1295
1296 Exit 2 "<none>" "$myname: should not get here"