]> arthur.barton.de Git - bup.git/commitdiff
replace test files with ones made up of bup code
authorJon Dowland <jmtd@debian.org>
Wed, 28 Apr 2010 12:58:54 +0000 (08:58 -0400)
committerAvery Pennarun <apenwarr@gmail.com>
Wed, 28 Apr 2010 12:58:54 +0000 (08:58 -0400)
This is needed to avoid possible questions about licensing in the source
data file.

t/sampledata/y/testfile1
t/testfile1
t/testfile2

index 13ae716417ed357d366cc543a2db14dea0629c54..afcd1f37ba621b8c453f61dd4e38a8cb40751ee4 100644 (file)
-#! /bin/sh -e
-
-# Check for daemon presence
-test -x /usr/sbin/acpid || exit 0
-
-# Check for ACPI support on kernel side
-[ -d /proc/acpi ] || exit 0
-
-# Include acpid defaults if available
-OPTIONS=""
-if [ -f /etc/default/acpid ] ; then
-       . /etc/default/acpid
-fi
-
-# Get lsb functions
-. /lib/lsb/init-functions
-. /etc/default/rcS
-
-if [ "x$VERBOSE" = "xno" ]; then
-        MODPROBE_OPTIONS="$MODPROBE_OPTIONS -Q"
-        export MODPROBE_OPTIONS
-fi
-
-# As the name says. If the kernel supports modules, it'll try to load
-# the ones listed in "MODULES".
-load_modules() {
-        PRINTK=`cat /proc/sys/kernel/printk`
-        [ "$VERBOSE" = no ] && echo "0 0 0 0" > /proc/sys/kernel/printk
+#!/usr/bin/env python
+from bup import options, drecurse
+from bup.helpers import *
+
+optspec = """
+bup drecurse <path>
+--
+x,xdev,one-file-system   don't cross filesystem boundaries
+q,quiet  don't actually print filenames
+profile  run under the python profiler
+"""
+o = options.Options('bup drecurse', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if len(extra) != 1:
+    o.fatal("exactly one filename expected")
+
+it = drecurse.recursive_dirlist(extra, opt.xdev)
+if opt.profile:
+    import cProfile
+    def do_it():
+        for i in it:
+            pass
+    cProfile.run('do_it()')
+else:
+    if opt.quiet:
+        for i in it:
+            pass
+    else:
+        for (name,st) in it:
+            print name
+
+if saved_errors:
+    log('WARNING: %d errors encountered.\n' % len(saved_errors))
+    sys.exit(1)
+#!/usr/bin/env python
+import sys, time, struct
+from bup import hashsplit, git, options, client
+from bup.helpers import *
+from subprocess import PIPE
+
+
+optspec = """
+bup split [-tcb] [-n name] [--bench] [filenames...]
+--
+r,remote=  remote repository path
+b,blobs    output a series of blob ids
+t,tree     output a tree id
+c,commit   output a commit id
+n,name=    name of backup set to update (if any)
+N,noop     don't actually save the data anywhere
+q,quiet    don't print progress messages
+v,verbose  increase log output (can be used more than once)
+copy       just copy input to output, hashsplitting along the way
+bench      print benchmark timings to stderr
+max-pack-size=  maximum bytes in a single pack
+max-pack-objects=  maximum number of objects in a single pack
+fanout=  maximum number of blobs in a single tree
+"""
+o = options.Options('bup split', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+git.check_repo_or_die()
+if not (opt.blobs or opt.tree or opt.commit or opt.name or
+        opt.noop or opt.copy):
+    o.fatal("use one or more of -b, -t, -c, -n, -N, --copy")
+if (opt.noop or opt.copy) and (opt.blobs or opt.tree or 
+                               opt.commit or opt.name):
+    o.fatal('-N is incompatible with -b, -t, -c, -n')
+
+if opt.verbose >= 2:
+    git.verbose = opt.verbose - 1
+    opt.bench = 1
+if opt.max_pack_size:
+    hashsplit.max_pack_size = parse_num(opt.max_pack_size)
+if opt.max_pack_objects:
+    hashsplit.max_pack_objects = parse_num(opt.max_pack_objects)
+if opt.fanout:
+    hashsplit.fanout = parse_num(opt.fanout)
+if opt.blobs:
+    hashsplit.fanout = 0
+
+is_reverse = os.environ.get('BUP_SERVER_REVERSE')
+if is_reverse and opt.remote:
+    o.fatal("don't use -r in reverse mode; it's automatic")
+start_time = time.time()
+
+refname = opt.name and 'refs/heads/%s' % opt.name or None
+if opt.noop or opt.copy:
+    cli = w = oldref = None
+elif opt.remote or is_reverse:
+    cli = client.Client(opt.remote)
+    oldref = refname and cli.read_ref(refname) or None
+    w = cli.new_packwriter()
+else:
+    cli = None
+    oldref = refname and git.read_ref(refname) or None
+    w = git.PackWriter()
+
+files = extra and (open(fn) for fn in extra) or [sys.stdin]
+if w:
+    shalist = hashsplit.split_to_shalist(w, files)
+    tree = w.new_tree(shalist)
+else:
+    last = 0
+    for (blob, bits) in hashsplit.hashsplit_iter(files):
+        hashsplit.total_split += len(blob)
+        if opt.copy:
+            sys.stdout.write(str(blob))
+        megs = hashsplit.total_split/1024/1024
+        if not opt.quiet and last != megs:
+            progress('%d Mbytes read\r' % megs)
+            last = megs
+    progress('%d Mbytes read, done.\n' % megs)
+
+if opt.verbose:
+    log('\n')
+if opt.blobs:
+    for (mode,name,bin) in shalist:
+        print bin.encode('hex')
+if opt.tree:
+    print tree.encode('hex')
+if opt.commit or opt.name:
+    msg = 'bup split\n\nGenerated by command:\n%r' % sys.argv
+    ref = opt.name and ('refs/heads/%s' % opt.name) or None
+    commit = w.new_commit(oldref, tree, msg)
+    if opt.commit:
+        print commit.encode('hex')
+
+if w:
+    w.close()  # must close before we can update the ref
         
-        LIST=`/sbin/lsmod|awk '!/Module/ {print $1}'`
-
-       # Get list of available modules
-        LOC="/lib/modules/`uname -r`/kernel/drivers/acpi"
-        LOC2="/lib/modules/`uname -r`/kernel/ubuntu/acpi"
-        if [ -d $LOC ]; then
-         MODAVAIL=`( find $LOC -type f -name "*.o" -printf "basename %f .o\n"; \
-               find $LOC -type f -name "*.ko" -printf "basename %f .ko\n" ) | /bin/sh`
-       else
-         MODAVAIL=""
-       fi
-
-        if [ -d $LOC2 ]; then
-         MODAVAIL="$MODAVAIL `( find $LOC2 -type f -name "*.o" -printf "basename %f .o\n"; \
-               find $LOC2 -type f -name "*.ko" -printf "basename %f .ko\n" ) | /bin/sh`"
-       fi
-
-        if [ "$MODULES" = "all" ]; then
-               MODULES="$MODAVAIL"
-        fi
-
-       if [ -n "$MODULES" ]; then
-               log_begin_msg "Loading ACPI modules..."
-               STATUS=0
-               for mod in $MODULES; do
-                       echo $MODAVAIL | grep -q -w "$mod" || continue
-                       if echo $LIST | grep -q -w "$mod"; then
-                               [ "$VERBOSE" != no ] && log_success_msg "Module already loaded: $mod"
-                       else
-                               if modprobe -b $mod 2>/dev/null; then
-                                       [ "$VERBOSE" != no ] && log_success_msg "Loaded module: $mod"
-                               else
-                                       if [ "$VERBOSE" != no ]; then
-                                               log_warning_msg "Unable to load module: $mod"
-                                       fi
-                               fi
-                       fi              
-               done
-               log_end_msg $STATUS
-       fi
-        echo "$PRINTK" > /proc/sys/kernel/printk
-}
-
-case "$1" in
-  start)
-    [ -f /proc/modules ] && load_modules
-    log_begin_msg "Starting ACPI services..."
-    start-stop-daemon --start --quiet --oknodo --exec /usr/sbin/acpid -- -c /etc/acpi/events $OPTIONS
-    log_end_msg $?
-    ;;
-  stop)
-    log_begin_msg "Stopping ACPI services..."
-    start-stop-daemon --stop --quiet --oknodo --retry 2 --exec /usr/sbin/acpid
-    log_end_msg $?
-    ;;
-  restart)
-    $0 stop
-    sleep 1
-    $0 start
-    ;;
-  reload|force-reload) 
-    log_begin_msg "Reloading ACPI services..."
-    start-stop-daemon --stop --signal 1 --exec /usr/sbin/acpid
-    log_end_msg $?
-    ;;
-  *)
-    log_success_msg "Usage: /etc/init.d/acpid {start|stop|restart|reload|force-reload}"
-    exit 1
-esac
-
-exit 0
-#!/bin/bash
-# INIT script to check whether we're on batteries, and so start with laptop 
-# mode etc enabled.
-
-# BUGS: unless we start *really* late, we have no way of throttling 
-# xscreensaver, since it won't be there to command.
-. /usr/share/acpi-support/power-funcs
-
-test -f /lib/lsb/init-functions || exit 1
-. /lib/lsb/init-functions
-
-test -d /var/lib/acpi-support || exit 0
-
-shopt -s nullglob
-
-case "$1" in
-  start)
-    log_begin_msg "Checking battery state..."
-    /etc/acpi/power.sh
-    # Source everything in /etc/acpi/start.d/
-    for SCRIPT in /etc/acpi/start.d/*.sh; do
-       . $SCRIPT
-    done
-    log_end_msg 0
-    ;;
-  stop)
-    log_begin_msg "Disabling power management..."
-    /etc/acpi/power.sh stop
-    log_end_msg 0
-    ;;
-  *)
-  ;;
-esac
-        
-
-#!/bin/sh
-#
-# alsa-utils initscript
-#
-### BEGIN INIT INFO
-# Provides:          alsa-utils
-# Required-Start:    $remote_fs
-# Required-Stop:     $remote_fs
-# Default-Start:     S
-# Default-Stop:      0 6
-# Short-Description: Restore and store ALSA driver settings
-# Description:       This script stores and restores mixer levels on
-#                    shutdown and bootup.On sysv-rc systems: to
-#                    disable storing of mixer levels on shutdown,
-#                    remove /etc/rc[06].d/K50alsa-utils.  To disable
-#                    restoring of mixer levels on bootup, rename the
-#                    "S50alsa-utils" symbolic link in /etc/rcS.d/ to
-#                    "K50alsa-utils".
-### END INIT INFO
-
-# Don't use set -e; check exit status instead
-
-# Exit silently if package is no longer installed
-[ -x /sbin/alsactl ] || exit 0
-
-PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
-MYNAME=/etc/init.d/alsa-utils
-
-. /lib/lsb/init-functions
-
-# $1 EXITSTATUS
-# [$2 MESSAGE]
-log_action_end_msg_and_exit()
-{
-       log_action_end_msg "$1" ${2:+"$2"}
-       exit $1
-}
-
-# $1 PROGRAM
-executable()
-{
-       # If which is not available then we must be running before
-       # /usr is mounted on a system that has which in /usr/bin/.
-       # Conclude that $1 is not executable.
-       [ -x /bin/which ] || [ -x /usr/bin/which ] || return 1
-       which "$1" >/dev/null 2>&1
-}
-
-# Wait for filesystems to show up
-while [ ! -d /usr/bin -o ! -d /var/lib/alsa ]; do
-       sleep 0.2
-done
-
-executable amixer || { echo "${MYNAME}: Error: No amixer program available." >&2 ; exit 1 ; }
-
-bugout() { echo "${MYNAME}: Programming error" >&2 ; exit 123 ; }
-
-# $1 <card ID> | "all"
-restore_levels()
-{
-       [ -f /var/lib/alsa/asound.state ] || return 1
-       CARD="$1"
-       [ "$1" = all ] && CARD=""
-       # Assume that if alsactl prints a message on stderr
-       # then it failed somehow.  This works around the fact
-       # that alsactl doesn't return nonzero status when it
-       # can't restore settings for the card
-       if MSG="$(alsactl restore $CARD 2>&1 >/dev/null)" && [ ! "$MSG" ] ; then
-               return 0
-       else
-               # Retry with the "force" option.  This restores more levels
-               # but it results in much longer error messages.
-               alsactl -F restore $CARD >/dev/null 2>&1
-               [ -z "$CARD" ] && log_action_cont_msg "warning: 'alsactl restore' failed with error message '$MSG'"
-               return 1
-       fi
-}
-
-# $1 <card ID> | "all"
-store_levels()
-{
-       CARD="$1"
-       [ "$1" = all ] && CARD=""
-       if MSG="$(alsactl store $CARD 2>&1)" ; then
-               sleep 1
-               return 0
-       else
-               [ -z "$CARD" ] && log_action_cont_msg "warning: 'alsactl store' failed with error message '$MSG'"
-               return 1
-       fi
-}
-
-echo_card_indices()
-{
-       if [ -f /proc/asound/cards ] ; then
-               sed -n -e's/^[[:space:]]*\([0-7]\)[[:space:]].*/\1/p' /proc/asound/cards
-       fi
-}
-
-filter_amixer_output()
-{
-       sed \
-               -e '/Unable to find simple control/d' \
-               -e '/Unknown playback setup/d' \
-               -e '/^$/d'
-}
-
-# The following functions try to set many controls.
-# No card has all the controls and so some of the attempts are bound to fail.
-# Because of this, the functions can't return useful status values.
-
-# $1 <control>
-# $2 <level>
-# $CARDOPT
-unmute_and_set_level()
-{
-       { [ "$2" ] && [ "$CARDOPT" ] ; } || bugout
-       amixer $CARDOPT -q set "$1" "$2" unmute 2>&1 | filter_amixer_output || :
-       return 0
-}
-
-# $1 <control>
-# $CARDOPT
-mute_and_zero_level()
-{
-       { [ "$1" ] && [ "$CARDOPT" ] ; } || bugout
-       amixer $CARDOPT -q set "$1" "0%" mute 2>&1 | filter_amixer_output || :
-       return 0
-}
-
-# $1 <control>
-# $2 "on" | "off"
-# $CARDOPT
-switch_control()
-{
-       { [ "$2" ] && [ "$CARDOPT" ] ; } || bugout
-       amixer $CARDOPT -q set "$1" "$2" 2>&1 | filter_amixer_output || :
-       return 0
-}
-
-# $1 <card ID>
-sanify_levels_on_card()
-{
-       CARDOPT="-c $1"
-
-       unmute_and_set_level "Front" "80%"
-       unmute_and_set_level "Master" "80%"
-       unmute_and_set_level "Master Mono" "80%"   # See Bug#406047
-       unmute_and_set_level "Master Digital" "80%"   # E.g., cs4237B
-       unmute_and_set_level "Playback" "80%"
-       unmute_and_set_level "Headphone" "70%"
-       unmute_and_set_level "PCM" "80%"
-       unmute_and_set_level "PCM,1" "80%"   # E.g., ess1969
-       unmute_and_set_level "DAC" "80%"     # E.g., envy24, cs46xx
-       unmute_and_set_level "DAC,0" "80%"   # E.g., envy24
-       unmute_and_set_level "DAC,1" "80%"   # E.g., envy24
-       unmute_and_set_level "Synth" "80%"
-       unmute_and_set_level "CD" "80%"
-
-       mute_and_zero_level "Mic"
-       mute_and_zero_level "IEC958"         # Ubuntu #19648
-
-       # Intel P4P800-MX  (Ubuntu bug #5813)
-       switch_control "Master Playback Switch" on
-       switch_control "Master Surround" on
-
-       # Trident/YMFPCI/emu10k1:
-       unmute_and_set_level "Wave" "80%"
-       unmute_and_set_level "Music" "80%"
-       unmute_and_set_level "AC97" "80%"
-
-       # DRC:
-       unmute_and_set_level "Dynamic Range Compression" "80%"
-
-       # Required for HDA Intel (hda-intel):
-       unmute_and_set_level "Front" "80%"
-
-       # Required for SB Live 7.1/24-bit (ca0106):
-       unmute_and_set_level "Analog Front" "80%"
-
-       # Required at least for Via 823x hardware on DFI K8M800-MLVF Motherboard with kernels 2.6.10-3/4 (see ubuntu #7286):
-       switch_control "IEC958 Capture Monitor" off
-
-       # Required for hardware allowing toggles for AC97 through IEC958,
-       #  valid values are 0, 1, 2, 3. Needs to be set to 0 for PCM1.
-       unmute_and_set_level "IEC958 Playback AC97-SPSA" "0"
-
-       # Required for newer Via hardware (see Ubuntu #31784)
-       unmute_and_set_level "VIA DXS,0" "80%"
-       unmute_and_set_level "VIA DXS,1" "80%"
-       unmute_and_set_level "VIA DXS,2" "80%"
-       unmute_and_set_level "VIA DXS,3" "80%"
-
-       # Required on some notebooks with ICH4:
-       switch_control "Headphone Jack Sense" off
-       switch_control "Line Jack Sense" off
-
-       # Some machines need one or more of these to be on;
-       # others need one or more of these to be off:
-       #
-       # switch_control "External Amplifier" on
-       switch_control "Audigy Analog/Digital Output Jack" on
-       switch_control "SB Live Analog/Digital Output Jack" on
-       
-       # D1984 -- Thinkpad T61/X61
-       switch_control "Speaker" on
-       switch_control "Headphone" on
-
-       # HDA-Intel w/ "Digital" capture mixer (See Ubuntu #193823)
-       unmute_and_set_level "Digital" "80%"
-
-       return 0
-}
-
-# $1 <card ID> | "all"
-sanify_levels()
-{
-       TTSDML_RETURNSTATUS=0
-       case "$1" in
-         all)
-               for CARD in $(echo_card_indices) ; do
-                       sanify_levels_on_card "$CARD" || TTSDML_RETURNSTATUS=1
-               done
-               ;;
-         *)
-               sanify_levels_on_card "$1" || TTSDML_RETURNSTATUS=1
-               ;;
-       esac
-       return $TTSDML_RETURNSTATUS
-}
-
-# $1 <card ID>
-preinit_levels_on_card()
-{
-       CARDOPT="-c $1"
-
-       # Silly dance to activate internal speakers by default on PowerMac
-       # Snapper and Tumbler
-       id=`cat /proc/asound/card$1/id 2>/dev/null`
-       if [ "$id" = "Snapper" -o "$id" = "Tumbler" ]; then
-               switch_control "Auto Mute" off
-               switch_control "PC Speaker" off
-               switch_control "Auto Mute" on
-       fi
-}
-
-# $1 <card ID> | "all"
-preinit_levels()
-{
-       TTSDML_RETURNSTATUS=0
-       case "$1" in
-         all)
-               for CARD in $(echo_card_indices) ; do
-                       preinit_levels_on_card "$CARD" || TTSDML_RETURNSTATUS=1
-               done
-               ;;
-         *)
-               preinit_levels_on_card "$1" || TTSDML_RETURNSTATUS=1
-               ;;
-       esac
-       return $TTSDML_RETURNSTATUS
-}
-
-# $1 <card ID>
-mute_and_zero_levels_on_card()
-{
-       CARDOPT="-c $1"
-       for CTL in \
-               Master \
-               PCM \
-               Synth \
-               CD \
-               Line \
-               Mic \
-               "PCM,1" \
-               Wave \
-               Music \
-               AC97 \
-               "Master Digital" \
-               DAC \
-               "DAC,0" \
-               "DAC,1" \
-               Headphone \
-               Playback \
-               Speaker
-       do
-               mute_and_zero_level "$CTL"
-       done
-#      for CTL in \
-#              "Audigy Analog/Digital Output Jack" \
-#              "SB Live Analog/Digital Output Jack"
-#      do
-#              switch_control "$CTL" off
-#      done
-       return 0
-}
-
-# $1 <card ID> | "all"
-mute_and_zero_levels()
-{
-       TTZML_RETURNSTATUS=0
-       case "$1" in
-         all)
-               for CARD in $(echo_card_indices) ; do
-                       mute_and_zero_levels_on_card "$CARD" || TTZML_RETURNSTATUS=1
-               done
-               ;;
-         *)
-               mute_and_zero_levels_on_card "$1" || TTZML_RETURNSTATUS=1
-               ;;
-       esac
-       return $TTZML_RETURNSTATUS
-}
-
-
-# $1 <card ID> | "all"
-card_OK()
-{
-       [ "$1" ] || bugout
-       if [ "$1" = all ] ; then
-               [ -d /proc/asound ]
-               return $?
-       else
-               [ -d "/proc/asound/card$1" ] || [ -d "/proc/asound/$1" ]
-               return $?
-       fi
-}
-
-# If a card identifier is provided in $2 then regard it as an error
-# if that card is not present; otherwise don't regard it as an error.
-
-case "$1" in
-  start)
-       EXITSTATUS=0
-       TARGET_CARD="$2"
-       case "$TARGET_CARD" in
-         ""|all) TARGET_CARD=all ; log_action_begin_msg "Setting up ALSA" ;;
-       esac
-       if ! card_OK "$TARGET_CARD"; then
-               [ "$TARGET_CARD" = "all" ] && log_action_end_msg "$( [ ! "$2" ] ; echo $? ; )" "none loaded"
-               exit $?
-       fi
-       preinit_levels "$TARGET_CARD" || EXITSTATUS=1
-       if ! restore_levels "$TARGET_CARD" ; then
-               sanify_levels "$TARGET_CARD" || EXITSTATUS=1
-               restore_levels "$TARGET_CARD" >/dev/null 2>&1 || :
-       fi
-       [ "$TARGET_CARD" = "all" ] && log_action_end_msg_and_exit "$EXITSTATUS"
-       exit $EXITSTATUS
-       ;;
-  stop)
-       EXITSTATUS=0
-       TARGET_CARD="$2"
-       case "$TARGET_CARD" in
-         ""|all) TARGET_CARD=all ; log_action_begin_msg "Shutting down ALSA" ;;
-         *) log_action_begin_msg "Shutting down ALSA card ${TARGET_CARD}" ;;
-       esac
-       card_OK "$TARGET_CARD" || log_action_end_msg_and_exit "$( [ ! "$2" ] ; echo $? ; )" "none loaded"
-       store_levels "$TARGET_CARD" || EXITSTATUS=1
-       mute_and_zero_levels "$TARGET_CARD" || EXITSTATUS=1
-       log_action_end_msg_and_exit "$EXITSTATUS"
-       ;;
-  restart|force-reload)
-       EXITSTATUS=0
-       $0 stop || EXITSTATUS=1
-       $0 start || EXITSTATUS=1
-       exit $EXITSTATUS
-       ;;
-  reset)
-       TARGET_CARD="$2"
-       case "$TARGET_CARD" in
-         ""|all) TARGET_CARD=all ; log_action_begin_msg "Resetting ALSA" ;;
-         *) log_action_begin_msg "Resetting ALSA card ${TARGET_CARD}" ;;
-       esac
-       card_OK "$TARGET_CARD" || log_action_end_msg_and_exit "$( [ ! "$2" ] ; echo $? ; )" "none loaded"
-       preinit_levels "$TARGET_CARD"
-       sanify_levels "$TARGET_CARD"
-       log_action_end_msg_and_exit "$?"
-       ;;
-  *)
-       echo "Usage: $MYNAME {start [CARD]|stop [CARD]|restart [CARD]|reset [CARD]}" >&2
-       exit 3
-       ;;
-esac
-
-#!/bin/bash -e
-#
-# apache2              This init.d script is used to start apache2.
-#                      It basically just calls apache2ctl.
-
-ENV="env -i LANG=C PATH=/usr/local/bin:/usr/bin:/bin"
-
-#edit /etc/default/apache2 to change this.
-NO_START=0
-
-set -e
-if [ -x /usr/sbin/apache2 ] ; then
-       HAVE_APACHE2=1
-else
-       exit 0
-fi
-
-. /lib/lsb/init-functions
-
-test -f /etc/default/rcS && . /etc/default/rcS
-test -f /etc/default/apache2 && . /etc/default/apache2
-if [ "$NO_START" != "0" -a "$1" != "stop" ]; then 
-        [ "$VERBOSE" != "no" ] && log_warning_msg "Not starting apache2 - edit /etc/default/apache2 and change NO_START to be 0.";
-        exit 0;
-fi
-
-APACHE2="$ENV /usr/sbin/apache2"
-APACHE2CTL="$ENV /usr/sbin/apache2ctl"
-
-apache_stop() {
-       PID=""
-       PIDFILE=""
-       AP_CONF=/etc/apache2/apache2.conf
-
-       # apache2 allows more than PidFile entry in the config but only the
-       # last found in the config is used; we attempt to follow includes
-       # here, but only first-level includes are supported, not nested ones
-
-       for i in $AP_CONF `awk '$1 ~ /^\s*[Ii]nclude$/ && $2 ~ /^\// {print $2}' $AP_CONF`; do
-               PIDFILE=`grep -i ^PidFile $i | tail -n 1 | awk '{print $2}'`
-               if [ -e "$PIDFILE" ]; then
-                       PID=`cat $PIDFILE`
-               fi
-       done
-       
-       errors=`$APACHE2 -t 2>&1`
-       if [ $? = 0 ]; then
-               # if the config is ok than we just stop normaly
-
-               if [ -n "$PID" ]
-               then
-                       $APACHE2CTL stop
-
-                       CNT=0
-                       while [ 1 ]
-                       do
-                               CNT=$(expr $CNT + 1)
-               
-                               [ ! -d /proc/$PID ] && break
-
-                               if [ $CNT -gt 60 ]
-                               then
-                                       if [ "$VERBOSE" != "no" ]; then
-                                               echo " ... failed!"
-                                               echo "Apache2 failed to honor the stop command, please investigate the situation by hand."
-                                       fi
-                                       return 1
-                               fi
-
-                               sleep 1
-                       done
-               else
-                       if [ "$VERBOSE" != "no" ]; then
-                               echo -n " ... no pidfile found! not running?"
-                       fi
-               fi
-
-       else
-               [ "$VERBOSE" != "no" ] && echo "$errors"
-
-               # if we are here something is broken and we need to try
-               # to exit as nice and clean as possible
-
-               # if pidof is null for some reasons the script exits automagically
-               # classified as good/unknown feature
-               PIDS=`pidof apache2` || true
-
-               REALPID=0
-               # if there is a pid we need to verify that belongs to apache2
-               # for real
-               for i in $PIDS; do
-                       if [ "$i" = "$PID" ]; then
-                               # in this case the pid stored in the
-                               # pidfile matches one of the pidof apache
-                               # so a simple kill will make it
-                               REALPID=1
-                       fi
-               done
-
-               if [ $REALPID = 1 ]; then
-                       # in this case everything is nice and dandy
-                       # and we kill apache2
-                       kill $PID
-               else
-                       # this is the worst situation... just kill all of them
-                       #for i in $PIDS; do
-                       #       kill $i
-                       #done
-                       # Except, we can't do that, because it's very, very bad
-                       if [ "$PIDS" ] && [ "$VERBOSE" != "no" ]; then
-                                echo " ... failed!"
-                               echo "You may still have some apache2 processes running.  There are"
-                               echo "processes named 'apache2' which do not match your pid file,"
-                               echo "and in the name of safety, we've left them alone.  Please review"
-                               echo "the situation by hand."
-                        fi
-                        return 1
-               fi
-       fi
-}
-
-# Stupid hack to keep lintian happy. (Warrk! Stupidhack!).
-case $1 in
-       start)
-               [ -f /etc/apache2/httpd.conf ] || touch /etc/apache2/httpd.conf
-               # ssl_scache shouldn't be here if we're just starting up.
-               [ -f /var/run/apache2/ssl_scache ] && rm -f /var/run/apache2/*ssl_scache*
-               # /var/run and /var/lock could be on a tmpfs
-               [ ! -d /var/run/apache2 ] && mkdir /var/run/apache2
-               [ ! -d /var/lock/apache2 ] && mkdir /var/lock/apache2
-               # Make sure /var/lock/apache2 has the correct permissions
-               chown www-data /var/lock/apache2
-
-               log_begin_msg "Starting apache 2.0 web server..."
-               if $APACHE2CTL startssl; then
-                        log_end_msg 0
-                else
-                        log_end_msg 1
-                fi
-       ;;
-       stop)
-               log_begin_msg "Stopping apache 2.0 web server..."
-               if apache_stop; then
-                        log_end_msg 0
-                else
-                        log_end_msg 1
-                fi
-       ;;
-       reload)
-               log_begin_msg "Reloading apache 2.0 configuration..."
-               if $APACHE2CTL graceful $2 ; then
-                        log_end_msg 0
-                else
-                        log_end_msg 1
-                fi
-       ;;
-       restart | force-reload)
-               log_begin_msg "Forcing reload of apache 2.0 web server..."
-               if ! apache_stop; then
-                        log_end_msg 1
-                fi
-               if $APACHE2CTL startssl; then
-                        log_end_msg 0
-                else
-                        log_end_msg 1
-                fi
-       ;;
-       status)
-               exit 4
-       ;;
-       *)
-               echo "Usage: /etc/init.d/apache2 start|stop|restart|reload|force-reload" >&2
-               exit 2
-       ;;
-esac
-#! /bin/sh -e
-#### BEGIN INIT INFO
-# Provides:          atd
-# Required-Start:    $syslog $time $local_fs $remote_fs
-# Required-Stop:     $syslog $time $local_fs $remote_fs
-# Default-Start:     2 3 4 5
-# Default-Stop:      S 0 1 6
-# Short-Description: Deferred execution scheduler
-# Description:       Debian init script for the atd deferred executions
-#                    scheduler
-### END INIT INFO
-#
-# Author:      Ryan Murray <rmurray@debian.org>
-#
-set -e
-
-PATH=/bin:/usr/bin:/sbin:/usr/sbin
-DAEMON=/usr/sbin/atd
-
-test -x $DAEMON || exit 0
-
-. /lib/lsb/init-functions
-
-case "$1" in
-    start)
-       log_daemon_msg "Starting deferred execution scheduler" "atd"
-       start_daemon $DAEMON
-       log_end_msg $?
-    ;;
-  stop)
-       log_daemon_msg "Stopping deferred execution scheduler" "atd"
-       killproc $DAEMON
-       log_end_msg $?
-    ;;
-  force-reload|restart)
-    $0 stop
-    $0 start
-    ;;
-  *)
-    echo "Usage: /etc/init.d/atd {start|stop|restart|force-reload}"
-    exit 1
-    ;;
-esac
-
-exit 0
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          binfmt-support
-# Required-Start:    $local_fs $remote_fs
-# Required-Stop:     $local_fs $remote_fs
-# Default-Start:     2 3 4 5
-# Default-Stop:      0 1 6
-# Short-Description: Support for extra binary formats
-# Description:       Enable support for extra binary formats using the Linux
-#                    kernel's binfmt_misc facility.
-### END INIT INFO
-
-PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
-NAME=binfmt-support
-DESC="additional executable binary formats"
-
-test -x /usr/sbin/update-binfmts || exit 0
-
-. /lib/lsb/init-functions
-. /etc/default/rcS
-
-set -e
-CODE=0
-
-case "$1" in
-  start)
-    log_daemon_msg "Enabling $DESC" "$NAME"
-    update-binfmts --enable || CODE=$?
-    log_end_msg $CODE
-    exit $CODE
-    ;;
-
-  stop)
-    log_daemon_msg "Disabling $DESC" "$NAME"
-    update-binfmts --disable || CODE=$?
-    log_end_msg $CODE
-    exit $CODE
-    ;;
-
-  restart|force-reload)
-    $0 stop
-    $0 start
-    ;;
-
-  *)
-    N=/etc/init.d/$NAME
-    echo "Usage: $N {start|stop|restart|force-reload}" >&2
-    exit 1
-    ;;
-esac
-
-exit 0
-#!/bin/sh
-#
-# bootclean
-#
-# Clean /tmp
-#
-# DO NOT RUN AFTER S:55bootmisc.sh and do not run this script directly
-# in runlevel S. Instead write an initscript to call it.
-#
-
-. /lib/init/vars.sh
-
-. /lib/lsb/init-functions
-
-# Should be called outside verbose message block
-mkflagfile()
-{
-       # Prevent symlink attack  (See #264234.)
-       [ -L "$1" ] && log_warning_msg "bootclean: Deleting symbolic link '$1'."
-       rm -f "$1" || { log_failure_msg "bootclean: Failure deleting '$1'." ; return 1 ; }
-       # No user processes should be running, so no one should be able to introduce
-       # a symlink here.  As an extra precaution, set noclobber.
-       set -o noclobber
-       :> "$1" || { log_failure_msg "bootclean: Failure creating '$1'." ; return 1 ; }
-       return 0
-}
-
-clean_tmp() {
-       cd /tmp || { log_failure_msg "bootclean: Could not cd to /tmp." ; return 1 ; }
-
-       #
-       # Only clean out /tmp if it is world-writable. This ensures
-       # it really is a/the temp directory we're cleaning.
-       #
-       [ "$(find . -maxdepth 0 -perm -002)" = "." ] || return 0
-
-       if [ ! "$TMPTIME" ]
-       then
-               log_warning_msg "Using default TMPTIME 0."
-               TMPTIME=0
-       fi
-
-       [ "$VERBOSE" = no ] || log_action_begin_msg "Cleaning /tmp"
-
-       #
-       # Remove regardless of TMPTIME setting
-       #
-       rm -f .X*-lock
-
-       #
-       # Don't clean remaining files if TMPTIME is negative or 'infinite'
-       #
-       case "$TMPTIME" in
-         -*|infinite|infinity)
-               [ "$VERBOSE" = no ] || log_action_end_msg 0 "skipped"
-               return 0
-               ;;
-       esac
-
-       #
-       # Wipe /tmp, excluding system files, but including lost+found
-       #
-       # If TMPTIME is set to 0, we do not use any ctime expression
-       # at all, so we can also delete files with timestamps
-       # in the future!
-       #
-       if [ "$TMPTIME" = 0 ] 
-       then
-               TEXPR=""
-               DEXPR=""
-       else
-               TEXPR="-mtime +$TMPTIME -ctime +$TMPTIME -atime +$TMPTIME"
-               DEXPR="-mtime +$TMPTIME -ctime +$TMPTIME"
-       fi
-
-       EXCEPT='! -name .
-               ! ( -path ./lost+found -uid 0 )
-               ! ( -path ./quota.user -uid 0 )
-               ! ( -path ./aquota.user -uid 0 )
-               ! ( -path ./quota.group -uid 0 )
-               ! ( -path ./aquota.group -uid 0 )
-               ! ( -path ./.journal -uid 0 )
-               ! ( -path ./.clean -uid 0 )
-               ! ( -path './...security*' -uid 0 )'
-
-       mkflagfile /tmp/.clean || return 1
-
-       report_err()
-       {
-               if [ "$VERBOSE" = no ]
-               then
-                       log_failure_msg "bootclean: Failure cleaning /tmp."
-               else
-                       log_action_end_msg 1 "bootclean: Failure cleaning /tmp"
-               fi
-       }
-
-       #
-       # First remove all old files...
-       # (Use xargs here so that only one additional process gets created)
-       #
-       find . -depth -xdev $TEXPR $EXCEPT ! -type d \
-               -print0 | xargs -0r rm -f -- \
-               || { report_err ; return 1 ; }
-
-       #
-       # ...and then all empty directories
-       # (Don't use xargs here because dirs must be removed one by one from
-       # the bottom up)
-       #
-       find . -depth -xdev $DEXPR $EXCEPT -type d -empty \
-               -exec rmdir \{\} \; \
-               || { report_err ; return 1 ; }
-
-       [ "$VERBOSE" = no ] || log_action_end_msg 0
-       return 0
-}
-
-which find >/dev/null 2>&1 || exit 1
-which xargs >/dev/null 2>&1 || exit 1
-
-# If there are flag files that have not been created by root
-# then remove them
-for D in /tmp
-do
-       if [ -f $D/.clean ]
-       then
-               which stat >/dev/null 2>&1 && cleanuid="$(stat -c %u $D/.clean)"
-               # Poor's man stat %u, since stat (and /usr) might not be
-               # available in some bootup stages
-               [ "$cleanuid" ] || cleanuid="$(find $D/.clean -printf %U)"
-               [ "$cleanuid" ] || { log_failure_msg "bootclean: Could not stat '$D/.clean'." ; exit 1 ; }
-               if [ "$cleanuid" -ne 0 ]
-               then
-                       rm -f $D/.clean || { log_failure_msg "bootclean: Could not delete '$D/.clean'." ; exit 1 ; }
-               fi
-       fi
-done
-
-[ -f /tmp/.clean ] && exit 0
-
-ES=0
-[ -d /tmp ] && ! [ -f /tmp/.clean ] && { clean_tmp || ES=1 ; }
-exit $ES
-
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          bootlogd
-# Required-Start:    mountdevsubfs
-# Required-Stop:
-# Default-Start:     S
-# Default-Stop:
-# Short-Description: Start or stop bootlogd.
-# Description:       Starts or stops the bootlogd log program
-#                    which logs boot messages.
-### END INIT INFO
-
-PATH=/sbin:/bin
-DAEMON=/sbin/bootlogd
-[ -x "$DAEMON" ] || exit 0
-NAME=bootlogd
-DESC="boot logger"
-BOOTLOGD_OPTS="-r -c"
-[ -r /etc/default/bootlogd ] && . /etc/default/bootlogd
-. /lib/init/vars.sh
-
-. /lib/lsb/init-functions
-
-# Because bootlogd is broken on some systems, we take the special measure
-# of requiring it to be enabled by setting an environment variable.
-case "$BOOTLOGD_ENABLE" in
-  [Nn]*)
-       exit 0
-       ;;
-esac
-
-# Previously this script was symlinked as "stop-bootlogd" which, when run
-# with the "start" argument, should stop bootlogd.  Now stop-bootlogd is
-# a distinct script, but for backward compatibility this script continues
-# to implement the old behavior.
-SCRIPTNAME=${0##*/}
-SCRIPTNAME=${SCRIPTNAME#[SK]??}
-ACTION="$1"
-case "$0" in
-  *stop-bootlog*)
-       [ "$ACTION" = start ] && ACTION=stop
-       ;;
-esac
-
-case "$ACTION" in
-  start)
-       # PATH is set above
-       log_daemon_msg "Starting $DESC" "$NAME"
-       if [ -d /proc/1/. ]
-       then
-               umask 027
-               start-stop-daemon --start --quiet --exec $DAEMON -- \
-                       $BOOTLOGD_OPTS
-               ES=$?
-       else
-               $DAEMON $BOOTLOGD_OPTS
-               ES=$?
-       fi
-       log_end_msg $ES
-       ;;
-  stop)
-       PATH=/sbin:/bin:/usr/sbin:/usr/bin
-       log_daemon_msg "Stopping $DESC" "$NAME"
-       start-stop-daemon --stop --quiet --exec $DAEMON
-       ES=$?
-       sleep 1
-       log_end_msg $ES
-       if [ -f /var/log/boot ] && [ -f /var/log/boot~ ]
-       then
-               [ "$VERBOSE" = no ] || log_action_begin_msg "Moving boot log file"
-               # bootlogd writes to boot, making backup at boot~
-               cd /var/log && {
-                       chgrp adm boot || :
-                       savelog -q -p -c 5 boot \
-                       && mv boot.0 boot \
-                       && mv boot~ boot.0
-               }
-               ES=$?
-               [ "$VERBOSE" = no ] || log_action_end_msg $ES
-       fi
-       ;;
-  restart|force-reload)
-       /etc/init.d/bootlogd stop
-       /etc/init.d/bootlogd start
-       ;;
-  *)
-       echo "Usage: $SCRIPTNAME {start|stop|restart|force-reload}" >&2
-       exit 3
-       ;;
-esac
-
-:
-#!/bin/sh
-### BEGIN INIT INFO
-# Provides:          bootmisc
-# Required-Start:    $local_fs hostname $remote_fs
-# Required-Stop:     $local_fs
-# Default-Start:     S
-# Default-Stop:
-# Short-Description: Miscellaneous things to be done during bootup.
-# Description:
-### END INIT INFO
-
-PATH=/usr/sbin:/usr/bin:/sbin:/bin
-[ "$DELAYLOGIN" ] || DELAYLOGIN=yes
-. /lib/init/vars.sh
-
-do_start () {
-       #
-       # If login delaying is enabled then create the flag file
-       # which prevents logins before startup is complete
-       #
-       case "$DELAYLOGIN" in
-         Y*|y*)
-               echo "System bootup in progress - please wait" > /var/lib/initscripts/nologin
-               ;;
-       esac
-
-       # Create /var/run/utmp so we can login.
-       : > /var/run/utmp
-       if grep -q ^utmp: /etc/group
-       then
-               chmod 664 /var/run/utmp
-               chgrp utmp /var/run/utmp
-       fi
-
-       # Set pseudo-terminal access permissions.
-       if [ ! -e /dev/.devfsd ] && [ -c /dev/ttyp0 ]
-       then
-               chmod -f 666 /dev/tty[p-za-e][0-9a-f]
-               chown -f root:tty /dev/tty[p-za-e][0-9a-f]
-       fi
-
-       # Update motd
-       uname -snrvm > /var/run/motd
-       [ -f /etc/motd.tail ] && cat /etc/motd.tail >> /var/run/motd
-
-       # Save kernel messages in /var/log/dmesg
-       if which dmesg >/dev/null 2>&1
-       then
-               savelog -q -p -c 5 /var/log/dmesg
-               dmesg -s 524288 > /var/log/dmesg
-               chgrp adm /var/log/dmesg || :
-       elif [ -c /dev/klog ]
-       then
-               savelog -q -p -c 5 /var/log/dmesg
-               dd if=/dev/klog of=/var/log/dmesg &
-               sleep 1
-               kill $!
-               [ -f /var/log/dmesg ] && { chgrp adm /var/log/dmesg || : ; }
-       fi
-
-       # Remove bootclean's flag files.
-       # Don't run bootclean again after this!
-       rm -f /tmp/.clean
-}
-
-case "$1" in
-  start|"")
-       do_start
-       ;;
-  restart|reload|force-reload)
-       echo "Error: argument '$1' not supported" >&2
-       exit 3
-       ;;
-  stop)
-       # No-op
-       ;;
-  *)
-       echo "Usage: bootmisc.sh [start|stop]" >&2
-       exit 3
-       ;;
-esac
-
-:
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          checkfs
-# Required-Start:    modutils checkroot
-# Required-Stop:
-# Should-Start:      lvm cryptdisks
-# Should-Stop:
-# Default-Start:     S
-# Default-Stop:
-# Short-Description: Check all filesystems.
-### END INIT INFO
-
-PATH=/sbin:/bin
-FSCK_LOGFILE=/var/log/fsck/checkfs
-[ "$FSCKFIX" ] || FSCKFIX=no
-. /lib/init/vars.sh
-. /lib/init/usplash-fsck-functions.sh
-
-. /lib/lsb/init-functions
-
-# Always output fsck progress
-stdin=`readlink /proc/self/fd/0`
-if [ "${stdin#/dev/null}" != "$stdin" ]; then
-    exec </dev/console >/dev/console 2>&1
-fi
-
-do_start () {
-       # See if we're on AC Power
-       # If not, we're not gonna run our check
-       if which on_ac_power >/dev/null 2>&1
-       then
-               on_ac_power >/dev/null 2>&1
-               if [ $? -eq 1 ]
-               then
-                       [ "$VERBOSE" = no ] || log_success_msg "Running on battery power, so skipping file system check."
-                       BAT=yes
-               fi
-       fi
-
-       #
-       # Check the rest of the file systems.
-       #
-       if [ ! -f /fastboot ] && [ ! "$BAT" ] && [ "$FSCKTYPES" != "none" ]
-       then
-               if [ -f /forcefsck ]
-               then
-                       force="-f"
-               else
-                       force=""
-               fi
-               if [ "$FSCKFIX" = yes ]
-               then
-                       fix="-y"
-               else
-                       fix="-a"
-               fi
-               spinner="-C"
-               case "$TERM" in
-                 dumb|network|unknown|"")
-                       spinner=""
-                       ;;
-               esac
-               [ "$(uname -m)" = s390 ] && spinner=""  # This should go away
-               FSCKTYPES_OPT=""
-               [ "$FSCKTYPES" ] && FSCKTYPES_OPT="-t $FSCKTYPES"
-               handle_failed_fsck() {
-                       log_failure_msg "File system check failed. 
-A log is being saved in ${FSCK_LOGFILE} if that location is writable. 
-Please repair the file system manually."
-                       log_warning_msg "A maintenance shell will now be started. 
-CONTROL-D will terminate this shell and resume system boot."
-                       # Start a single user shell on the console
-                       if ! sulogin $CONSOLE
-                       then
-                               log_failure_msg "Attempt to start maintenance shell failed. 
-Continuing with system boot in 5 seconds."
-                               sleep 5
-                       fi
-               }
-               if [ "$VERBOSE" = no ]
-               then
-                       log_action_begin_msg "Checking file systems"
-                        if pidof usplash; then
-                            PROGRESS_FILE=`mktemp` || exit 1
-                            set -m
-                            logsave -s $FSCK_LOGFILE fsck -C3 -R -A $fix $force $FSCKTYPES_OPT >/dev/console 2>&1 3>$PROGRESS_FILE &
-                            set +m
-                            usplash_progress "$PROGRESS_FILE"
-                            rm -f $PROGRESS_FILE
-                        else
-                            logsave -s $FSCK_LOGFILE fsck $spinner -R -A $fix $force $FSCKTYPES_OPT
-                            FSCKCODE=$?
-                        fi
-
-                       if [ "$FSCKCODE" -gt 1 ]
-                       then
-                               log_action_end_msg 1 "code $FSCKCODE"
-                               handle_failed_fsck
-                       else
-                               log_action_end_msg 0
-                       fi
-               else
-                       if [ "$FSCKTYPES" ]
-                       then
-                               log_action_msg "Will now check all file systems of types $FSCKTYPES"
-                       else
-                               log_action_msg "Will now check all file systems"
-                       fi
-                       logsave -s $FSCK_LOGFILE fsck $spinner -V -R -A $fix $force $FSCKTYPES_OPT
-                       FSCKCODE=$?
-                       if [ "$FSCKCODE" -gt 1 ]
-                       then
-                               handle_failed_fsck
-                       else
-                               log_success_msg "Done checking file systems. 
-A log is being saved in ${FSCK_LOGFILE} if that location is writable."
-                       fi
-               fi
-       fi
-       rm -f /fastboot /forcefsck
-}
-
-case "$1" in
-  start|"")
-       do_start
-       ;;
-  restart|reload|force-reload)
-       echo "Error: argument '$1' not supported" >&2
-       exit 3
-       ;;
-  stop)
-       # No-op
-       ;;
-  *)
-       echo "Usage: checkfs.sh [start|stop]" >&2
-       exit 3
-       ;;
-esac
-
-:
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          checkroot
-# Required-Start:    mountdevsubfs
-# Required-Stop:     
-# Should-Start:      keymap hwclockfirst
-# Should-stop:
-# Default-Start:     S
-# Default-Stop:
-# Short-Description: Check to root file system.
-### END INIT INFO
-
-PATH=/lib/init:/sbin:/bin
-FSCK_LOGFILE=/var/log/fsck/checkroot
-[ "$FSCKFIX" ] || FSCKFIX=no
-[ "$SULOGIN" ] || SULOGIN=no
-. /lib/init/vars.sh
-. /lib/init/usplash-fsck-functions.sh
-
-. /lib/lsb/init-functions
-
-# Always output fsck progress
-stdin=`readlink /proc/self/fd/0`
-if [ "${stdin#/dev/null}" != "$stdin" ]; then
-    exec </dev/console >/dev/console 2>&1
-fi
-
-do_start () {
-       #
-       # Set SULOGIN in /etc/default/rcS to yes if you want a sulogin to
-       # be spawned from this script *before anything else* with a timeout,
-       # like sysv does.
-       #
-       [ "$SULOGIN" = yes ] && sulogin -t 30 $CONSOLE
-
-       KERNEL="$(uname -s)"
-       MACHINE="$(uname -m)"
-
-       #
-       # Read /etc/fstab, looking for:
-       # 1) The root filesystem, resolving LABEL=*|UUID=* entries to the
-       #       device node,
-       # 2) Swap that is on a md device or a file that may be on a md 
-       #       device,
-       # 3) The mount parameters for a devfs filesystem.
-       #
-
-       exec 9<&0 </etc/fstab
-
-       fstabroot=/dev/root
-       rootdev=none
-       roottype=none
-       rootopts=defaults
-       rootmode=rw
-       rootcheck=no
-       swap_on_lv=no
-       swap_on_file=no
-       devfs=
-
-       while read DEV MTPT FSTYPE OPTS DUMP PASS JUNK
-       do
-               case "$DEV" in
-                 ""|\#*)
-                       continue;
-                       ;;
-                 /dev/mapper/*)
-                       [ "$FSTYPE" = "swap" ] && swap_on_lv=yes
-                       ;;
-                 /dev/*)
-                       ;;
-                 LABEL=*|UUID=*)
-                       if [ "$MTPT" = "/" ] && which findfs >/dev/null 2>&1
-                       then
-                               DEV="$(findfs "$DEV")"
-                       fi
-                       ;;
-                 /*)
-                       [ "$FSTYPE" = "swap" ] && swap_on_file=yes
-                       ;;
-                 *)
-                       # Devfs definition ?
-                       if [ "$FSTYPE" = "devfs" ] && [ "$MTPT" = "/dev" ] && mountpoint -q /dev
-                       then
-                               devfs="-t $FSTYPE $DEV $MTPT"
-                       fi
-                       ;;
-               esac
-               [ "$MTPT" != "/" ] && continue
-               rootdev="$DEV"
-               fstabroot="$DEV"
-               rootopts="$OPTS"
-               roottype="$FSTYPE"
-               ( [ "$PASS" != 0 ] && [ "$PASS" != "" ]   ) && rootcheck=yes
-               ( [ "$FSTYPE" = "nfs" ] || [ "$FSTYPE" = "nfs4" ] ) && rootcheck=no
-               case "$OPTS" in
-                 ro|ro,*|*,ro|*,ro,*)
-                       rootmode=ro
-                       ;;
-               esac
-       done
-
-       exec 0<&9 9<&-
-
-       #
-       # Activate the swap device(s) in /etc/fstab. This needs to be done
-       # before fsck, since fsck can be quite memory-hungry.
-       #
-       ENABLE_SWAP=no
-       case "$KERNEL" in
-         Linux)
-               if [ "$swap_on_lv" = yes ]
-               then
-                       [ "$VERBOSE" = no ] || log_warning_msg "Not activating swap on logical volume."
-               elif [ "$swap_on_file" = yes ]
-               then
-                       [ "$VERBOSE" = no ] || log_warning_msg "Not activating swap on swapfile."
-               else
-                       ENABLE_SWAP=yes
-               fi
-               ;;
-         *)
-               ENABLE_SWAP=yes
-               ;;
-       esac
-       if [ "$ENABLE_SWAP" = yes ]
-       then
-               if [ "$VERBOSE" = no ]
-               then
-                       log_action_begin_msg "Activating swap"
-                       swapon -a -e >/dev/null 2>&1
-                       log_action_end_msg $?
-               else
-                       log_action_msg "Will now activate swap"
-                       swapon -a -v
-                       ES=$?
-                       if [ "$ES" = 0 ]
-                       then
-                               log_success_msg "Done activating swap."
-                       else
-                               log_failure_msg "Swap activation failed with error code ${ES}."
-                       fi
-               fi
-       fi
-
-       #
-       # Does the root device in /etc/fstab match with the actual device ?
-       # If not we try to use the /dev/root alias device, and if that
-       # fails we create a temporary node in /dev/shm.
-       #
-       if [ "$rootcheck" = yes ]
-       then
-               ddev="$(mountpoint -qx $rootdev)"
-               rdev="$(mountpoint -d /)"
-               if [ "$ddev" != "$rdev" ] && [ "$ddev" != "4:0" ]
-               then
-                       if [ "$(mountpoint -qx /dev/root)" = "4:0" ]
-                       then
-                               rootdev=/dev/root
-                       else
-                               if \
-                                       rm -f /dev/shm/root \
-                                       && mknod -m 600 /dev/shm/root b ${rdev%:*} ${rdev#*:} \
-                                       && [ -e /dev/shm/root ]
-                               then
-                                       rootdev=/dev/shm/root
-                               else
-                                       rootfatal=yes
-                               fi
-                       fi
-               fi
-       fi
-
-       #
-       # Bother, said Pooh.
-       #
-       if [ "$rootfatal" = yes ]
-       then
-               log_failure_msg "The device node $rootdev for the root filesystem is missing or incorrect 
-or there is no entry for the root filesystem listed in /etc/fstab. 
-The system is also unable to create a temporary node in /dev/shm. 
-This means you have to fix the problem manually."
-               log_warning_msg "A maintenance shell will now be started. 
-CONTROL-D will terminate this shell and restart the system."
-               # Start a single user shell on the console
-               if ! sulogin $CONSOLE
-               then
-                       log_failure_msg "Attempt to start maintenance shell failed. 
-Will restart in 5 seconds."
-                       sleep 5
-               fi
-               [ "$VERBOSE" = no ] || log_action_msg "Will now restart"
-               reboot -f
-       fi
-
-       # See if we're on AC Power
-       # If not, we're not gonna run our check
-       if which on_ac_power >/dev/null 2>&1 && [ "$rootcheck" = yes ]
-       then
-               if [ -d /proc/acpi ]; then
-                       modprobe ac >/dev/null 2>&1
-               fi
-               on_ac_power >/dev/null 2>&1
-               if [ "$?" -eq 1 ]
-               then
-                       log_warning_msg "On battery power, so skipping file system check."
-                       rootcheck=no
-               fi
-       fi
-
-       #
-       # See if we want to check the root file system.
-       #
-       FSCKCODE=0
-       if [ -f /fastboot ]
-       then
-               [ "$rootcheck" = yes ] && log_warning_msg "Fast boot enabled, so skipping file system check."
-               rootcheck=no
-       fi
-
-       if [ "$rootcheck" = yes ]
-       then
-               #
-               # Ensure that root is quiescent and read-only before fsck'ing.
-               #
-               # mount -n -o remount,ro / would be the correct syntax but
-               # mount can get confused when there is a "bind" mount defined
-               # in fstab that bind-mounts "/" somewhere else.
-               #
-               # So we use mount -n -o remount,ro $rootdev / but that can
-               # fail on older kernels on sparc64/alpha architectures due
-               # to a bug in sys_mount().
-               #
-               # As a compromise we try both.
-               #
-               if \
-                       ! mount    -n -o remount,ro              $rootdev /              \
-                       && ! mount -n -o remount,ro -t dummytype $rootdev /  2>/dev/null \
-                       && ! mount -n -o remount,ro                       /  2>/dev/null
-               then
-                       log_failure_msg "Cannot check root file system because it is not mounted read-only."
-                       rootcheck=no
-               fi
-       fi
-
-       #
-       # The actual checking is done here.
-       #
-       if [ "$rootcheck" = yes ]
-       then
-               if [ -f /forcefsck ]
-               then
-                       force="-f"
-               else
-                       force=""
-               fi
-
-               if [ "$FSCKFIX" = yes ]
-               then
-                       fix="-y"
-               else
-                       fix="-a"
-               fi
-
-               spinner="-C"
-               case "$TERM" in
-                 dumb|network|unknown|"")
-                       spinner="" ;;
-               esac
-               # This Linux/s390 special case should go away.
-               if [ "${KERNEL}:${MACHINE}" = Linux:s390 ]
-               then
-                       spinner=""
-               fi
-               
-               if [ "$VERBOSE" = no ]
-               then
-                       log_action_begin_msg "Checking root file system"
-                        if [ "$roottype" = "ext2" -o "$roottype" = "ext3" ] && pidof usplash; then
-                            PROGRESS_FILE=`mktemp -p /var/run` || PROGRESS_FILE=/var/run/checkroot_fsck
-                            set -m
-                            logsave -s $FSCK_LOGFILE fsck -C3 $force $fix -t $roottype $rootdev >/dev/console 2>&1 3>$PROGRESS_FILE &
-                            set +m
-                            usplash_progress "$PROGRESS_FILE"
-                            rm -f $PROGRESS_FILE
-                        else
-                            logsave -s $FSCK_LOGFILE fsck $spinner $force $fix -t $roottype $rootdev
-                            FSCKCODE=$?
-                        fi
-                       if [ "$FSCKCODE" = 0 ]
-                       then
-                               log_action_end_msg 0
-                       else
-                               log_action_end_msg 1 "code $FSCKCODE"
-                       fi
-               else
-                       log_action_msg "Will now check root file system"
-                       logsave -s $FSCK_LOGFILE fsck $spinner $force $fix -V -t $roottype $rootdev
-                       FSCKCODE=$?
-                       if [ "$FSCKCODE" = 0 ]
-                       then
-                               log_success_msg "Done checking root file system. 
-A log will be saved in ${FSCK_LOGFILE} if that location is writable."
-                       else
-                               log_failure_msg "Root file system check failed with error code ${FSCKCODE}. 
-A log is being saved in ${FSCK_LOGFILE} if that location is writable."
-                       fi
-               fi
-       fi
-
-       #
-       # If there was a failure, drop into single-user mode.
-       #
-       # NOTE: "failure" is defined as exiting with a return code of
-       # 4 or larger. A return code of 1 indicates that file system
-       # errors were corrected but that the boot may proceed. A return
-       # code of 2 or 3 indicates that the system should immediately reboot.
-       #
-       if [ "$FSCKCODE" -gt 3 ]
-       then
-               # Surprise! Re-directing from a HERE document (as in "cat << EOF")
-               # does not work because the root is currently read-only.
-               log_failure_msg "An automatic file system check (fsck) of the root filesystem failed. 
-A manual fsck must be performed, then the system restarted. 
-The fsck should be performed in maintenance mode with the 
-root filesystem mounted in read-only mode."
-               log_warning_msg "The root filesystem is currently mounted in read-only mode. 
-A maintenance shell will now be started. 
-After performing system maintenance, press CONTROL-D 
-to terminate the maintenance shell and restart the system."
-               # Start a single user shell on the console
-               if ! sulogin $CONSOLE
-               then
-                       log_failure_msg "Attempt to start maintenance shell failed. 
-Will restart in 5 seconds."
-                       sleep 5
-               fi
-               [ "$VERBOSE" = no ] || log_action_msg "Will now restart"
-               reboot -f
-       elif [ "$FSCKCODE" -gt 1 ]
-       then
-               log_failure_msg "The file system check corrected errors on the root partition 
-but requested that the system be restarted."
-               log_warning_msg "The system will be restarted in 5 seconds."
-               sleep 5
-               [ "$VERBOSE" = no ] || log_action_msg "Will now restart"
-               reboot -f
-       fi
-
-       #
-       # Remount root to final mode (rw or ro).
-       #
-       # See the comments above at the previous "mount -o remount"
-       # for an explanation why we try this twice.
-       #
-       if ! mount -n -o remount,$rootopts,$rootmode $fstabroot / 2>/dev/null
-       then
-               mount -n -o remount,$rootopts,$rootmode /
-       fi
-
-       #
-       # We only create/modify /etc/mtab if the location where it is
-       # stored is writable. If /etc/mtab is a symlink into /proc/
-       # then it is not writable.
-       #
-       INIT_MTAB_FILE=no
-       MTAB_PATH="$(readlink -f /etc/mtab || :)"
-       case "$MTAB_PATH" in
-         /proc/*)
-               ;;
-         /*)
-               if touch "$MTAB_PATH" >/dev/null 2>&1
-               then
-                       :> "$MTAB_PATH"
-                       rm -f ${MTAB_PATH}~
-                       INIT_MTAB_FILE=yes
-               fi
-               ;;
-         "")
-               [ -L /etc/mtab ] && MTAB_PATH="$(readlink /etc/mtab)"
-               if [ "$MTAB_PATH" ]
-               then
-                       log_failure_msg "Cannot initialize ${MTAB_PATH}."
-               else
-                       log_failure_msg "Cannot initialize /etc/mtab."
-               fi
-               ;;
-         *)
-               log_failure_msg "Illegal mtab location '${MTAB_PATH}'."
-               ;;
-       esac
-
-       if [ "$INIT_MTAB_FILE" = yes ]
-       then
-               [ "$roottype" != none ] &&
-                       mount -f -o $rootopts -t $roottype $fstabroot /
-               [ "$devfs" ] && mount -f $devfs
-       fi
-
-       #
-       # Remove /dev/shm/root if we created it.
-       #
-       rm -f /dev/shm/root
-}
-
-case "$1" in
-  start|"")
-       do_start
-       ;;
-  restart|reload|force-reload)
-       echo "Error: argument '$1' not supported" >&2
-       exit 3
-       ;;
-  stop)
-       # No-op
-       ;;
-  *)
-       echo "Usage: checkroot.sh [start|stop]" >&2
-       exit 3
-       ;;
-esac
-
-:
-#! /bin/sh
-#
-# This file was automatically customized by debmake on Fri,  6 Nov 1998 23:00:08 -0600
-#
-# Written by Miquel van Smoorenburg <miquels@drinkel.ow.org>.
-# Modified for Debian GNU/Linux by Ian Murdock <imurdock@gnu.ai.mit.edu>.
-# Modified for Debian by Christoph Lameter <clameter@debian.org>
-# Modified for chrony by John Hasler <jhasler@debian.org> 10 Nov 1998
-
-PATH=/bin:/usr/bin:/sbin:/usr/sbin
-DAEMON=/usr/sbin/chronyd
-FLAGS="defaults"
-NAME="chronyd"
-DESC="time daemon"
-
-test -f $DAEMON || exit 0
-
-case "$1" in
-  start)
-    start-stop-daemon --start --verbose --exec $DAEMON
-    ;;
-  stop)
-    start-stop-daemon --stop --verbose --oknodo --exec $DAEMON
-    ;;
-  restart|force-reload)
-        #
-        #       If the "reload" option is implemented, move the "force-reload"
-        #       option to the "reload" entry above. If not, "force-reload" is
-        #       just the same as "restart".
-        #                                                                                   
-        echo -n "Restarting $DESC: "
-        start-stop-daemon --stop --quiet --exec $DAEMON
-        sleep 1
-        start-stop-daemon --start --quiet --exec $DAEMON -- -r
-        echo "$NAME."
-        ;;
-  *)
-    echo "Usage: /etc/init.d/chrony {start|stop|restart|force-reload}"
-    exit 1
-    ;;
-esac
-
-exit 0
-#!/bin/sh
-### BEGIN INIT INFO
-# Provides:          console-screen
-# Required-Start:    $local_fs $remote_fs
-# Required-Stop:     $local_fs $remote_fs
-# Default-Start:     S 2 3 4 5
-# Default-Stop:      0 1 6
-# Should-Start:      $syslog
-# Should-Stop: 
-# Description: Set console screen modes and fonts
-# Short-Description:   Prepare console
-### END INIT INFO
-
-#
-# This is the boot script for the `console-tools' package.
-#
-# It loads parameters from /etc/console-tools/config, maybe loads
-# default screen-font, screen font-map, and application charset-map,
-# and maybe start "vcstime"
-#
-# (c) 1997 Yann Dirson
-
-# If setupcon is present, then we've been superseded by console-setup.
-if type setupcon >/dev/null 2>&1; then
-    exit 0
-fi
-
-# check if usplash is runing and skip this, we'll get run again later
-if pidof usplash > /dev/null; then
-    exit 0
-fi
-
-if [ -r /etc/console-tools/config ] ; then
-    . /etc/console-tools/config
-fi
-
-if [ -d /etc/console-tools/config.d ]; then
-    for i in `run-parts --list /etc/console-tools/config.d `; do
-       . $i
-    done
-fi
-
-. /lib/lsb/init-functions
-
-PATH=/sbin:/bin:/usr/sbin:/usr/bin
-SETFONT="/usr/bin/consolechars"
-SETFONT_OPT=""
-CHARSET="/usr/bin/charset"
-VCSTIME="/usr/sbin/vcstime"
-
-# Different device name for 2.6 kernels and devfs
-if [ `uname -r | cut -f 2 -d .` = 6 ] && [ -e /dev/.devfsd ]; then
-    VCSTIME_OPT="-2 /dev/vcsa0"
-else
-    VCSTIME_OPT=""
-fi
-
-
-
-# set DEVICE_PREFIX depending on devfs/udev
-if [ -d /dev/vc ]; then
-    DEVICE_PREFIX="/dev/vc/"
-else
-    DEVICE_PREFIX="/dev/tty"
-fi
-
-reset_vga_palette ()
-{
-       if [ -f /proc/fb ]; then
-           # They have a framebuffer device.
-           # That means we have work to do...
-           echo -n "\e]R"
-       fi
-}
-
-setup ()
-{
-    # be sure the main program is installed
-    [ -x "${SETFONT}" ] || return 0
-
-    VT="no"
-    # If we can't access the console, quit
-    CONSOLE_TYPE=`fgconsole 2>/dev/null` || return 0
-
-    if [ ! $CONSOLE_TYPE = "serial" ]  ; then
-       readlink /proc/self/fd/0 | grep -q -e /dev/vc -e '/dev/tty[^p]' -e /dev/console
-       if [ $? -eq 0 ] ; then
-           VT="yes"
-           reset_vga_palette
-       fi
-    fi
-
-    [ $VT = "no" ] && return 0
-
-    # start vcstime
-    if [ "${DO_VCSTIME}" = "yes" -a -x ${VCSTIME} ] ; then
-       [ "$VERBOSE" != "no" ] && log_action_begin_msg "Starting clock on text console"
-       ${VCSTIME} ${VCSTIME_OPT} &
-        [ "$VERBOSE" != "no" ] && log_action_end_msg 0
-    fi
-
-
-    # Global default font+sfm
-    if [ "${SCREEN_FONT}" ]
-       then
-       [ "$VERBOSE" != "no" ] && log_action_begin_msg "Setting up general console font"
-       SCREEN_FONT="-f ${SCREEN_FONT}"
-
-       # maybe use an external SFM
-       [ "${SCREEN_FONT_MAP}" ] && SCREEN_FONT_MAP="-u ${SCREEN_FONT_MAP}"
-
-       # Try to be cleverer and run for all consoles, but this is run
-       # _before_ getty and so only one console running. So,
-       # Set for the first 6 VCs (as they are allocated in /etc/inittab)
-       NUM_CONSOLES=`fgconsole --next-available`
-       NUM_CONSOLES=$(($NUM_CONSOLES - 1))
-       [ ${NUM_CONSOLES} -eq 1 ] && NUM_CONSOLES=6
-       i=1
-       while [ $i -le $NUM_CONSOLES ]
-           do
-           if ! ${SETFONT} --tty=${DEVICE_PREFIX}$i ${SETFONT_OPT} ${SCREEN_FONT} ${SCREEN_FONT_MAP} ; then
-             [ "$VERBOSE" != "no" ] && log_action_end_msg 1
-             break
-           elif [ "$i" -eq "$NUM_CONSOLES" ]; then
-             [ "$VERBOSE" != "no" ] && log_action_end_msg 0
-           fi
-           i=$(($i + 1))
-       done
-    fi
-
-
-    # Per-VC font+sfm
-    VCS="`set | grep '^SCREEN_FONT_vc[0-9]*=' | sed -e 's/^SCREEN_FONT_vc//' -e 's/=.*//'`"
-    if [ "${VCS}" ]
-       then
-       [ "$VERBOSE" != "no" ] && log_action_begin_msg "Setting up per-VC fonts"
-       for vc in ${VCS}
-         do
-           # extract FONTNAME info from variable setting
-         eval font=\$SCREEN_FONT_vc$vc
-         # eventually find an associated SFM
-         eval sfm=\${SCREEN_FONT_MAP_vc${vc}}
-         [ "$sfm" ] && sfm="-u $sfm"
-
-         ${SETFONT} --tty=${DEVICE_PREFIX}$vc ${SETFONT_OPT} -f $font $sfm
-       done
-       [ "$VERBOSE" != "no" ] && log_action_end_msg 0
-    fi
-
-
-    # Global ACM
-    [ "${APP_CHARSET_MAP}" ] && ${CHARSET} G0 ${APP_CHARSET_MAP}
-
-
-    # Per-VC ACMs
-    VCS="`set | grep '^APP_CHARSET_MAP_vc[0-9]*=' | sed -e 's/^APP_CHARSET_MAP_vc//' -e 's/=.*//'`"
-    if [ "${VCS}" ]
-       then
-       [ "$VERBOSE" != "no" ] && log_action_begin_msg "Setting up per-VC ACM\'s"
-       for vc in ${VCS}
-         do
-           # extract FONTNAME info from variable setting
-         eval acm=\$APP_CHARSET_MAP_vc$vc
-         ${CHARSET} --tty="${DEVICE_PREFIX}$vc" G0 "$acm"
-       done
-       [ "$VERBOSE" != "no" ] && log_action_end_msg 0
-    fi
-
-
-    # Go to UTF-8 mode as necessary
-    # 
-    ENV_FILE=''
-    [ -r /etc/environment ] && ENV_FILE="/etc/environment"
-    [ -r /etc/default/locale ] && ENV_FILE="/etc/default/locale"
-    [ "$ENV_FILE" ] && CHARMAP=$(set -a && . "$ENV_FILE" && locale charmap)
-    if test "$CHARMAP" = "UTF-8" 
-    then
-        unicode_start 2> /dev/null || true
-    else
-        unicode_stop 2> /dev/null|| true
-    fi
-
-    # screensaver stuff
-    setterm_args=""
-    if [ "$BLANK_TIME" ]; then
-        setterm_args="$setterm_args -blank $BLANK_TIME"
-    fi
-    if [ "$BLANK_DPMS" ]; then
-        setterm_args="$setterm_args -powersave $BLANK_DPMS"
-    fi
-    if [ "$POWERDOWN_TIME" ]; then
-        setterm_args="$setterm_args -powerdown $POWERDOWN_TIME"
-    fi
-    if [ "$setterm_args" ]; then
-        setterm $setterm_args 
-    fi
-
-    # Keyboard rate and delay
-    KBDRATE_ARGS=""
-    if [ -n "$KEYBOARD_RATE" ]; then
-        KBDRATE_ARGS="-r $KEYBOARD_RATE"
-    fi
-    if [ -n "$KEYBOARD_DELAY" ]; then
-        KBDRATE_ARGS="$KBDRATE_ARGS -d $KEYBOARD_DELAY"
-    fi
-    if [ -n "$KBDRATE_ARGS" ]; then
-       [ "$VERBOSE" != "no" ] && log_action_begin_msg "Setting keyboard rate and delay"
-        kbdrate -s $KBDRATE_ARGS
-       [ "$VERBOSE" != "no" ] && log_action_end_msg 0
-    fi
-
-    # Inform gpm if present, of potential changes.
-    if [ -f /var/run/gpm.pid ]; then
-       kill -WINCH `cat /var/run/gpm.pid` 2> /dev/null
-    fi
-
-    # Allow user to remap keys on the console
-    if [ -r /etc/console-tools/remap ]
-       then
-       dumpkeys < ${DEVICE_PREFIX}1 | sed -f /etc/console-tools/remap | loadkeys --quiet
-    fi
-    # Set LEDS here
-    if [ "$LEDS" != "" ]
-       then
-       i=1
-       while [ $i -le $NUM_CONSOLES ]
-         do
-          setleds -D $LEDS < $DEVICE_PREFIX$i
-         i=$(($i + 1))
-       done
-    fi
-}
-
-case "$1" in
-    start|reload|restart|force-reload)
-       log_action_msg "Setting console screen modes and fonts"
-       setup
-       ;;
-    stop)
-       ;;
-    *)
-       setup
-       ;;
-esac
-#!/bin/sh
-# Start/stop the cron daemon.
-#
-### BEGIN INIT INFO
-# Provides:          cron
-# Required-Start:    $syslog $time
-# Required-Stop:     $syslog $time
-# Default-Start:     2 3 4 5
-# Default-Stop:      0 1 6
-# Short-Description: Regular background program processing daemon
-# Description:       cron is a standard UNIX program that runs user-specified 
-#                    programs at periodic scheduled times. vixie cron adds a 
-#                    number of features to the basic UNIX cron, including better
-#                    security and more powerful configuration options.
-### END INIT INFO
-
-
-test -f /usr/sbin/cron || exit 0
-
-#LSBNAMES='-l'  # Uncomment for LSB name support in /etc/cron.d/
-
-. /lib/lsb/init-functions
-
-case "$1" in
-start) log_daemon_msg "Starting periodic command scheduler" "crond"
-        start-stop-daemon --start --quiet --pidfile /var/run/crond.pid --name cron --startas /usr/sbin/cron -- $LSBNAMES
-        log_end_msg $?
-       ;;
-stop)  log_daemon_msg "Stopping periodic command scheduler" "crond"
-        start-stop-daemon --stop --quiet --pidfile /var/run/crond.pid --name cron
-        log_end_msg $?
-        ;;
-restart) log_daemon_msg "Restarting periodic command scheduler" "crond" 
-        start-stop-daemon --stop --retry 5 --quiet --pidfile /var/run/crond.pid --name cron
-        start-stop-daemon --start --quiet --pidfile /var/run/crond.pid --name cron --startas /usr/sbin/cron -- $LSBNAMES
-        log_end_msg $?
-        ;;
-reload|force-reload) log_daemon_msg "Reloading configuration files for periodic command scheduler" "crond"
-       # cron reloads automatically
-        log_end_msg 0
-        ;;
-*)     log_action_msg "Usage: /etc/init.d/cron {start|stop|restart|reload|force-reload}"
-        exit 2
-        ;;
-esac
-exit 0
-#!/bin/sh
-### BEGIN INIT INFO
-# Provides:          dbus
-# Required-Start:    $remote_fs $syslog
-# Required-Stop:     $remote_fs $syslog
-# Default-Start:     2 3 4 5
-# Default-Stop:      1
-# Short-Description: D-Bus systemwide message bus
-# Description:       D-Bus is a simple interprocess messaging system, used
-#                    for sending messages between applications.
-### END INIT INFO
-# -*- coding: utf-8 -*-
-# Debian init.d script for D-BUS
-# Copyright Â© 2003 Colin Walters <walters@debian.org>
-# Copyright Â© 2005 Sjoerd Simons <sjoerd@debian.org>
-
-set -e
-
-DAEMON=/usr/bin/dbus-daemon
-UUIDGEN=/usr/bin/dbus-uuidgen
-UUIDGEN_OPTS=--ensure
-NAME=dbus
-DAEMONUSER=messagebus
-PIDDIR=/var/run/dbus
-PIDFILE=$PIDDIR/pid
-DESC="system message bus"
-EVENTDIR=/etc/dbus-1/event.d
-
-test -x $DAEMON || exit 0
-
-. /lib/lsb/init-functions
-
-# Source defaults file; edit that file to configure this script.
-PARAMS=""
-if [ -e /etc/default/dbus ]; then
-  . /etc/default/dbus
-fi
-
-if [ -n "$ENABLED" ]; then
-    log_warning_msg "The ENABLED option in /etc/default/$NAME has been deprecated."
-    log_warning_msg "Please remove this setting from the configuration file."
-    log_warning_msg "To disable the service use a runlevel editor like sysv-rc-conf or bum instead."
-fi
-
-create_machineid() {
-  # Create machine-id file
-  if [ -x $UUIDGEN ]; then
-    $UUIDGEN $UUIDGEN_OPTS
-  fi
-}
-
-dependent_services()
-{
-  # Do nothing if we are called by init
-  [ ! -z $runlevel ] && return 
-
-  # Determine current runlevel
-  r=$(/sbin/runlevel) || true
-  r=${r#*\ }
-
-  # Do nothing if we can't determine the runlevel (e.g. inside chroots)
-  [ "$r" = "unknown" ] && return
-
-  if [ "$1" = "stop" ] ; then
-    param="--reverse"
-    action="stop"
-  else
-    param=""
-    action="start"
-  fi
-
-  # Get the list of services active in this runlevel
-  if [ -d /etc/rc${r}.d/ ] ; then # sysv-rc
-    services=$(grep -s -l "^# Required-Start:.*dbus" /etc/rc${r}.d/S??* | sort $param)
-  elif [ -f /etc/runlevel.conf ] ; then # file-rc
-    list=$(grep -s -l "^# Required-Start:.*dbus" /etc/init.d/* || true)
-    services=$( for i in $list ; do
-      grep -E "^[[:digit:]]{2}[[:space:]]+([0-9,S]+|[-])[[:space:]]+.*$r.*[[:space:]]+$i$" /etc/runlevel.conf
-    done  | sort $param | awk '{print $4}' )
-  else
-    services=""
-    log_warning_msg "Unable to determine dependent services: unknown init system"
-  fi
-
-  # Start the services in the correct order
-  for i in $services ; do
-    service=$(basename $i)
-    service=${service#S??}
-    invoke-rc.d $service $action || true
-  done
-
-}
-
-
-start_it_up()
-{
-  if [ ! -d $PIDDIR ]; then
-    mkdir -p $PIDDIR
-    chown $DAEMONUSER $PIDDIR
-    chgrp $DAEMONUSER $PIDDIR
-  fi
-
-  if ! mountpoint -q /proc/ ; then
-    log_failure_msg "Can't start $DESC - /proc is not mounted"
-    return
-  fi
-
-  if [ -e $PIDFILE ]; then
-    PIDDIR=/proc/$(cat $PIDFILE)
-    if [ -d ${PIDDIR} -a  "$(readlink -f ${PIDDIR}/exe)" = "${DAEMON}" ]; then 
-      log_success_msg "$DESC already started; not starting."
-      return
-    else
-      log_success_msg "Removing stale PID file $PIDFILE."
-      rm -f $PIDFILE
-    fi
-  fi
-
-  create_machineid
-
-  log_daemon_msg "Starting $DESC" "$NAME"
-  start-stop-daemon --start --quiet --pidfile $PIDFILE \
-    --user $DAEMONUSER --exec $DAEMON -- --system $PARAMS
-  log_end_msg $?
-  if [ -d $EVENTDIR ]; then
-      run-parts --arg=start $EVENTDIR || true
-  fi
-  dependent_services start
-}
-
-shut_it_down()
-{
-  dependent_services stop
-  if [ -d $EVENTDIR ]; then
-      run-parts --reverse --arg=stop $EVENTDIR || true
-  fi
-  log_daemon_msg "Stopping $DESC" "$NAME"
-  start-stop-daemon --stop --retry 5 --quiet --oknodo --pidfile $PIDFILE \
-    --user $DAEMONUSER
-  # We no longer include these arguments so that start-stop-daemon
-  # can do its job even given that we may have been upgraded.
-  # We rely on the pidfile being sanely managed
-  # --exec $DAEMON -- --system $PARAMS
-  log_end_msg $?
-  rm -f $PIDFILE
-}
-
-reload_it()
-{
-  create_machineid
-  log_action_begin_msg "Reloading $DESC config"
-  dbus-send --print-reply --system --type=method_call \
-            --dest=org.freedesktop.DBus \
-            / org.freedesktop.DBus.ReloadConfig > /dev/null
-  # hopefully this is enough time for dbus to reload it's config file.
-  log_action_end_msg $?
-}
-
-case "$1" in
-  start)
-    start_it_up
-  ;;
-  stop)
-    shut_it_down
-  ;;
-  reload|force-reload)
-    reload_it
-  ;;
-  restart)
-    shut_it_down
-    start_it_up
-  ;;
-  *)
-    echo "Usage: /etc/init.d/$NAME {start|stop|reload|restart|force-reload}" >&2
-    exit 2
-  ;;
-esac
-
-#! /bin/sh
-
-# $Id: dns-clean,v 1.1.1.1 2004/05/07 03:12:59 john Exp $
-
-# dns-clean by John Hasler 1999-2003
-# Any possessor of a copy of this program may treat it as if it
-# were in the public domain.  I waive all rights.
-
-# This script should be run at bootup to clean up any mess left by 0dns-up.
-# It should be run before ppp is started.
-# It should never be run while ppp is up.
-
-### BEGIN INIT INFO
-# Provides:          dns-clean
-# Required-Start:    $local_fs
-# Required-Stop:     $local_fs
-# Default-Start:     S
-# Default-Stop:
-# Short-Description: Cleans up any mess left by 0dns-up
-# Description: 0dns-up often leaves behind some cruft. This Script is meant
-#              to clean up any such mess.
-### END INIT INFO
-
-PATH=/sbin:/bin:/usr/sbin:/usr/bin
-
-test -f /usr/sbin/pppconfig || exit 0
-# We might have a tmpfs /var/run.
-mkdir /var/run/pppconfig >/dev/null 2>&1 || true
-test -f /etc/ppp/ip-down.d/0dns-down || exit 0
-
-. /lib/lsb/init-functions
-. /etc/default/rcS
-
-case "$1" in
-  start)
-       [ "$VERBOSE" != no ] && log_begin_msg "Restoring resolver state..."
-       /etc/ppp/ip-down.d/0dns-down "0dns-clean"
-       [ "$VERBOSE" != no ] && log_end_msg $?
-       ;;
-  stop|restart|force-reload)
-       ;;
-  *)
-        ;;
-esac
-
-exit 0
-
-
-
-#! /bin/sh
-#
-# evms          Enterprise Volume Management System
-#
-#              Written by Miquel van Smoorenburg <miquels@cistron.nl>.
-#              Modified for Debian GNU/Linux
-#              by Ian Murdock <imurdock@gnu.ai.mit.edu>.
-#               Modified for evms package
-#               by Matt Zimmerman <mdz@debian.org>
-#
-
-### BEGIN INIT INFO
-# Provides:          evms
-# Default-Start:     2 3 4 5
-# Default-Stop:      0 1 6
-# Required-Start:    
-# Required-Stop:     
-# Short-Description: Activates EVMS volumes
-# Description:       Activates any EVMS volumes that are left unactivated
-#                    by the initramfs for some reason (or if the user does
-#                    not use initramfs). This possibly includes setting up
-#                    RAID, LVM, snapshots, BBR etc., but does not start a
-#                    service.
-### END INIT INFO
-
-PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
-NAME=evms
-DESC="Enterprise Volume Management System"
-
-test -x /sbin/evms_activate || exit 0
-
-. /lib/lsb/init-functions
-. /etc/default/rcS
-
-set -e
-
-case "$1" in
-  start|reload|restart|force-reload)
-       log_begin_msg "Starting $DESC..."
-       status=0
-       if [ "$VERBOSE" != no ]; then
-               evms_activate || status=$?
-       else
-               # Messages are still written to the log
-               evms_activate >/dev/null 2>&1 || status=$?
-       fi
-       log_end_msg $status
-       ;;
-  stop)
-       ;;
-  status)
-       echo "no daemons started by this script"
-        log_end_msg 0
-       ;;
-  *)
-       N=/etc/init.d/$NAME
-       log_success_msg "Usage: $N {start|stop|restart|reload|force-reload|status}"
-       exit 1
-       ;;
-esac
-
-exit 0
-#! /bin/sh
-#
-# Originally based on:
-# Version:     @(#)skeleton  1.8  03-Mar-1998  miquels@cistron.nl
-#
-# Modified for gdm, Steve Haslam <steve@arise.dmeon.co.uk> 14mar99
-# modified to remove --exec, as it does not work on upgrades. 18jan2000
-# modified to use --name, to detect stale PID files 18mar2000
-# sleep until gdm dies, then restart it 16jul2000
-# get along with other display managers (Branden Robinson, Ryan Murray) 05sep2001
-
-set -e
-
-# To start gdm even if it is not the default display manager, change
-# HEED_DEFAULT_DISPLAY_MANAGER to "false."
-HEED_DEFAULT_DISPLAY_MANAGER=true
-DEFAULT_DISPLAY_MANAGER_FILE=/etc/X11/default-display-manager
-PATH=/sbin:/bin:/usr/sbin:/usr/bin
-DAEMON=/usr/sbin/gdm
-PIDFILE=/var/run/gdm.pid
-UPGRADEFILE=/var/run/gdm.upgrade
-
-if [ -e $UPGRADEFILE -a "$1" != "restart" -a "$1" != "force-reload" ]; then
-       SSD_ARG="--startas $DAEMON"
-       rm -f $UPGRADEFILE
-else
-       SSD_ARG="--exec $DAEMON"
-fi
-
-# Allow cdd to override the config
-if [ -f /etc/gdm/gdm-cdd.conf ]; then
-       CONFIG_FILE="--config=/etc/gdm/gdm-cdd.conf"
-fi
-
-test -x $DAEMON || exit 0
-
-if [ -r /etc/environment ]; then
-  if LANG=$(pam_getenv -l LANG); then
-    export LANG
-  fi
-  if LANGUAGE=$(pam_getenv -l LANGUAGE); then
-    export LANGUAGE
-  fi
-
-fi
-
-. /lib/lsb/init-functions
-
-case "$1" in
-  start)
-       if [ -e "$DEFAULT_DISPLAY_MANAGER_FILE" -a "$HEED_DEFAULT_DISPLAY_MANAGER" = "true" -a "$(cat $DEFAULT_DISPLAY_MANAGER_FILE 2>/dev/null)" != "$DAEMON" ]; then
-               log_warning_msg "Not starting GNOME Display Manager (gdm); it is not the default display manager."
-       else
-               # if usplash is runing, make sure to stop it now, yes "start" kills it.
-               if pidof usplash > /dev/null; then
-                       /etc/init.d/usplash start
-               fi
-               log_begin_msg "Starting GNOME Display Manager..."
-               start-stop-daemon --start --quiet --oknodo --pidfile $PIDFILE --name gdm $SSD_ARG -- $CONFIG_FILE >/dev/null 2>&1 || log_end_msg 1
-               log_end_msg 0
-       fi
-  ;;
-  stop)
-       log_begin_msg "Stopping GNOME Display Manager..."
-       start-stop-daemon --stop  --quiet --oknodo --pidfile $PIDFILE --name gdm $SSD_ARG --retry 30 >/dev/null 2>&1
-       log_end_msg 0
-  ;;
-  reload)
-       log_begin_msg "Reloading GNOME Display Manager configuration..."
-       log_warning_msg "Changes will take effect when all current X sessions have ended."
-       start-stop-daemon --stop --signal USR1 --quiet --pidfile \
-               $PIDFILE --name gdm $SSD_ARG >/dev/null 2>&1
-       log_end_msg 0
-  ;;
-  restart|force-reload)
-       $0 stop || true
-       $0 start
-  ;;
-  *)
-       log_success_msg "Usage: /etc/init.d/gdm {start|stop|restart|reload|force-reload}"
-       exit 1
-  ;;
-esac
-
-exit 0
-#! /bin/sh -e
-#
-### BEGIN INIT INFO
-# Provides:          glibc
-# Required-Start:
-# Required-Stop:
-# Default-Start:     S
-# Default-Stop:
-### END INIT INFO
-#
-# 
-# This script detects deprecated kernel versions incompatible with
-# the current version of the glibc
-
-# glibc kernel version check: KERNEL_VERSION_CHECK
-linux_compare_versions () {
-    verA=$(($(echo "$1" | sed 's/\([0-9]*\)\.\([0-9]*\)\.\([0-9]*\).*/\1 \* 10000 + \2 \* 100 + \3/')))
-    verB=$(($(echo "$3" | sed 's/\([0-9]*\)\.\([0-9]*\)\.\([0-9]*\).*/\1 \* 10000 + \2 \* 100 + \3/')))
-
-    test $verA -$2 $verB
-}
-
-kfreebsd_compare_versions () {
-    verA=$(($(echo "$1" | sed 's/\([0-9]*\)\.\([0-9]*\).*/\1 \* 100 + \2/')))
-    verB=$(($(echo "$3" | sed 's/\([0-9]*\)\.\([0-9]*\).*/\1 \* 100 + \2/')))
-
-    test $verA -$2 $verB
-}
-
-kernel26_help() {
-    echo ""
-    echo "The installation of a 2.6 kernel _could_ ask you to install a new libc"
-    echo "first, this is NOT a bug, and should *NOT* be reported. In that case,"
-    echo "please add etch sources to your /etc/apt/sources.list and run:"
-    echo "  apt-get install -t etch linux-image-2.6"
-    echo "Then reboot into this new kernel, and proceed with your upgrade"
-}
-
-exit_check () {
-    sleep 5
-    exit 1
-}
-
-    system=`uname -s`
-    if [ "$system" = "Linux" ]
-    then
-        # Test to make sure z < 255, in x.y.z-n form of kernel version
-        # Also make sure we don't trip on x.y.zFOO-n form
-        #kernel_rev=$(uname -r | tr -- - . | cut -d. -f3 | tr -d '[:alpha:]')
-        kernel_rev=$(uname -r | sed 's/\([0-9]*\.[0-9]*\.\)\([0-9]*\)\(.*\)/\2/')
-        if [ "$kernel_rev" -ge 255 ]
-        then
-            echo "WARNING: Your kernel version indicates a revision number"
-            echo "of 255 or greater.  Glibc has a number of built in"
-            echo "assumptions that this revision number is less than 255."
-            echo "If you\'ve built your own kernel, please make sure that any"
-            echo "custom version numbers are appended to the upstream"
-            echo "kernel number with a dash or some other delimiter."
-
-            exit_check
-        fi
-
-        # sanity checking for the appropriate kernel on each architecture.
-        realarch=`uname -m`
-        kernel_ver=`uname -r`
-
-        # convert "armv4l" and similar to just "arm", and "mips64" and similar
-        # to just "mips"
-        case $realarch in
-          arm*) realarch="arm";;
-          mips*) realarch="mips";;
-        esac
-
-
-        # From glibc 2.3.5-7 real-i386 is dropped.
-        if [ "$realarch" = i386 ]
-        then
-            echo "WARNING: This machine has real i386 class processor."
-            echo "Debian etch and later does not support such old hardware"
-            echo "any longer."
-            echo "The reason is that \"bswap\" instruction is not supported"
-            echo "on i386 class processors, and some core libraries have"
-            echo "such instruction.  You\'ll see illegal instruction error"
-            echo "when you upgrade your Debian system."
-            exit_check
-        fi
-
-        # arm boxes require __ARM_NR_set_tls in the kernel to function properly.
-        if [ "$realarch" = arm ]
-        then
-            if linux_compare_versions "$kernel_ver" lt 2.6.12
-            then
-                echo WARNING: This version of glibc requires that you be running
-                echo kernel version 2.6.12 or later.  Earlier kernels contained
-                echo bugs that may render the system unusable if a modern version
-                echo of glibc is installed.
-                kernel26_help
-                exit_check
-            fi 
-        fi
-
-        # Alpha and HPPA boxes require latest fixes in the kernel to function properly.
-        if [ "$realarch" = parisc -o "$realarch" = alpha ]
-        then
-            if linux_compare_versions "$kernel_ver" lt 2.6.9
-            then
-                echo WARNING: This version of glibc requires that you be running
-                echo kernel version 2.6.9 or later.  Earlier kernels contained
-                echo bugs that may render the system unusable if a modern version
-                echo of glibc is installed.
-                kernel26_help
-                exit_check
-            fi
-        fi
-
-        # sh4 boxes require kernel version 2.6.11 minimum
-        if [ "$realarch" = sh4 ]
-        then
-            if linux_compare_versions "$kernel_ver" lt 2.6.11
-            then
-                echo WARNING: This version of glibc requires that you be running
-                echo kernel version 2.6.11 or later.  Earlier kernels contained
-                echo bugs that may render the system unusable if a modern version
-                echo of glibc is installed.
-                kernel26_help
-                exit_check
-            fi 
-        fi
-
-        # The GNU libc requires 2.6 kernel (except on m68k) because we drop to
-        # support linuxthreads
-        if [ "$realarch" != m68k ]
-        then
-            if linux_compare_versions "$kernel_ver" lt 2.6.8
-            then
-                echo WARNING: POSIX threads library NPTL requires kernel version
-                echo 2.6.8 or later.  If you use a kernel 2.4, please upgrade it
-                echo before installing glibc.
-                kernel26_help
-                exit_check
-            fi
-        fi
-
-        # The GNU libc is now built with --with-kernel= >= 2.4.1 on m68k
-        if [ "$realarch" = m68k ]
-        then
-            if linux_compare_versions "$kernel_ver" lt 2.4.1
-            then
-                echo WARNING: This version of glibc requires that you be running
-                echo kernel version 2.4.1 or later.  Earlier kernels contained
-                echo bugs that may render the system unusable if a modern version
-                echo of glibc is installed.
-                kernel26_help
-                exit_check
-            fi
-        fi
-
-        # From glibc 2.6-3 SPARC V8 support is dropped.
-        if [ "$realarch" = sparc ]
-        then
-            # The process could be run using linux32, check for /proc.
-            if [ -f /proc/cpuinfo ]
-            then
-               case "$(sed '/^type/!d;s/^type.*: //g' /proc/cpuinfo)" in
-                   sun4u)
-                      # UltraSPARC CPU
-                      ;;
-                   sun4v)
-                      # Niagara CPU
-                      ;;
-                   *)
-                      echo "WARNING: This machine has a SPARC V8 or earlier class processor."
-                      echo "Debian lenny and later does not support such old hardware"
-                      echo "any longer."
-                      exit_check
-                      ;;
-               esac
-            fi
-        fi
-    elif [ $system = "GNU/kFreeBSD" ] ; then
-        kernel_ver=`uname -r`
-        if kfreebsd_compare_versions "$kernel_ver" lt 6.0
-        then
-            echo WARNING: This version of glibc uses UMTX_OP_WAIT and UMTX_OP_WAKE
-           echo syscalls that are not present in the current running kernel. They
-           echo have been added in kFreeBSD 6.0.  Your system should still work,
-           echo but it is recommended to upgrade to a more recent version.
-        fi
-    fi
-
-: exit 0
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          halt
-# Required-Start:    umountroot
-# Required-Stop:
-# Should-Start:      lvm raid2
-# Should-Stop:
-# Default-Start:     0
-# Default-Stop:
-# Short-Description: Execute the halt command.
-# Description:
-### END INIT INFO
-
-PATH=/usr/sbin:/usr/bin:/sbin:/bin
-[ -f /etc/default/halt ] && . /etc/default/halt
-
-. /lib/lsb/init-functions
-
-do_stop () {
-       if [ "$INIT_HALT" = "" ]
-       then
-               case "$HALT" in
-                 [Pp]*)
-                       INIT_HALT=POWEROFF
-                       ;;
-                 [Hh]*)
-                       INIT_HALT=HALT
-                       ;;
-                 *)
-                       INIT_HALT=POWEROFF
-                       ;;
-               esac
-       fi
-
-       # See if we need to cut the power.
-       if [ "$INIT_HALT" = "POWEROFF" ] && [ -x /etc/init.d/ups-monitor ]
-       then
-               /etc/init.d/ups-monitor poweroff
-       fi
-
-       # Don't shut down drives if we're using RAID.
-       hddown="-h"
-       if grep -qs '^md.*active' /proc/mdstat
-       then
-               hddown=""
-       fi
-
-       # If INIT_HALT=HALT don't poweroff.
-       poweroff="-p"
-       if [ "$INIT_HALT" = "HALT" ]
-       then
-               poweroff=""
-       fi
-
-       log_action_msg "Will now halt"
-       sleep 1
-       halt -d -f -i $poweroff $hddown
-}
-
-case "$1" in
-  start)
-       # No-op
-       ;;
-  restart|reload|force-reload)
-       echo "Error: argument '$1' not supported" >&2
-       exit 3
-       ;;
-  stop)
-       do_stop
-       ;;
-  *)
-       echo "Usage: $0 start|stop" >&2
-       exit 3
-       ;;
-esac
-
-:
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          hostname
-# Required-Start:
-# Required-Stop:
-# Default-Start:     S
-# Default-Stop:
-# Short-Description: Set hostname.
-# Description:
-### END INIT INFO
-
-PATH=/sbin:/bin
-
-. /lib/init/vars.sh
-. /lib/lsb/init-functions
-
-do_start () {
-       [ -f /etc/hostname ] && HOSTNAME="$(cat /etc/hostname)"
-
-       # Keep current name if /etc/hostname is missing.
-       [ -z "$HOSTNAME" ] && HOSTNAME="$(hostname)"
-
-       # And set it to 'localhost' if no setting was found
-       [ -z "$HOSTNAME" ] && HOSTNAME=localhost
-
-       [ "$VERBOSE" != no ] && log_action_begin_msg "Setting hostname to '$HOSTNAME'"
-       hostname "$HOSTNAME"
-       ES=$?
-       [ "$VERBOSE" != no ] && log_action_end_msg $ES
-}
-
-case "$1" in
-  start|"")
-       do_start
-       ;;
-  restart|reload|force-reload)
-       echo "Error: argument '$1' not supported" >&2
-       exit 3
-       ;;
-  stop)
-       # No-op
-       ;;
-  *)
-       echo "Usage: hostname.sh [start|stop]" >&2
-       exit 3
-       ;;
-esac
-#!/bin/sh
-# hwclock.sh   Set and adjust the CMOS clock, according to the UTC
-#              setting in /etc/default/rcS (see also rcS(5)).
-#
-# Version:     @(#)hwclock.sh  2.00  14-Dec-1998  miquels@cistron.nl
-#
-# Patches:
-#              2000-01-30 Henrique M. Holschuh <hmh@rcm.org.br>
-#               - Minor cosmetic changes in an attempt to help new
-#                 users notice something IS changing their clocks
-#                 during startup/shutdown.
-#               - Added comments to alert users of hwclock issues
-#                 and discourage tampering without proper doc reading.
-
-# WARNING:     Please read /usr/share/doc/util-linux/README.Debian.hwclock
-#              before changing this file. You risk serious clock
-#              misbehaviour otherwise.
-
-### BEGIN INIT INFO
-# Provides:          hwclockfirst
-# Required-Start:    mountdevsubfs
-# Required-Stop:     umountroot
-# Default-Start:     S
-# Default-Stop:      0 6
-### END INIT INFO
-
-FIRST=yes      # debian/rules sets this to 'yes' when creating hwclockfirst.sh
-
-# Set this to any options you might need to give to hwclock, such
-# as machine hardware clock type for Alphas.
-HWCLOCKPARS=
-
-hwclocksh()
-{
-    [ ! -x /sbin/hwclock ] && return 0
-    . /etc/default/rcS
-
-    . /lib/lsb/init-functions
-    verbose_log_action_msg() { [ "$VERBOSE" = no ] || log_action_msg "$@"; }
-
-    [ "$GMT" = "-u" ] && UTC="yes"
-    case "$UTC" in
-       no|"")  GMT="--localtime"
-               UTC=""
-               if [ "X$FIRST" = "Xyes" ] && [ ! -r /etc/localtime ]; then
-                   if [ -z "$TZ" ]; then
-                       log_action_msg "System clock was not updated at this time"
-                       return 1
-                   fi
-               fi
-               ;;
-       yes)    GMT="--utc"
-               UTC="--utc"
-               ;;
-       *)      log_action_msg "Unknown UTC setting: \"$UTC\""; return 1 ;;
-    esac
-
-    case "$BADYEAR" in
-       no|"")  BADYEAR="" ;;
-       yes)    BADYEAR="--badyear" ;;
-       *)      log_action_msg "unknown BADYEAR setting: \"$BADYEAR\""; return 1 ;;
-    esac
-
-    case "$1" in
-       start)
-           if [ -w /etc ] && [ ! -f /etc/adjtime ] && [ ! -e /etc/adjtime ]; then
-               echo "0.0 0 0.0" > /etc/adjtime
-           fi
-
-           if [ ! -w /etc/adjtime ]; then
-               NOADJ="--noadjfile"
-           else
-               NOADJ=""
-           fi
-
-           if [ "$FIRST" != yes ]; then
-               # Uncomment the hwclock --adjust line below if you want
-               # hwclock to try to correct systematic drift errors in the
-               # Hardware Clock.
-               #
-               # WARNING: If you uncomment this option, you must either make
-               # sure *nothing* changes the Hardware Clock other than
-               # hwclock --systohc, or you must delete /etc/adjtime
-               # every time someone else modifies the Hardware Clock.
-               #
-               # Common "vilains" are: ntp, MS Windows, the BIOS Setup
-               # program.
-               #
-               # WARNING: You must remember to invalidate (delete)
-               # /etc/adjtime if you ever need to set the system clock
-               # to a very different value and hwclock --adjust is being
-               # used.
-               #
-               # Please read /usr/share/doc/util-linux/README.Debian.hwclock
-               # before enabling hwclock --adjust.
-
-               #/sbin/hwclock --adjust $GMT $BADYEAR
-               :
-           fi
-
-           if [ "$HWCLOCKACCESS" != no ]; then
-               log_action_msg "Setting the system clock"
-
-               # Copies Hardware Clock time to System Clock using the correct
-               # timezone for hardware clocks in local time, and sets kernel
-               # timezone. DO NOT REMOVE.
-               if /sbin/hwclock --hctosys $GMT $HWCLOCKPARS $BADYEAR $NOADJ; then
-                   #   Announce the local time.
-                   verbose_log_action_msg "System Clock set to: `date $UTC`"
-               else
-                   log_warning_msg "Unable to set System Clock to: `date $UTC`"
-               fi
-           else
-               verbose_log_action_msg "Not setting System Clock"
-           fi
-           ;;
-       stop|restart|reload|force-reload)
-           #
-           # Updates the Hardware Clock with the System Clock time.
-           # This will *override* any changes made to the Hardware Clock.
-           #
-           # WARNING: If you disable this, any changes to the system
-           #          clock will not be carried across reboots.
-           #
-           if [ "$HWCLOCKACCESS" != no ]; then
-               log_action_msg "Saving the system clock"
-               if [ "$GMT" = "-u" ]; then
-                   GMT="--utc"
-               fi
-               if /sbin/hwclock --systohc $GMT $HWCLOCKPARS $BADYEAR; then
-                   verbose_log_action_msg "Hardware Clock updated to `date`"
-               fi
-           else
-               verbose_log_action_msg "Not saving System Clock"
-           fi
-           ;;
-       show)
-           if [ "$HWCLOCKACCESS" != no ]; then
-               /sbin/hwclock --show $GMT $HWCLOCKPARS $BADYEAR
-           fi
-           ;;
-       *)
-           log_success_msg "Usage: hwclock.sh {start|stop|reload|force-reload|show}"
-           log_success_msg "       start sets kernel (system) clock from hardware (RTC) clock"
-           log_success_msg "       stop and reload set hardware (RTC) clock from kernel (system) clock"
-           return 1
-           ;;
-    esac
-}
-
-hwclocksh "$@"
-#!/bin/sh
-# hwclock.sh   Set and adjust the CMOS clock, according to the UTC
-#              setting in /etc/default/rcS (see also rcS(5)).
-#
-# Version:     @(#)hwclock.sh  2.00  14-Dec-1998  miquels@cistron.nl
-#
-# Patches:
-#              2000-01-30 Henrique M. Holschuh <hmh@rcm.org.br>
-#               - Minor cosmetic changes in an attempt to help new
-#                 users notice something IS changing their clocks
-#                 during startup/shutdown.
-#               - Added comments to alert users of hwclock issues
-#                 and discourage tampering without proper doc reading.
-
-# WARNING:     Please read /usr/share/doc/util-linux/README.Debian.hwclock
-#              before changing this file. You risk serious clock
-#              misbehaviour otherwise.
-
-### BEGIN INIT INFO
-# Provides:          hwclock
-# Required-Start:    mountdevsubfs
-# Required-Stop:     $local_fs
-# Default-Start:     S
-# Default-Stop:      0 6
-### END INIT INFO
-
-FIRST=no       # debian/rules sets this to 'yes' when creating hwclockfirst.sh
-
-# Set this to any options you might need to give to hwclock, such
-# as machine hardware clock type for Alphas.
-HWCLOCKPARS=
-
-hwclocksh()
-{
-    [ ! -x /sbin/hwclock ] && return 0
-    . /etc/default/rcS
-
-    . /lib/lsb/init-functions
-    verbose_log_action_msg() { [ "$VERBOSE" = no ] || log_action_msg "$@"; }
-
-    [ "$GMT" = "-u" ] && UTC="yes"
-    case "$UTC" in
-       no|"")  GMT="--localtime"
-               UTC=""
-               if [ "X$FIRST" = "Xyes" ] && [ ! -r /etc/localtime ]; then
-                   if [ -z "$TZ" ]; then
-                       log_action_msg "System clock was not updated at this time"
-                       return 1
-                   fi
-               fi
-               ;;
-       yes)    GMT="--utc"
-               UTC="--utc"
-               ;;
-       *)      log_action_msg "Unknown UTC setting: \"$UTC\""; return 1 ;;
-    esac
-
-    case "$BADYEAR" in
-       no|"")  BADYEAR="" ;;
-       yes)    BADYEAR="--badyear" ;;
-       *)      log_action_msg "unknown BADYEAR setting: \"$BADYEAR\""; return 1 ;;
-    esac
-
-    case "$1" in
-       start)
-           if [ -w /etc ] && [ ! -f /etc/adjtime ] && [ ! -e /etc/adjtime ]; then
-               echo "0.0 0 0.0" > /etc/adjtime
-           fi
-
-           if [ ! -w /etc/adjtime ]; then
-               NOADJ="--noadjfile"
-           else
-               NOADJ=""
-           fi
-
-           if [ "$FIRST" != yes ]; then
-               # Uncomment the hwclock --adjust line below if you want
-               # hwclock to try to correct systematic drift errors in the
-               # Hardware Clock.
-               #
-               # WARNING: If you uncomment this option, you must either make
-               # sure *nothing* changes the Hardware Clock other than
-               # hwclock --systohc, or you must delete /etc/adjtime
-               # every time someone else modifies the Hardware Clock.
-               #
-               # Common "vilains" are: ntp, MS Windows, the BIOS Setup
-               # program.
-               #
-               # WARNING: You must remember to invalidate (delete)
-               # /etc/adjtime if you ever need to set the system clock
-               # to a very different value and hwclock --adjust is being
-               # used.
-               #
-               # Please read /usr/share/doc/util-linux/README.Debian.hwclock
-               # before enabling hwclock --adjust.
-
-               #/sbin/hwclock --adjust $GMT $BADYEAR
-               :
-           fi
-
-           if [ "$HWCLOCKACCESS" != no ]; then
-               log_action_msg "Setting the system clock"
-
-               # Copies Hardware Clock time to System Clock using the correct
-               # timezone for hardware clocks in local time, and sets kernel
-               # timezone. DO NOT REMOVE.
-               if /sbin/hwclock --hctosys $GMT $HWCLOCKPARS $BADYEAR $NOADJ; then
-                   #   Announce the local time.
-                   verbose_log_action_msg "System Clock set to: `date $UTC`"
-               else
-                   log_warning_msg "Unable to set System Clock to: `date $UTC`"
-               fi
-           else
-               verbose_log_action_msg "Not setting System Clock"
-           fi
-           ;;
-       stop|restart|reload|force-reload)
-           #
-           # Updates the Hardware Clock with the System Clock time.
-           # This will *override* any changes made to the Hardware Clock.
-           #
-           # WARNING: If you disable this, any changes to the system
-           #          clock will not be carried across reboots.
-           #
-           if [ "$HWCLOCKACCESS" != no ]; then
-               log_action_msg "Saving the system clock"
-               if [ "$GMT" = "-u" ]; then
-                   GMT="--utc"
-               fi
-               if /sbin/hwclock --systohc $GMT $HWCLOCKPARS $BADYEAR; then
-                   verbose_log_action_msg "Hardware Clock updated to `date`"
-               fi
-           else
-               verbose_log_action_msg "Not saving System Clock"
-           fi
-           ;;
-       show)
-           if [ "$HWCLOCKACCESS" != no ]; then
-               /sbin/hwclock --show $GMT $HWCLOCKPARS $BADYEAR
-           fi
-           ;;
-       *)
-           log_success_msg "Usage: hwclock.sh {start|stop|reload|force-reload|show}"
-           log_success_msg "       start sets kernel (system) clock from hardware (RTC) clock"
-           log_success_msg "       stop and reload set hardware (RTC) clock from kernel (system) clock"
-           return 1
-           ;;
-    esac
-}
-
-hwclocksh "$@"
-#!/bin/sh
-### BEGIN INIT INFO
-# Provides:             keymap
-# Required-Start:       mountdevsubfs
-# Required-Stop:     
-# Default-Start:        S
-# Default-Stop:
-# Short-Description:   Set keymap
-# Description:         Set the Console keymap
-### END INIT INFO
-
-# If setupcon is present, then we've been superseded by console-setup.
-if type setupcon >/dev/null 2>&1; then
-       exit 0
-fi
-
-. /lib/lsb/init-functions
-
-#
-# Load the keymaps *as soon as possible*
-#
-
-# Don't fail on error
-CONSOLE_TYPE=`fgconsole 2>/dev/null` || CONSOLE_TYPE="unknown"
-
-# Don't fail on serial consoles
-
-QUIT=0
-# fail silently if loadkeys not present (yet).
-command -v loadkeys >/dev/null 2>&1 || QUIT=1
-
-CONFDIR=/etc/console
-CONFFILEROOT=boottime
-EXT=kmap
-CONFFILE=${CONFDIR}/${CONFFILEROOT}.${EXT}.gz
-
-reset_kernel()
-{
-       # On Mac PPC machines, we may need to set kernel vars first
-        # We need to mount /proc to do that; not optimal, as its going to 
-        # be mounted in S10checkroot, but we need it set up before sulogin
-        # may be run in checkroot, which will need the keyboard to log in...
-       [ -x /sbin/sysctl ] || return
-       [ -r /etc/sysctl.conf ] || return
-       grep -v '^\#' /etc/sysctl.conf | grep -q keycodes 
-       if [ "$?" = "0" ] ; then
-           grep keycodes /etc/sysctl.conf | grep -v "^#" | while read d ; do
-               /sbin/sysctl -w $d 2> /dev/null || true
-            done
-        fi
-}
-
-unicode_start_stop()
-{
-       # Switch unicode mode by checking the locale.
-       # This will be needed before loading the keymap.
-       [ -x /usr/bin/unicode_start ] || [ -x /bin/unicode_start ] ||  return
-       [ -x /usr/bin/unicode_stop ] || [ -x /bin/unicode_stop ] || return
-
-       ENV_FILE="none"
-       [ -r /etc/environment ] && ENV_FILE="/etc/environment"
-       [ -r /etc/default/locale ] && ENV_FILE="/etc/default/locale" 
-       [ $ENV_FILE = none ] && return
-       
-       for var in LANG LC_ALL LC_CTYPE; do
-               value=$(egrep "^[^#]*${var}=" $ENV_FILE | tail -n1 | cut -d= -f2)
-               eval $var=$value
-       done
-
-       CHARMAP=`LANG=$LANG LC_ALL=$LC_ALL LC_CTYPE=$LC_CTYPE locale charmap`
-       if [ "$CHARMAP" = "UTF-8" ]; then
-               unicode_start 2> /dev/null || true
-       else
-               unicode_stop 2> /dev/null || true
-       fi
-}
-
-if [ ! $QUIT = '1' ] ; then
-
-  case "$1" in
-      start | restart | force-reload | reload)
-  
-       # Set kernel variables if required
-       reset_kernel
-
-        # First mount /proc if necessary...and if it is there (#392798)
-        unmount_proc="no"
-       if [ -d /proc ]; then
-               if [ ! -x /proc/$$ ]; then
-                       unmount_proc="yes"      
-                       mount -n /proc
-               fi
-  
-
-               if [ -f /proc/sys/dev/mac_hid/keyboard_sends_linux_keycodes ] ; then
-                       linux_keycodes=`cat /proc/sys/dev/mac_hid/keyboard_sends_linux_keycodes`
-               else
-                       linux_keycodes=1;
-               fi
-       else
-                       linux_keycodes=1;
-       fi
-
-       # load new map
-       if [ $linux_keycodes -gt 0 ] ; then 
-         if [ -r ${CONFFILE} ] ; then
-
-           # Switch console mode to UTF-8 or ASCII as necessary
-           unicode_start_stop
-
-           if [ $CONSOLE_TYPE = "serial" ] ; then 
-                   loadkeys -q ${CONFFILE} 2>&1 > /dev/null
-           else
-                   loadkeys -q ${CONFFILE}
-           fi
-           if [ $? -gt 0 ]
-               then
-               # if we've a serial console, we may not have a keyboard, so don't
-               # complain if we fail. 
-                  if [ ! $CONSOLE_TYPE = "serial" ]; then 
-                       log_warning_msg "Problem when loading ${CONFDIR}/${CONFFILEROOT}.${EXT}.gz, use install-keymap"
-                       sleep 10
-                  fi 
-               fi
-           fi
-       fi
-
-       # unmount /proc if we mounted it
-        [ "$unmount_proc" = "no" ] || umount -n /proc
-
-       ;;
-
-    stop)
-       ;;
-
-    *)
-       log_warning_msg "Usage: $0 {start|stop|restart|reload|force-reload}"
-       ;;
-  esac
-
-fi
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          killprocs
-# Required-Start:    $local_fs
-# Required-Stop:
-# Default-Start:     1
-# Default-Stop:
-# Short-Description: executed by init(8) upon entering runlevel 1 (single).
-### END INIT INFO
-
-PATH=/usr/sbin:/usr/bin:/sbin:/bin
-
-. /lib/lsb/init-functions
-
-do_start () {
-       # Kill all processes.
-       log_action_begin_msg "Sending all processes the TERM signal"
-       killall5 -15
-       log_action_end_msg 0
-       sleep 5
-       log_action_begin_msg "Sending all processes the KILL signal"
-       killall5 -9
-       log_action_end_msg 0
-
-       # We start update here, since we just killed it.
-       if [ -x /sbin/update ] && [ "$(uname -s)" = Linux ]
-       then
-               case "$(uname -r)" in
-                 0.*|1.*|2.[0123].*)
-                       /sbin/update
-                       ;;
-               esac
-       fi
-}
-
-case "$1" in
-  start)
-       do_start
-       ;;
-  restart|reload|force-reload)
-       echo "Error: argument '$1' not supported" >&2
-       exit 3
-       ;;
-  stop)
-       # No-op
-       ;;
-  *)
-       echo "Usage: $0 start|stop" >&2
-       exit 3
-       ;;
-esac
-#! /bin/sh
-# /etc/init.d/klogd: start the kernel log daemon.
-
-### BEGIN INIT INFO
-# Provides:             klogd
-# Required-Start:       syslog
-# Required-Stop:        syslog
-# Default-Start:        S 1 2 3 4 5
-# Default-Stop:         0 6
-# Short-Description:    Kernel logger
-### END INIT INFO
-
-PATH=/bin:/usr/bin:/sbin:/usr/sbin
-
-pidfile=/var/run/klogd/klogd.pid
-kmsgpipe=/var/run/klogd/kmsg
-kmsgpidfile=/var/run/klogd/kmsgpipe.pid
-binpath=/sbin/klogd
-
-test -f $binpath || exit 0
-. /lib/lsb/init-functions
-
-#  Use KLOGD="-k /boot/System.map-$(uname -r)" to specify System.map
-#
-KLOGD="-P $kmsgpipe"
-
-test ! -r /etc/default/klogd || . /etc/default/klogd
-
-. /lib/lsb/init-functions
-
-case "$1" in
-  start)
-    log_begin_msg "Starting kernel log daemon..."
-    # create klog-writeable pid and fifo directory
-    mkdir -p /var/run/klogd
-    chown klog:klog /var/run/klogd
-    mkfifo -m 700 $kmsgpipe
-    chown klog:klog $kmsgpipe
-    # shovel /proc/kmsg to pipe readable by klogd user
-    start-stop-daemon --start --pidfile $kmsgpidfile --exec /bin/dd -b -m -- bs=1 if=/proc/kmsg of=$kmsgpipe
-    # start klogd as non-root with reading from kmsgpipe
-    start-stop-daemon --start --quiet --chuid klog --exec $binpath -- $KLOGD
-    log_end_msg $?
-    ;;
-  stop)
-    log_begin_msg "Stopping kernel log daemon..."
-    start-stop-daemon --stop --quiet --retry 3 --oknodo --exec $binpath --pidfile $pidfile
-    # stop kmsgpipe
-    start-stop-daemon --stop --quiet --oknodo --pidfile $kmsgpidfile
-    rm -f $kmsgpidfile $kmsgpipe
-    log_end_msg $?
-    ;;
-  restart|force-reload)
-    $0 stop
-    sleep 1
-    $0 start
-    ;;
-  *)
-    log_success_msg "Usage: /etc/init.d/klogd {start|stop|restart|force-reload}"
-    exit 1
-esac
-
-exit 0
-#!/bin/sh
-#
-# chkconfig: - 20 90
-# description: Starts and stops "laptop-mode" - tweaks system behavior
-#              to extend battery life.
-#
-# config:  /etc/laptop-mode/laptop-mode.conf
-
-### BEGIN INIT INFO
-# Provides:          laptop-mode
-# Should-Start:      $all
-# Required-Start:    $local_fs
-# Required-Stop:     $local_fs
-# Default-Start:     2 3 4 5
-# Default-Stop:      0 1 6
-# Short-Description: Enable laptop-mode-tools power management functions
-# Description:       Enable laptop-mode-tools power management functions
-### END INIT INFO
-
-
-test -f /usr/sbin/laptop_mode || exit 0
-
-. /lib/lsb/init-functions
-TEMPFILE=`mktemp`
-
-if [ -f /etc/default/laptop-mode ]; then
-       . /etc/default/laptop-mode;
-fi
-if [ -f /etc/default/acpi-support ]; then
-       . /etc/default/acpi-support;
-fi
-
-if [ x$ENABLE_LAPTOP_MODE = xfalse ]; then
-       exit 0;
-fi
-
-# Enable laptop mode when the system is booted when running on battery.
-
-case $1 in
-  start)
-    log_action_begin_msg "Enabling laptop mode"
-    mkdir -p /var/run/laptop-mode-tools
-    touch /var/run/laptop-mode-tools/enabled
-    /usr/sbin/laptop_mode init auto > $TEMPFILE
-    log_action_end_msg $? "$( cat $TEMPFILE )"
-    ;;
-
-  restart|reload|force-reload)
-    # Full restart: first stop laptop mode completely (to restore default mount options etc.)
-    log_action_begin_msg "Disabling laptop mode"
-    mkdir -p /var/run/laptop-mode-tools
-    rm -f /var/run/laptop-mode-tools/enabled
-    /usr/sbin/laptop_mode init stop > $TEMPFILE
-    log_action_end_msg $? "$( cat $TEMPFILE )"
-
-    # Now remove files containing stored status, re-enable, and start it up again.
-    log_action_begin_msg "Enabling laptop mode"
-    rm -f /var/run/laptop-mode-tools/*\r
-    touch /var/run/laptop-mode-tools/enabled
-    /usr/sbin/laptop_mode init auto force > $TEMPFILE
-    log_action_end_msg $? "$( cat $TEMPFILE )"
-    ;;
-
-  stop)
-    log_action_begin_msg "Disabling laptop mode"
-    rm -f /var/run/laptop-mode-tools/enabled
-    /usr/sbin/laptop_mode init stop > $TEMPFILE
-    log_action_end_msg $? "$( cat $TEMPFILE )"
-    ;;
-
-  status)
-    echo "Laptop mode status:"
-    echo
-    /usr/sbin/laptop_mode status
-    ;;
+if opt.name:
+    if cli:
+        cli.update_ref(refname, commit, oldref)
+    else:
+        git.update_ref(refname, commit, oldref)
+
+if cli:
+    cli.close()
+
+secs = time.time() - start_time
+size = hashsplit.total_split
+if opt.bench:
+    log('\nbup: %.2fkbytes in %.2f secs = %.2f kbytes/sec\n'
+        % (size/1024., secs, size/1024./secs))
+#!/usr/bin/env python
+import sys, re, struct, mmap
+from bup import git, options
+from bup.helpers import *
+
+
+def s_from_bytes(bytes):
+    clist = [chr(b) for b in bytes]
+    return ''.join(clist)
+
+
+def report(count):
+    fields = ['VmSize', 'VmRSS', 'VmData', 'VmStk']
+    d = {}
+    for line in open('/proc/self/status').readlines():
+        l = re.split(r':\s*', line.strip(), 1)
+        d[l[0]] = l[1]
+    if count >= 0:
+        e1 = count
+        fields = [d[k] for k in fields]
+    else:
+        e1 = ''
+    print ('%9s  ' + ('%10s ' * len(fields))) % tuple([e1] + fields)
+    sys.stdout.flush()
+
+
+optspec = """
+bup memtest [-n elements] [-c cycles]
+--
+n,number=  number of objects per cycle
+c,cycles=  number of cycles to run
+ignore-midx  ignore .midx files, use only .idx files
+"""
+o = options.Options('bup memtest', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if extra:
+    o.fatal('no arguments expected')
+
+git.ignore_midx = opt.ignore_midx
+
+git.check_repo_or_die()
+m = git.PackIdxList(git.repo('objects/pack'))
+
+cycles = opt.cycles or 100
+number = opt.number or 10000
+
+report(-1)
+f = open('/dev/urandom')
+a = mmap.mmap(-1, 20)
+report(0)
+for c in xrange(cycles):
+    for n in xrange(number):
+        b = f.read(3)
+        if 0:
+            bytes = list(struct.unpack('!BBB', b)) + [0]*17
+            bytes[2] &= 0xf0
+            bin = struct.pack('!20s', s_from_bytes(bytes))
+        else:
+            a[0:2] = b[0:2]
+            a[2] = chr(ord(b[2]) & 0xf0)
+            bin = str(a[0:20])
+        #print bin.encode('hex')
+        m.exists(bin)
+    report((c+1)*number)
+#!/usr/bin/env python
+import sys, os, stat
+from bup import options, git, vfs
+from bup.helpers import *
+
+def print_node(text, n):
+    prefix = ''
+    if opt.hash:
+        prefix += "%s " % n.hash.encode('hex')
+    if stat.S_ISDIR(n.mode):
+        print '%s%s/' % (prefix, text)
+    elif stat.S_ISLNK(n.mode):
+        print '%s%s@' % (prefix, text)
+    else:
+        print '%s%s' % (prefix, text)
+
+
+optspec = """
+bup ls <dirs...>
+--
+s,hash   show hash for each file
+"""
+o = options.Options('bup ls', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+git.check_repo_or_die()
+top = vfs.RefList(None)
+
+if not extra:
+    extra = ['/']
+
+ret = 0
+for d in extra:
+    try:
+        n = top.lresolve(d)
+        if stat.S_ISDIR(n.mode):
+            for sub in n:
+                print_node(sub.name, sub)
+        else:
+            print_node(d, n)
+    except vfs.NodeError, e:
+        log('error: %s\n' % e)
+        ret = 1
+
+sys.exit(ret)
+#!/usr/bin/env python
+import sys, os, re, stat, readline, fnmatch
+from bup import options, git, shquote, vfs
+from bup.helpers import *
+
+def node_name(text, n):
+    if stat.S_ISDIR(n.mode):
+        return '%s/' % text
+    elif stat.S_ISLNK(n.mode):
+        return '%s@' % text
+    else:
+        return '%s' % text
+
+
+def do_ls(path, n):
+    l = []
+    if stat.S_ISDIR(n.mode):
+        for sub in n:
+            l.append(node_name(sub.name, sub))
+    else:
+        l.append(node_name(path, n))
+    print columnate(l, '')
     
-  *)
-    echo "Usage: $0 {stop|start|restart|reload|force-reload|status}" >&2
-    exit 2
-    ;;
-esac
-
-if [ -f $TEMPFILE ] ; then
-       rm $TEMPFILE
-fi
-
-exit 0
-#!/bin/sh
-### BEGIN INIT INFO
-# Provides:          libpam-foreground-clean
-# Required-Start:    $local_fs $remote_fs
-# Required-Stop:
-# Default-Start:     S
-# Default-Stop:
-# Short-Description: Clean old status files during boot.
-### END INIT INFO
-
-set -e
-
-. /lib/lsb/init-functions
-PATH=/sbin:/bin
-
-STATEDIR=/var/run/console
-
-case "$1" in
-  start)
-    if [ -d $STATEDIR ]; then
-      log_begin_msg "Cleaning up $STATEDIR/..."
-      rm -f $STATEDIR/*
-      log_end_msg 0
-    fi
-    exit 0
-    ;;
-
-  stop|restart|force-reload)
-    exit 0
-    ;;
-
-  *)
-    echo "Usage: $0 {start|stop|restart|force-reload}" >&2
-    exit 3
-    ;;
-esac
-#!/bin/sh -e
-#
-# loopback - brings up the loopback (127.0.0.1) network device so that
-#            DHCP and other such things will work
-#
 
-# Check the package is still installed
-[ -x /sbin/ifup ] || exit 0
-
-# Get LSB functions
-. /lib/lsb/init-functions
-. /etc/default/rcS
-
-case "$1" in
-    start)
-       [ -d /var/run/network ] || mkdir /var/run/network
-
-       log_begin_msg "Starting basic networking..."
-       if ifup --allow auto lo; then
-           log_end_msg 0
-       else
-           log_end_msg $?
-       fi
-       ;;
-    stop)
-       log_begin_msg "Stopping basic networking..."
-       if ifdown lo; then
-           log_end_msg 0
-       else
-           log_end_msg $?
-       fi
-       ;;
-    restart|force-reload)
-       exit 0
-       ;;
-    *)
-       echo "Usage: /etc/init.d/loopback {start|stop|restart|force-reload}"
-       exit 1
-       ;;
-esac
-
-exit 0
-#! /bin/sh
-
-N=/etc/init.d/makedev
-PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
-
-set -e
-
-case "$1" in
-  start)
-       test -L /dev/MAKEDEV || ln -fs /sbin/MAKEDEV /dev/MAKEDEV
-
-       # create dvb-devices, if the dvb-directory allready exists, and 
-       # no devfs or udev is in use (workaround for the changed major-number
-       # of the dvb-devices, introduced in kernel 2.6.8, to be able to 
-       # switch between kernels <= 2.6.7 and >= 2.6.8, without manual 
-       # recreation of the devices (MAKEDEV dvb checks the kernel-version 
-       # and uses the correct major-number))
-       
-       if [ ! -e /dev/.devfsd -a ! -e /dev/.udevdb ]; then
-               if [ -d /dev/dvb ]; then
-                       cd /dev && ./MAKEDEV dvb
-               fi
-       fi
-       
-       ;;
-  stop|reload|restart|force-reload)
-       ;;
-  *)
-       echo "Usage: $N {start|stop|restart|force-reload}" >&2
-       exit 1
-       ;;
-esac
-
-exit 0
-#!/bin/sh
-#
-# Start the RAID monitor daemon for all active md arrays if desired.
-#
-# Copyright (c) 2001-2004 Mario Jou/3en <joussen@debian.org>
-# Distributable under the terms of the GNU GPL version 2.
-
-MDADM=/sbin/mdadm
-DEBIANCONFIG=/etc/default/mdadm
-PIDFILE=/var/run/mdadm.pid
-
-test -x $MDADM || exit 0
-
-. /lib/lsb/init-functions
-
-MAIL_TO=root
-START_DAEMON=true
-test -f $DEBIANCONFIG && . $DEBIANCONFIG
-
-case "$1" in
-    start)
-        if [ "x$START_DAEMON" = "xtrue" ] ; then
-            log_begin_msg "Starting RAID monitoring services..."
-            start-stop-daemon -S -q -p $PIDFILE -x $MDADM -- -F -i $PIDFILE -m $MAIL_TO -f -s
-            log_end_msg $?
-        fi
-        ;;
-    stop)
-        if [ -f $PIDFILE ] ; then
-            log_begin_msg "Stopping RAID monitoring services..."
-            start-stop-daemon -K -q -p $PIDFILE -x $MDADM
-           log_end_msg $?
-            rm -f $PIDFILE
-        fi
-        ;;
-    restart|reload|force-reload)
-        $0 stop
-        $0 start
-        ;;
-    *)
-        log_success_msg "Usage: $0 {start|stop|restart|reload|force-reload}"
-        exit 1
-        ;;
-esac
-
-exit 0
-#!/bin/sh
-#
-# Start any arrays which are described in /etc/mdadm/mdadm.conf and which are
-# not running already.
-#
-# Copyright (c) 2001-2004 Mario Jou/3en <joussen@debian.org>
-# Distributable under the terms of the GNU GPL version 2.
-
-MDADM=/sbin/mdadm
-MDRUN=/sbin/mdrun
-CONFIG=/etc/mdadm/mdadm.conf
-DEBIANCONFIG=/etc/default/mdadm
-
-. /lib/lsb/init-functions
-
-test -x $MDADM || exit 0
-
-AUTOSTART=true
-test -f $DEBIANCONFIG && . $DEBIANCONFIG
-
-case "$1" in
-    start)
-       if [ "x$AUTOSTART" = "xtrue" ] ; then
-            if [ ! -f /proc/mdstat ] && [ -x /sbin/modprobe ] ; then
-                /sbin/modprobe -k md > /dev/null 2>&1  
-            fi
-            test -f /proc/mdstat || exit 0
-           log_begin_msg "Starting RAID devices..."
-           if [ -f $CONFIG ] && [ -x $MDADM ] ; then
-               $MDADM -A -s
-           elif [ -x $MDRUN ] ; then
-               $MDRUN
-           fi
-           log_end_msg $?
-       fi
-        ;;
-    stop|restart|reload|force-reload)
-        ;;
-    *)
-       log_success_msg "Usage: $0 {start|stop|restart|reload|force-reload}"
-        exit 1
-        ;;
-esac
-
-exit 0
-#!/bin/sh -e
-### BEGIN INIT INFO
-# Provides:          module-init-tools
-# Required-Start:    
-# Required-Stop:     
-# Should-Start:      checkroot
-# Should-stop:
-# Default-Start:     S
-# Default-Stop:
-# Short-Description: Process /etc/modules.
-# Description:       Load the modules listed in /etc/modules.
-### END INIT INFO
-
-# Silently exit if the kernel does not support modules or needs modutils.
-[ -f /proc/modules ] || exit 0
-[ ! -f /proc/ksyms ] || exit 0
-[ -x /sbin/modprobe  ] || exit 0
-
-. /etc/default/rcS
-. /lib/lsb/init-functions
-
-PATH="/sbin:/bin"
-
-KVER=$(uname -r)
-KMAJ=${KVER%${KVER#*.*[^.]}}
-KMAJ=${KMAJ%.}
-
-if [ -e /etc/modules-$KVER ]; then
-  MODULES_FILE=/etc/modules-$KVER
-elif [ -e /etc/modules-$KMAJ ]; then
-  MODULES_FILE=/etc/modules-$KMAJ
-else
-  MODULES_FILE=/etc/modules
-fi
-
-load_module() {
-  local module args
-  module="$1"
-  args="$2"
-
-  if [ "$VERBOSE" != no ]; then
-    log_action_msg "Loading kernel module $module"
-    modprobe $module $args || true
-  else
-    modprobe $module $args > /dev/null 2>&1 || true
-  fi   
-}
-
-if [ "$VERBOSE" = no ]; then
-  log_action_begin_msg 'Loading kernel modules'
-fi
-
-# Loop over every line in /etc/modules.
-log_begin_msg 'Loading manual drivers...'
-grep '^[^#]' $MODULES_FILE | \
-while read module args; do
-  [ "$module" ] || continue
-  load_module "$module" "$args"
-done
-
-if [ "$VERBOSE" = no ]; then 
-  log_action_end_msg 0
-fi
-
-exit 0
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          mountall-bootclean
-# Required-Start:    mountall
-# Required-Stop:
-# Default-Start:     S
-# Default-Stop:
-# Short-Description: bootclean after mountall.
-# Description:       Clean temporary filesystems after
-#                    all local filesystems have been mounted.
-### END INIT INFO
-
-case "$1" in
-  start|"")
-       # Clean /tmp
-       /etc/init.d/bootclean
-       ;;
-  restart|reload|force-reload)
-       echo "Error: argument '$1' not supported" >&2
-       exit 3
-       ;;
-  stop)
-       # No-op
-       ;;
-  *)
-       echo "Usage: mountall-bootclean.sh [start|stop]" >&2
-       exit 3
-       ;;
-esac
-
-:
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          mountall
-# Required-Start:    checkfs
-# Required-Stop: 
-# Should-Start:      lvm
-# Should-Stop:
-# Default-Start:     S
-# Default-Stop:
-# Short-Description: Mount all filesystems.
-# Description:
-### END INIT INFO
-
-PATH=/sbin:/bin
-. /lib/init/vars.sh
-
-. /lib/lsb/init-functions
-. /lib/init/mount-functions.sh
-
-if [ -r /etc/default/locale ]; then
-       . /etc/default/locale
-       export LANG
-fi
-
-do_start() {
-       #
-       # Mount local file systems in /etc/fstab.
-       #
-       pre_mountall
-       if [ "$VERBOSE" = no ]
-       then
-               log_action_begin_msg "Mounting local filesystems"
-               mount -a -t proc >/dev/null 2>&1  # Ignore error message due to /proc already being mounted
-               ES_TO_REPORT=$?
-               mount -a -t noproc,nfs,nfs4,smbfs,cifs,ncp,ncpfs,coda,ocfs2,gfs
-               ES=$?
-               ES_TO_REPORT=$(($ES_TO_REPORT | $ES))
-               if [ 0 = "$ES_TO_REPORT" ]
-               then
-                       log_action_end_msg 0
-               else
-                       log_action_end_msg 1 "code $ES_TO_REPORT"
-               fi
-       else
-               log_action_msg "Will now mount local filesystems"
-               mount -a -t proc >/dev/null 2>&1  # Ignore error message due to /proc already being mounted
-               ES=$?
-               [ 0 = "$ES" ] || log_failure_msg "Mounting proc filesystems failed with error code ${ES}."
-               mount -a -v -t noproc,nfs,nfs4,smbfs,cifs,ncp,ncpfs,coda,ocfs2,gfs
-               ES=$?
-               if [ 0 = "$ES" ]
-               then
-                       log_success_msg "Done mounting local filesystems."
-               else
-                       log_failure_msg "Mounting local filesystems failed with error code ${ES}."
-               fi
-       fi
-
-       post_mountall
-
-       case "$(uname -s)" in
-         *FreeBSD)
-               INITCTL=/etc/.initctl
-               ;;
-         *)
-               INITCTL=/dev/initctl
-               ;;
-       esac
-
-       #
-       # We might have mounted something over /dev, see if
-       # /dev/initctl is there.
-       #
-       if [ ! -p $INITCTL ]
-       then
-               rm -f $INITCTL
-               mknod -m 600 $INITCTL p
-       fi
-       kill -USR1 1
-
-       #
-       # Execute swapon command again, in case we want to swap to
-       # a file on a now mounted filesystem.
-       #
-       # Ignore 255 status due to swap already being enabled
-       #
-       if [ "$VERBOSE" = no ]
-       then
-               log_action_begin_msg "Activating swapfile swap"
-               swapon -a -e 2>/dev/null || :  # Stifle "Device or resource busy"
-               log_action_end_msg 0
-       else
-               log_action_msg "Will now activate swapfile swap"
-               swapon -a -e -v || :
-               log_success_msg "Done activating swapfile swap."
-       fi
-}
-
-case "$1" in
-  start|"")
-       do_start
-       ;;
-  restart|reload|force-reload)
-       echo "Error: argument '$1' not supported" >&2
-       exit 3
-       ;;
-  stop)
-       # No-op
-       ;;
-  *)
-       echo "Usage: mountall.sh [start|stop]" >&2
-       exit 3
-       ;;
-esac
-
-:
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          mountdevsubfs mountvirtfs
-# Required-Start:    mountkernfs
-# Required-Stop:
-# Default-Start:     S
-# Default-Stop:
-# Short-Description: Mount special file systems under /dev.
-# Description:       Mount the virtual filesystems the kernel provides
-#                    that ordinarily live under the /dev filesystem.
-### END INIT INFO
-
-PATH=/lib/init:/sbin:/bin
-TTYGRP=5
-TTYMODE=620
-[ -f /etc/default/devpts ] && . /etc/default/devpts
-
-TMPFS_SIZE=
-[ -f /etc/default/tmpfs ] && . /etc/default/tmpfs
-
-KERNEL="$(uname -s)"
-
-. /lib/lsb/init-functions
-. /lib/init/mount-functions.sh
-
-do_start () {
-       #
-       # Mount a tmpfs on /dev/shm
-       #
-       SHM_OPT=
-       [ "${SHM_SIZE:=$TMPFS_SIZE}" ] && SHM_OPT="-osize=$SHM_SIZE"
-       domount tmpfs shmfs /dev/shm $SHM_OPT
-
-       #
-       # Mount /dev/pts. Create master ptmx node if needed.
-       #
-       domount devpts "" /dev/pts -ogid=$TTYGRP,mode=$TTYMODE
-
-       #
-       # Magic to make /proc/bus/usb work
-       #
-       #mkdir -p /dev/bus/usb/.usbfs
-       #domount usbfs "" /dev/bus/usb/.usbfs -obusmode=0700,devmode=0600,listmode=0644
-       #ln -s .usbfs/devices /dev/bus/usb/devices
-       #mount --rbind /dev/bus/usb /proc/bus/usb
-}
-
-case "$1" in
-  "")
-       echo "Warning: mountdevsubfs should be called with the 'start' argument." >&2
-       do_start
-       ;;
-  start)
-       do_start
-       ;;
-  restart|reload|force-reload)
-       echo "Error: argument '$1' not supported" >&2
-       exit 3
-       ;;
-  stop)
-       # No-op
-       ;;
-  *)
-       echo "Usage: mountdevsubfs [start|stop]" >&2
-       exit 3
-       ;;
-esac
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          mountkernfs
-# Required-Start:
-# Required-Stop:
-# Default-Start:     S
-# Default-Stop:
-# Short-Description: Mount kernel virtual file systems.
-# Description:       Mount initial set of virtual filesystems the kernel
-#                    provides and that are required by everything.
-### END INIT INFO
-
-PATH=/lib/init:/sbin:/bin
-
-. /lib/lsb/init-functions
-. /lib/init/mount-functions.sh
-
-do_start () {
-       #
-       # Mount proc filesystem on /proc
-       #
-       domount proc "" /proc -onodev,noexec,nosuid
-
-       #
-       # Mount sysfs on /sys
-       #
-       domount sysfs "" /sys -onodev,noexec,nosuid
-
-       # Mount /var/run and /var/lock as tmpfs.
-       domount tmpfs "" /var/run -omode=0755,nodev,noexec,nosuid
-       domount tmpfs "" /var/lock -omode=1777,nodev,noexec,nosuid
-
-       # Mount spufs, if Cell Broadband processor is detected
-       if mountpoint -q /proc && grep -qs '^cpu.*Cell' /proc/cpuinfo; then
-               mkdir -p /spu
-               domount spufs "" /spu -ogid=spu
-       fi
-
-       # Propagate files from the initramfs to our new /var/run.
-       for file in /dev/.initramfs/varrun/*; do
-               [ -e "$file" ] || continue
-               cp -a "$file" "/var/run/${x#/dev/.initramfs/varrun/}"
-       done
-
-       if [ ! -d /var/run/sendsigs.omit.d/ ]; then
-               mkdir /var/run/sendsigs.omit.d/
-       fi
-}
-
-case "$1" in
-  "")
-       echo "Warning: mountvirtfs should be called with the 'start' argument." >&2
-       do_start
-       ;;
-  start)
-       do_start
-       ;;
-  restart|reload|force-reload)
-       echo "Error: argument '$1' not supported" >&2
-       exit 3
-       ;;
-  stop)
-       # No-op
-       ;;
-  *)
-       echo "Usage: mountvirtfs [start|stop]" >&2
-       exit 3
-       ;;
-esac
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          mountnfs-bootclean
-# Required-Start:    mountnfs
-# Required-Stop:
-# Default-Start:     S
-# Default-Stop:
-# Short-Description: bootclean after mountnfs.
-# Description:       Clean temporary filesystems after
-#                    network filesystems have been mounted.
-### END INIT INFO
-
-case "$1" in
-  start|"")
-       # Clean /tmp
-       /etc/init.d/bootclean
-       ;;
-  restart|reload|force-reload)
-       echo "Error: argument '$1' not supported" >&2
-       exit 3
-       ;;
-  stop)
-       # No-op
-       ;;
-  *)
-       echo "Usage: mountnfs-bootclean.sh [start|stop]" >&2
-       exit 3
-       ;;
-esac
-
-:
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          mountoverflowtmp
-# Required-Start:    mountall-bootclean
-# Required-Stop:
-# Default-Start:     S
-# Default-Stop:
-# Short-Description: mount emergency /tmp.
-# Description:       Mount a tmpfs on /tmp if there would
-#                    otherwise be too little space to log in.
-### END INIT INFO
-
-. /lib/lsb/init-functions
-
-set -e
-
-defs=/etc/default/mountoverflowtmp
-test ! -f "$defs" || . "$defs"
-
-: ${MINTMPKB:=1024}
-if test "$MINTMPKB" = "0"; then exit 0; fi
-
-case "$1" in
-  start|"")
-       log_action_begin_msg "Checking minimum space in /tmp"
-       df="`df -kP /tmp`"
-       avail="`printf "%s" "$df" | awk 'NR==2 { print $4 }'`"
-       log_action_end_msg 0
-       if test $avail -lt "$MINTMPKB"; then
-               log_action_begin_msg "Mounting emergency tmpfs on /tmp"
-               mount -t tmpfs -o size=1048576,mode=1777 overflow /tmp
-               log_action_end_msg 0
-       fi
-       ;;
-  restart|reload|force-reload)
-       echo "Error: argument '$1' not supported" >&2
-       exit 3
-       ;;
-  stop)
-       log_action_begin_msg "Unmounting any overflow tmpfs from /tmp"
-       if LANG=C LC_ALL=C mount | \
-               grep '^overflow on /tmp type tmpfs' >/dev/null; then
-               umount overflow
-       fi
-       log_action_end_msg 0
-       ;;
-  *)
-       echo "Usage: mountoverflowtmp [start|stop]" >&2
-       exit 3
-       ;;
-esac
-
-:
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          mtab
-# Required-Start:    mountall
-# Required-Stop:
-# Default-Start:     S
-# Default-Stop:
-# Short-Description: Update mtab file.
-# Description:       Update the mount program's mtab file after
-#                    all local filesystems have been mounted.
-### END INIT INFO
-
-PATH=/lib/init:/sbin:/bin
-TTYGRP=5
-TTYMODE=620
-[ -f /etc/default/devpts ] && . /etc/default/devpts
-
-TMPFS_SIZE=
-[ -f /etc/default/tmpfs ] && . /etc/default/tmpfs
-
-KERNEL="$(uname -s)"
-
-. /lib/lsb/init-functions
-. /lib/init/mount-functions.sh
-
-domtab ()
-{
-       # Directory present?
-       if [ ! -d $2 ]
-       then
-               return
-       fi
-
-       # Not mounted?
-       if ! mountpoint -q $2
-       then
-               return
-       fi
-
-       if [ -n "$3" ]
-       then
-               NAME="$3"
-       else
-               NAME="$1"
-       fi
-
-       # Already recorded?
-       if ! grep -E -sq "^([^ ]+) +$2 +" /etc/mtab
-       then
-               mount -f -t $1 $OPTS $4 $NAME $2
-       fi
-}
-
-do_start () {
-       DO_MTAB=""
-       MTAB_PATH="$(readlink -f /etc/mtab || :)"
-       case "$MTAB_PATH" in
-         /proc/*)
-               # Assume that /proc/ is not writable
-               ;;
-         /*)
-               # Only update mtab if it is known to be writable
-               # Note that the touch program is in /usr/bin
-               #if ! touch "$MTAB_PATH" >/dev/null 2>&1
-               #then
-               #       return
-               #fi
-               ;;
-         "")
-               [ -L /etc/mtab ] && MTAB_PATH="$(readlink /etc/mtab)"
-               if [ "$MTAB_PATH" ]
-               then
-                       log_failure_msg "Cannot initialize ${MTAB_PATH}."
-               else
-                       log_failure_msg "Cannot initialize /etc/mtab."
-               fi
-               ;;
-         *)
-               log_failure_msg "Illegal mtab location '${MTAB_PATH}'."
-               ;;
-       esac
-
-       #
-       # Initialize mtab file if necessary
-       #
-       if [ ! -f /etc/mtab ]
-       then
-               :> /etc/mtab
-               chmod 644 /etc/mtab
-       fi
-       if selinux_enabled && which restorecon >/dev/null 2>&1 && [ -r /etc/mtab ]
-       then
-               restorecon /etc/mtab
-       fi
-
-       # S01mountkernfs.sh
-       domtab proc /proc "proc" -onodev,noexec,nosuid
-       domtab sysfs /sys "sys" -onodev,noexec,nosuid
-       domtab tmpfs /var/run "varrun" -omode=0755,nodev,noexec,nosuid
-       domtab tmpfs /var/lock "varlock" -omode=1777,nodev,noexec,nosuid
-       domtab usbfs /proc/bus/usb "procbususb"
-
-       # S10udev
-       domtab tmpfs /dev "udev" -omode=0755
-
-       # S02mountdevsubfs
-       SHM_OPT=
-       [ "${SHM_SIZE:=$TMPFS_SIZE}" ] && SHM_OPT="-osize=$SHM_SIZE"
-       domtab tmpfs /dev/shm "devshm" $SHM_OPT
-       domtab devpts /dev/pts "devpts" -ogid=$TTYGRP,mode=$TTYMODE
-
-       # S07linux-restricted-modules-common
-       exec 9<&0 0</proc/mounts
-       while read FDEV FDIR FTYPE FOPTS REST
-       do
-               case "$FDIR" in
-                       /lib/modules/*/volatile)
-                               domtab "$FTYPE" "$FDIR" "lrm"
-                               ;;
-               esac
-       done
-       exec 0<&9 9<&-
-
-       # /etc/network/if-up.d/mountnfs
-       exec 9<&0 </etc/fstab
-       while read FDEV FDIR FTYPE FOPTS REST
-       do
-               case "$FDEV" in
-                 ""|\#*)
-                       continue
-                       ;;
-               esac
-               case "$FOPTS" in
-                 noauto|*,noauto|noauto,*|*,noauto,*)
-                       continue
-                       ;;
-               esac
-               case "$FTYPE" in
-                 nfs|nfs4|smbfs|cifs|coda|ncp|ncpfs|ocfs2|gfs)
-                       domtab "$FTYPE" "$FDIR" "$FDEV" "-o$FOPTS"
-                       ;;
-                 *)
-                       continue
-                       ;;
-               esac
-        done
-        exec 0<&9 9<&-
-
-       
-}
-
-case "$1" in
-  start|"")
-       do_start
-       ;;
-  restart|reload|force-reload)
-       echo "Error: argument '$1' not supported" >&2
-       exit 3
-       ;;
-  stop)
-       # No-op
-       ;;
-  *)
-       echo "Usage: mountall-mtab.sh [start|stop]" >&2
-       exit 3
-       ;;
-esac
-
-:
-#!/bin/bash
-#
-# MySQL daemon start/stop script.
-#
-# Debian version. Based on the original by TcX.
-#
-set -e
-set -u
-${DEBIAN_SCRIPT_DEBUG:+ set -v -x}
-
-test -x /usr/sbin/mysqld || exit 0
-
-SELF=$(cd $(dirname $0); pwd -P)/$(basename $0)
-CONF=/etc/mysql/my.cnf
-MYADMIN="/usr/bin/mysqladmin --defaults-file=/etc/mysql/debian.cnf"
-
-# priority can be overriden and "-s" adds output to stderr
-ERR_LOGGER="logger -p daemon.err -t /etc/init.d/mysql -i"
-
-# Safeguard (relative paths, core dumps..)
-cd /
-umask 077
-
-# mysqladmin likes to read /root/.my.cnf. This is usually not what I want
-# as many admins e.g. only store a password without a username there and
-# so break my scripts.
-export HOME=/etc/mysql/
-
-## fetch a particular option from mysql's invocation
-#
-# usage: void mysqld_get_param option
-mysqld_get_param() {
-       /usr/sbin/mysqld --print-defaults \
-               | tr " " "\n" \
-               | grep -- "--$1" \
-               | tail -n 1 \
-               | cut -d= -f2
-}
-
-## Checks if there is a server running and if so if it is accessible.
-#
-# check_alive insists on a pingable server
-# check_dead also fails if there is a lost mysqld in the process list
-#
-# Usage: boolean mysqld_status [check_alive|check_dead] [warn|nowarn]
-mysqld_status () {
-    ping_output=`$MYADMIN ping 2>&1`; ping_alive=$(( ! $? ))
-
-    ps_alive=0
-    pidfile=`mysqld_get_param pid-file`
-    if [ -f "$pidfile" ] && ps `cat $pidfile` >/dev/null 2>&1; then ps_alive=1; fi
+def write_to_file(inf, outf):
+    for blob in chunkyreader(inf):
+        outf.write(blob)
     
-    if [ "$1" = "check_alive"  -a  $ping_alive = 1 ] ||
-       [ "$1" = "check_dead"   -a  $ping_alive = 0  -a  $ps_alive = 0 ]; then
-       return 0 # EXIT_SUCCESS
-    else
-       if [ "$2" = "warn" ]; then
-           /bin/echo -e "$ps_alive processes alive and '$MYADMIN ping' resulted in\n$ping_output\n" | $ERR_LOGGER -p daemon.debug
-       fi
-       return 1 # EXIT_FAILURE
-    fi
-}
-
-#
-# main()
-#
-
-case "${1:-''}" in
-  'start')
-       # check for config file
-       if [ ! -r /etc/mysql/my.cnf ]; then
-         /bin/echo -e "\nWARNING: /etc/mysql/my.cnf cannot be read. See README.Debian.gz"
-        fi 
-       # Start daemon
-       echo -n "Starting MySQL database server: mysqld"
-       if mysqld_status check_alive nowarn; then
-          echo "...already running."
-       else
-           /usr/bin/mysqld_safe > /dev/null 2>&1 &
-           for i in 1 2 3 4 5 6; do
-                sleep 1
-               if mysqld_status check_alive nowarn ; then break; fi
-            done
-           if mysqld_status check_alive warn; then
-                echo "."
-               # Now start mysqlcheck or whatever the admin wants.
-               /etc/mysql/debian-start
-           else
-               echo "...failed."
-               /bin/echo -e "\tPlease take a look at the syslog."
-           fi
-       fi
-
-        if $MYADMIN variables | egrep -q have_bdb.*YES; then
-            /bin/echo "BerkeleyDB is obsolete, see /usr/share/doc/mysql-server-4.1/README.Debian.gz" | $ERR_LOGGER -p daemon.info
-        fi
-       ;;
-
-  'stop')
-       # * As a passwordless mysqladmin (e.g. via ~/.my.cnf) must be possible
-       # at least for cron, we can rely on it here, too. (although we have 
-       # to specify it explicit as e.g. sudo environments points to the normal
-       # users home and not /root)
-       echo -n "Stopping MySQL database server: mysqld"        
-       if ! mysqld_status check_dead nowarn; then
-         set +e
-         shutdown_out=`$MYADMIN shutdown 2>&1`; r=$?
-         set -e
-         if [ "$r" -ne 0 ]; then
-           /bin/echo -e -n "...failed.\n$shutdown_out\nKilling MySQL database server by signal: mysqld"
-           killall -15 mysqld
-            server_down=
-           for i in 1 2 3 4 5 6 7 8 9 10; do
-              sleep 1
-              if mysqld_status check_dead nowarn; then server_down=1; break; fi
-            done
-          if test -z "$server_down"; then killall -9 mysqld; fi
-         fi
-        fi
-
-        if ! mysqld_status check_dead warn; then
-         echo "...failed."
-         echo "Please stop MySQL manually and read /usr/share/doc/mysql-server-4.1/README.Debian.gz!"
-         exit -1
-       else
-         echo "."
-        fi
-       ;;
-
-  'restart')
-       set +e; $SELF stop; set -e
-       $SELF start 
-       ;;
-
-  'reload'|'force-reload')
-       echo -n "Reloading MySQL database server: mysqld"
-       $MYADMIN reload
-       echo "."
-       ;;
-
-  'status')
-       if mysqld_status check_alive nowarn; then
-         $MYADMIN version
-       else
-         echo "MySQL is stopped."
-         exit 3
-       fi
-       ;;
-
-  *)
-       echo "Usage: $SELF start|stop|restart|reload|force-reload|status"
-       exit 1
-       ;;
-esac
-
-#!/bin/bash
-#
-# MySQL NDB management daemon start/stop script.
-#
-set -e
-set -u
-${DEBIAN_SCRIPT_DEBUG:+ set -v -x}
-
-# Variables
-SELF=$(cd $(dirname $0); pwd -P)/$(basename $0)
-DAEMON=/usr/sbin/ndbd
-CONF=/etc/mysql/my.cnf
-export HOME=/etc/mysql/
-
-# Safeguard (relative paths, core dumps..)
-cd /
-umask 077
-
-# Exit *silently* if we're not supposed to be started.
-#
-# The Debian scripts should execute these scripts to stop and start
-# the daemon when upgrading if it is started. On the other hand it should
-# remain silently if the server has not even been configured.
-# See /usr/share/doc/mysql-server-*/README.Debian for more information.
-test -x $DAEMON || exit 0
-if $DAEMON --help | grep -q '^ndb-connectstring.*No default value'; then exit 0; fi
-
-#
-# main()
-#
-case "${1:-''}" in
-  'start')
-       # Start daemon
-        # Creatign a PID file does not work as the master process forks
-        # a child with different PID and then terminates itself.
-       echo -n "Starting MySQL NDB cluster server: ndbd"
-       if start-stop-daemon \
-               --start \
-               --exec $DAEMON \
-               --user mysql
-       then
-         echo "."
-       else
-         echo "...failed."
-         /bin/echo -e "\tPlease take a look at the syslog."
-         exit 1
-       fi                        
-       ;;
-
-  'stop')
-       echo -n "Stopping MySQL NDB cluster management server: ndbd"    
-       if start-stop-daemon \
-               --stop \
-               --oknodo \
-               --exec $DAEMON
-       then
-         echo "."
-       else
-         echo "...failed."
-         exit 1
-        fi
-       ;;
-
-  'restart'|'force-reload')
-       set +e; $SELF stop; set -e
-       $SELF start 
-       ;;
-
-  *)
-       echo "Usage: $SELF start|stop|restart|force-reload"
-       exit 1
-       ;;
-esac
-
-#!/bin/bash
-#
-# MySQL NDB management daemon start/stop script.
-#
-set -e
-set -u
-${DEBIAN_SCRIPT_DEBUG:+ set -v -x}
-
-# Variables
-SELF=$(cd $(dirname $0); pwd -P)/$(basename $0)
-DAEMON=/usr/sbin/ndb_mgmd
-CONF=/etc/mysql/ndb_mgmd.cnf
-export HOME=/etc/mysql/
-
-# Safeguard (relative paths, core dumps..)
-cd /
-umask 077
-
-# Exit *silently* if we're not supposed to be started.
-#
-# The Debian scripts should execute these scripts to stop and start
-# the daemon when upgrading if it is started. On the other hand it should
-# remain silently if the server has not even been configured.
-# See /usr/share/doc/mysql-server-*/README.Debian for more information.
-test -x $DAEMON || exit 0
-test -r $CONF || exit 0
-
-#
-# main()
-#
-case "${1:-''}" in
-  'start')
-       # Start daemon
-       echo -n "Starting MySQL NDB cluster management server: ndb_mgmd"
-       # --pid-file does not work as the daemon forks itself with $PID=$PID+1
-       if start-stop-daemon \
-               --start \
-               --exec $DAEMON \
-               --user mysql \
-               -- \
-               -f $CONF
-       then
-         echo "."
-       else
-         echo "...failed."
-         /bin/echo -e "\tPlease take a look at the syslog."
-         exit 1
-       fi                        
-       ;;
-
-  'stop')
-       echo -n "Stopping MySQL NDB cluster management server: ndb_mgmd"        
-       if start-stop-daemon \
-               --stop \
-               --oknodo \
-               --exec $DAEMON
-       then
-         echo "."
-       else
-         echo "...failed."
-         exit 1
-        fi
-       ;;
-
-  'restart'|'force-reload')
-       set +e; $SELF stop; set -e
-       $SELF start 
-       ;;
-
-  *)
-       echo "Usage: $SELF start|stop|restart|force-reload"
-       exit 1
-       ;;
-esac
-
-#!/bin/sh -e
-### BEGIN INIT INFO
-# Provides:          networking
-# Required-Start:    mountkernfs ifupdown $local_fs
-# Required-Stop:     ifupdown $local_fs
-# Default-Start:     S
-# Default-Stop:      0 6
-# Short-Description: Raise network interfaces.
-### END INIT INFO
-
-PATH="/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin"
-
-[ -x /sbin/ifup ] || exit 0
-
-. /lib/lsb/init-functions
-
-
-case "$1" in
-start)
-       log_action_begin_msg "Configuring network interfaces"
-        type usplash_write >/dev/null 2>/dev/null && usplash_write "TIMEOUT 120" || true
-       if [ "$VERBOSE" != no ]; then
-           if ifup -a; then
-               log_action_end_msg $?
-           else
-               log_action_end_msg $?
-           fi
-       else
-           if ifup -a >/dev/null 2>&1; then
-               log_action_end_msg $?
-           else
-               log_action_end_msg $?
-           fi
-       fi
-        type usplash_write >/dev/null 2>/dev/null && usplash_write "TIMEOUT 15" || true
-       ;;
-
-stop)
-       if sed -n 's/^[^ ]* \([^ ]*\) \([^ ]*\) .*$/\2/p' /proc/mounts | 
-               grep -qE '^(nfs[1234]?|smbfs|ncp|ncpfs|coda|cifs)$'; then
-           log_warning_msg "not deconfiguring network interfaces: network shares still mounted."
-           exit 0
-       fi
-
-       log_action_begin_msg "Deconfiguring network interfaces"
-       if [ "$VERBOSE" != no ]; then
-           if ifdown -a --exclude=lo; then
-               log_action_end_msg $?
-           else
-               log_action_end_msg $?
-           fi
-       else
-           if ifdown -a --exclude=lo >/dev/null 2>/dev/null; then
-               log_action_end_msg $?
-           else
-               log_action_end_msg $?
-           fi
-       fi
-       ;;
-
-force-reload|restart)
-       log_action_begin_msg "Reconfiguring network interfaces"
-       ifdown -a --exclude=lo || true
-       if ifup -a --exclude=lo; then
-           log_action_end_msg $?
-       else
-           log_action_end_msg $?
-       fi
-       ;;
-
-*)
-       echo "Usage: /etc/init.d/networking {start|stop|restart|force-reload}"
-       exit 1
-       ;;
-esac
-
-exit 0
-
-#!/bin/sh
-#
-# nfs-common    This shell script takes care of starting and stopping
-#               common daemons required for NFS clients and servers.
-#
-# chkconfig: 345 20 80
-# description: NFS is a popular protocol for file sharing across \
-#             TCP/IP networks. This service provides NFS file \
-#             locking functionality.
-#
-
-set -e
-
-# What is this?
-DESC="NFS common utilities"
-
-# Read config
-DEFAULTFILE=/etc/default/nfs-common
-PREFIX=
-NEED_LOCKD=
-NEED_IDMAPD=yes
-IDMAPD_PIDFILE=/var/run/rpc.idmapd.pid
-NEED_GSSD=yes
-GSSD_PIDFILE=/var/run/rpc.gssd.pid
-PIPEFS_MOUNTPOINT=/var/lib/nfs/rpc_pipefs
-RPCGSSDOPTS=
-if [ -f $DEFAULTFILE ]; then
-    . $DEFAULTFILE
-fi
-
-. /lib/lsb/init-functions
-
-# Determine whether lockd daemon is required.
-case "$NEED_LOCKD" in
-yes|no)        ;;
-*)  case `uname -r` in
-    '' | [01].* | 2.[0123].* )
-       # Older kernels may or may not need a lockd daemon.
-       # We must assume they do, unless we can prove otherwise.
-       # (A false positive here results only in a harmless message.)
-       NEED_LOCKD=yes
-       if test -f /proc/ksyms
-       then
-           grep -q lockdctl /proc/ksyms || NEED_LOCKD=no
-       fi
-       ;;
-
-    *)  # Modern kernels (>= 2.4) start a lockd thread automatically.
-       NEED_LOCKD=no
-       ;;
-    esac
-    ;;
-esac
-
-# Exit if required binaries are missing.
-[ -x $PREFIX/sbin/rpc.statd ] || exit 0
-[ -x $PREFIX/sbin/rpc.lockd ] || [ "$NEED_LOCKD"  = no ] || exit 0
-[ -x /usr/sbin/rpc.idmapd   ] || [ "$NEED_IDMAPD" = no ] || exit 0
-[ -x /usr/sbin/rpc.gssd     ] || [ "$NEED_GSSD"   = no ] || exit 0
-
-do_modprobe() {
-    modprobe -q "$1" || true
-}
 
-do_mount() {
-    if ! grep -E -qs "$1\$" /proc/filesystems
-    then
-       return 1
-    fi
-    if ! mountpoint -q "$2"
-    then
-       mount -t "$1" "$1" "$2"
-       return
-    fi
-    return 0
-}
-
-# See how we were called.
-case "$1" in
-  start)
-       cd /    # daemons should have root dir as cwd
-       log_begin_msg "Starting nfs statd..."
-       ERROR=0
-       start-stop-daemon --start --quiet \
-           --exec $PREFIX/sbin/rpc.statd -- $STATDOPTS || ERROR=1
-       log_end_msg $ERROR
-       if [ "$NEED_LOCKD" = yes ]
-       then
-           log_begin_msg "Starting nfs lockd..."
-           ERROR=0
-           start-stop-daemon --start --quiet \
-               --exec $PREFIX/sbin/rpc.lockd || ERROR=1
-           log_end_msg $ERROR
-       fi
-       if [ "$NEED_IDMAPD" = yes ] || [ "$NEED_GSSD" = yes ]
-       then
-           do_modprobe nfs
-           if do_mount rpc_pipefs $PIPEFS_MOUNTPOINT
-           then
-               if [ "$NEED_IDMAPD" = yes ]
-               then
-                   log_begin_msg "Starting rpc idmapd..."
-                   ERROR=0
-                   start-stop-daemon --start --quiet \
-                           --make-pidfile --pidfile $IDMAPD_PIDFILE \
-                           --exec /usr/sbin/rpc.idmapd || ERROR=1
-                   log_end_msg $ERROR
-               fi
-               if [ "$NEED_GSSD" = yes ]
-               then
-                   log_begin_msg "Starting rpc gssd..."
-                   ERROR=0
-                   start-stop-daemon --start --quiet \
-                           --make-pidfile --pidfile $GSSD_PIDFILE \
-                           --exec /usr/sbin/rpc.gssd -- $RPCGSSDOPTS || ERROR=1
-                   log_end_msg $ERROR
-               fi
-           fi
-       fi
-       ;;
-
-  stop)
-       if [ "$NEED_GSSD" = yes ]
-       then
-           log_begin_msg "Stopping rpc gssd..."
-           ERROR=0
-           start-stop-daemon --stop --oknodo --quiet \
-                   --name rpc.gssd --user 0 || ERROR=1
-           log_end_msg $ERROR
-           rm -f $GSSD_PIDFILE
-       fi
-       if [ "$NEED_IDMAPD" = yes ]
-       then
-           log_begin_msg "Stopping rpc idmapd..."
-           ERROR=0
-           start-stop-daemon --stop --oknodo --quiet \
-               --name rpc.idmapd --user 0 || ERROR=1
-           log_end_msg $ERROR
-           rm -f $IDMAPD_PIDFILE
-       fi
-       if [ "$NEED_LOCKD" = yes ]
-       then
-           log_begin_msg "Stopping nfs lockd..."
-           ERROR=0
-           start-stop-daemon --stop --oknodo --quiet \
-               --name rpc.lockd --user 0  || ERROR=1
-           log_end_msg $ERROR
-       fi
-       log_begin_msg "Stopping nfs statd..."
-       ERROR=0
-       start-stop-daemon --stop --oknodo --quiet \
-           --name rpc.statd --user 0 || ERROR=1
-       log_end_msg $ERROR
-       ;;
-
-  restart | force-reload)
-       $0 stop
-       sleep 1
-       $0 start
-       ;;
-
-  *)
-       log_success_msg "Usage: nfs-common {start|stop|restart}"
-       exit 1
-       ;;
-esac
-
-exit 0
-#!/bin/sh
-#
-# nfs-kernel-server
-#              This shell script takes care of starting and stopping
-#               the kernel-mode NFS server.
-#
-# chkconfig: 345 60 20
-# description: NFS is a popular protocol for file sharing across TCP/IP \
-#              networks. This service provides NFS server functionality, \
-#              which is configured via the /etc/exports file.
-#
-
-set -e
-
-# What is this?
-DESC="NFS kernel daemon"
-PREFIX=/usr
-
-# Exit if required binaries are missing.
-[ -x $PREFIX/sbin/rpc.nfsd    ] || exit 0
-[ -x $PREFIX/sbin/rpc.mountd  ] || exit 0
-[ -x $PREFIX/sbin/exportfs    ] || exit 0
-[ -x $PREFIX/sbin/rpc.svcgssd ] || exit 0
-
-# Read config
-DEFAULTFILE=/etc/default/nfs-kernel-server
-RPCNFSDCOUNT=8
-RPCMOUNTDOPTS=
-NEED_SVCGSSD=yes
-RPCGSSDOPTS=
-RPCSVCGSSDOPTS=
-PROCNFSD_MOUNTPOINT=/proc/fs/nfsd
-if [ -f $DEFAULTFILE ]; then
-    . $DEFAULTFILE
-fi
-
-. /lib/lsb/init-functions
-
-do_modprobe() {
-    modprobe -q "$1" || true
-}
-
-do_mount() {
-    if ! grep -E -qs "$1\$" /proc/filesystems
-    then
-       return 1
-    fi
-    if ! mountpoint -q "$2"
-    then
-       mount -t "$1" "$1" "$2"
-       return
-    fi
-    return 0
-}
-
-# See how we were called.
-case "$1" in
-  start)
-       cd /    # daemons should have root dir as cwd
-       if grep -q '^/' /etc/exports
-       then
-               do_modprobe nfsd
-               do_mount nfsd $PROCNFSD_MOUNTPOINT || NEED_SVCGSSD=no
-               log_begin_msg "Exporting directories for $DESC..."
-               ERROR=0
-               $PREFIX/sbin/exportfs -r || ERROR=1
-               log_end_msg $ERROR
-
-               if [ "$NEED_SVCGSSD" = yes ]
-               then
-                   log_begin_msg "Starting rpc svcgssd..."
-                   ERROR=0
-                   start-stop-daemon --start --quiet \
-                           --make-pidfile --pidfile /var/run/rpc.svcgssd.pid \
-                           --exec $PREFIX/sbin/rpc.svcgssd -- $RPCSVCGSSDOPTS || ERROR=1
-                   log_end_msg $ERROR
-               fi
-
-               log_begin_msg "Starting rpc nfsd..."
-               ERROR=0
-               start-stop-daemon --start --quiet \
-                   --exec $PREFIX/sbin/rpc.nfsd -- $RPCNFSDCOUNT || ERROR=1
-               log_end_msg $ERROR
-
-               # make sure 127.0.0.1 is a valid source for requests
-               ClearAddr=
-               if [ -f /proc/net/rpc/auth.unix.ip/channel ]
-               then
-                   fgrep -qs 127.0.0.1 /proc/net/rpc/auth.unix.ip/content || {
-                       echo "nfsd 127.0.0.1 2147483647 localhost" >/proc/net/rpc/auth.unix.ip/channel
-                       ClearAddr=yes
-                   }
-               fi
-
-               $PREFIX/bin/rpcinfo -u localhost nfs 3 >/dev/null 2>&1 ||
-                   RPCMOUNTDOPTS="$RPCMOUNTDOPTS --no-nfs-version 3"
-
-               [ -z "$ClearAddr" ] || echo "nfsd 127.0.0.1 1" >/proc/net/rpc/auth.unix.ip/channel
-
-               log_begin_msg "Starting rpc mountd..."
-               ERROR=0
-               start-stop-daemon --start --quiet \
-                   --exec $PREFIX/sbin/rpc.mountd -- $RPCMOUNTDOPTS || ERROR=1
-               log_end_msg $ERROR
-       else
-               log_warning_msg "Not starting $DESC: No exports."
-       fi
-       ;;
-
-  stop)
-       log_begin_msg "Stopping rpc mountd..."
-       ERROR=0
-       start-stop-daemon --stop --oknodo --quiet \
-           --name rpc.mountd --user 0 || ERROR=1
-       log_end_msg $ERROR
-       if [ "$NEED_SVCGSSD" = yes ]
-       then
-           log_begin_msg "Stopping rpc svcgssd..."
-           ERROR=0
-           start-stop-daemon --stop --oknodo --quiet \
-                   --name rpc.svcgssd --user 0 || ERROR=1
-           log_end_msg $ERROR
-           rm -f /var/run/rpc.svcgssd.pid
-       fi
-       log_begin_msg "Stopping rpc nfsd..."
-       ERROR=0
-       start-stop-daemon --stop --oknodo --quiet \
-           --name nfsd --user 0 --signal 2 || ERROR=1
-       log_end_msg $ERROR
-
-       log_begin_msg "Unexporting directories for $DESC..."
-       ERROR=0
-       $PREFIX/sbin/exportfs -au || ERROR=1
-       log_end_msg $ERROR
-       ;;
-
-  reload | force-reload)
-       log_begin_msg "Re-exporting directories for $DESC..."
-       ERROR=0
-       $PREFIX/sbin/exportfs -r || ERROR=1
-       log_end_msg $ERROR
-       ;;
-
-  restart)
-       $0 stop
-       sleep 1
-       $0 start
-       ;;
-
-  *)
-       log_success_msg "Usage: nfs-kernel-server {start|stop|reload|force-reload|restart}"
-       exit 1
-       ;;
-esac
-
-exit 0
-#! /bin/sh
-#
-### BEGIN INIT INFO
-# Provides:          pcmcia
-# Required-Start:    udev
-# Required-Stop:
-# Default-Start:     S
-# Default-Stop:
-# Short-Description: PCMCIA support
-# Description:       This service provides PCMCIA hardware support for
-#                    systems running Linux >= 2.6.13-rc1.
-### END INIT INFO
-
-set -e
-
-[ -f /sbin/pccardctl ] || exit 0
-
-# If /lib/lsb/init-functions doesn't exist
-# define them here, otherwise installer breaks
-if [ -f /lib/lsb/init-functions ]; then
-    . /lib/lsb/init-functions
-else
-    log_daemon_msg()
-    {
-       echo "$1: $2"
-    }
-    log_end_msg()
-    {
-       if [ "$1" = 0 ]; then
-           echo "done"
-       else
-           echo "failed!"
-       fi
-       return $1
-    }
-    log_success_msg()
-    {
-       echo "$@"
-    }
-    log_failure_msg()
-    {
-       echo "$@"
-    }
-fi
-
-[ -f /etc/default/pcmciautils ] && . /etc/default/pcmciautils
-
-case $PCMCIA in
-    no|false)
-       exit 0
-       ;;
-esac
-
-[ -f /etc/default/rcS ] && . /etc/default/rcS
-
-# Are we running from init?
-run_by_init()
-{
-    ([ "$previous" ] && [ "$runlevel" ]) || [ "$runlevel" = S ]
-}
-
-if ls /sys/class/pcmcia_socket/* >/dev/null 2>&1; then
-    if ! run_by_init; then
-       log_success_msg "PCMCIA bridge driver already present in kernel"
-    fi
-    exit 0
-fi
-
-KERNEL_VERSION="$(uname -r | sed 's/-.*//')"
-
-supported_kernel()
-{
-    case $KERNEL_VERSION in
-       2.[012345].*|2.6.[0-9]|2.6.[0-9][!0-9]*) return 1 ;;
-       2.6.1[012]|2.6.1[012][!0-9]*) return 1 ;;
-    esac
-    return 0
-}
-
-if ! supported_kernel; then
-    if ! run_by_init; then
-       log_failure_msg "pcmciautils requires Linux >= 2.6.13-rc1; use pcmcia-cs instead"
-    fi
-    exit 1
-fi
-
-if [ -z "$PCIC" ]; then
-    if ! run_by_init; then
-       log_failure_msg "No PCMCIA bridge module specified"
-    fi
-    exit 1
-fi
-
-if ! [ -e /dev/.udev ]; then
-    if ! run_by_init; then
-       log_failure_msg "pcmciautils requires udev to be enabled"
-    fi
-    exit 1
-fi
-
-if [ "$VERBOSE" = "no" ]; then
-    MODPROBE_OPTIONS="$MODPROBE_OPTIONS -Q"
-    export MODPROBE_OPTIONS
-fi
-
-case "$1" in
-    start)
-       log_daemon_msg "Loading PCMCIA bridge driver module" "$PCIC"
-
-       if [ "$CORE_OPTS" ]; then
-           modprobe -Qb pcmcia_core $CORE_OPTS
-       fi
-       
-       modprobe -Qb $PCIC $PCIC_OPTS
-       
-       log_end_msg $?
-       ;;
-
-    stop)
-       ;;
+def inputiter():
+    if os.isatty(sys.stdin.fileno()):
+        while 1:
+            try:
+                yield raw_input('bup> ')
+            except EOFError:
+                break
+    else:
+        for line in sys.stdin:
+            yield line
+
+
+def _completer_get_subs(line):
+    (qtype, lastword) = shquote.unfinished_word(line)
+    (dir,name) = os.path.split(lastword)
+    #log('\ncompleter: %r %r %r\n' % (qtype, lastword, text))
+    n = pwd.resolve(dir)
+    subs = list(filter(lambda x: x.name.startswith(name),
+                       n.subs()))
+    return (dir, name, qtype, lastword, subs)
+
+
+_last_line = None
+_last_res = None
+def completer(text, state):
+    global _last_line
+    global _last_res
+    try:
+        line = readline.get_line_buffer()[:readline.get_endidx()]
+        if _last_line != line:
+            _last_res = _completer_get_subs(line)
+            _last_line = line
+        (dir, name, qtype, lastword, subs) = _last_res
+        if state < len(subs):
+            sn = subs[state]
+            sn1 = sn.resolve('')  # deref symlinks
+            fullname = os.path.join(dir, sn.name)
+            if stat.S_ISDIR(sn1.mode):
+                ret = shquote.what_to_add(qtype, lastword, fullname+'/',
+                                          terminate=False)
+            else:
+                ret = shquote.what_to_add(qtype, lastword, fullname,
+                                          terminate=True) + ' '
+            return text + ret
+    except Exception, e:
+        log('\nerror in completion: %s\n' % e)
+
+            
+optspec = """
+bup ftp
+"""
+o = options.Options('bup ftp', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+git.check_repo_or_die()
+
+top = vfs.RefList(None)
+pwd = top
+
+if extra:
+    lines = extra
+else:
+    readline.set_completer_delims(' \t\n\r/')
+    readline.set_completer(completer)
+    readline.parse_and_bind("tab: complete")
+    lines = inputiter()
+
+for line in lines:
+    if not line.strip():
+        continue
+    words = [word for (wordstart,word) in shquote.quotesplit(line)]
+    cmd = words[0].lower()
+    #log('execute: %r %r\n' % (cmd, parm))
+    try:
+        if cmd == 'ls':
+            for parm in (words[1:] or ['.']):
+                do_ls(parm, pwd.resolve(parm))
+        elif cmd == 'cd':
+            for parm in words[1:]:
+                pwd = pwd.resolve(parm)
+        elif cmd == 'pwd':
+            print pwd.fullname()
+        elif cmd == 'cat':
+            for parm in words[1:]:
+                write_to_file(pwd.resolve(parm).open(), sys.stdout)
+        elif cmd == 'get':
+            if len(words) not in [2,3]:
+                raise Exception('Usage: get <filename> [localname]')
+            rname = words[1]
+            (dir,base) = os.path.split(rname)
+            lname = len(words)>2 and words[2] or base
+            inf = pwd.resolve(rname).open()
+            log('Saving %r\n' % lname)
+            write_to_file(inf, open(lname, 'wb'))
+        elif cmd == 'mget':
+            for parm in words[1:]:
+                (dir,base) = os.path.split(parm)
+                for n in pwd.resolve(dir).subs():
+                    if fnmatch.fnmatch(n.name, base):
+                        try:
+                            log('Saving %r\n' % n.name)
+                            inf = n.open()
+                            outf = open(n.name, 'wb')
+                            write_to_file(inf, outf)
+                            outf.close()
+                        except Exception, e:
+                            log('  error: %s\n' % e)
+        elif cmd == 'help' or cmd == '?':
+            log('Commands: ls cd pwd cat get mget help quit\n')
+        elif cmd == 'quit' or cmd == 'exit' or cmd == 'bye':
+            break
+        else:
+            raise Exception('no such command %r' % cmd)
+    except Exception, e:
+        log('error: %s\n' % e)
+        #raise
+#!/usr/bin/env python
+import sys, mmap
+from bup import options, _hashsplit
+from bup.helpers import *
+
+optspec = """
+bup random [-S seed] <numbytes>
+--
+S,seed=   optional random number seed (default 1)
+f,force   print random data to stdout even if it's a tty
+"""
+o = options.Options('bup random', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if len(extra) != 1:
+    o.fatal("exactly one argument expected")
+
+total = parse_num(extra[0])
+
+if opt.force or (not os.isatty(1) and
+                 not atoi(os.environ.get('BUP_FORCE_TTY')) & 1):
+    _hashsplit.write_random(sys.stdout.fileno(), total, opt.seed or 0)
+else:
+    log('error: not writing binary data to a terminal. Use -f to force.\n')
+    sys.exit(1)
+#!/usr/bin/env python
+import sys, os, glob
+from bup import options
+
+optspec = """
+bup help <command>
+"""
+o = options.Options('bup help', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if len(extra) == 0:
+    # the wrapper program provides the default usage string
+    os.execvp(os.environ['BUP_MAIN_EXE'], ['bup'])
+elif len(extra) == 1:
+    docname = (extra[0]=='bup' and 'bup' or ('bup-%s' % extra[0]))
+    exe = sys.argv[0]
+    (exepath, exefile) = os.path.split(exe)
+    manpath = os.path.join(exepath, '../Documentation/' + docname + '.[1-9]')
+    g = glob.glob(manpath)
+    if g:
+        os.execvp('man', ['man', '-l', g[0]])
+    else:
+        os.execvp('man', ['man', docname])
+else:
+    o.fatal("exactly one command name expected")
+#!/usr/bin/env python
+import sys, os, stat, errno, fuse, re, time, tempfile
+from bup import options, git, vfs
+from bup.helpers import *
+
+
+class Stat(fuse.Stat):
+    def __init__(self):
+        self.st_mode = 0
+        self.st_ino = 0
+        self.st_dev = 0
+        self.st_nlink = 0
+        self.st_uid = 0
+        self.st_gid = 0
+        self.st_size = 0
+        self.st_atime = 0
+        self.st_mtime = 0
+        self.st_ctime = 0
+        self.st_blocks = 0
+        self.st_blksize = 0
+        self.st_rdev = 0
+
+
+cache = {}
+def cache_get(top, path):
+    parts = path.split('/')
+    cache[('',)] = top
+    c = None
+    max = len(parts)
+    #log('cache: %r\n' % cache.keys())
+    for i in range(max):
+        pre = parts[:max-i]
+        #log('cache trying: %r\n' % pre)
+        c = cache.get(tuple(pre))
+        if c:
+            rest = parts[max-i:]
+            for r in rest:
+                #log('resolving %r from %r\n' % (r, c.fullname()))
+                c = c.lresolve(r)
+                key = tuple(pre + [r])
+                #log('saving: %r\n' % (key,))
+                cache[key] = c
+            break
+    assert(c)
+    return c
+        
     
-    restart)
-       $0 stop
-       $0 start
-       exit $?
-       ;;
-
-    reload|force-reload)
-       ;;
-
-    *)
-       log_success_msg "Usage: $0 {start|stop|restart|reload|force-reload}"
-       exit 2
-       ;;
-esac
-#!/bin/sh
-#
-# start/stop portmap daemon.
-
-### BEGIN INIT INFO
-# Provides:          portmap
-# Required-Start:    $network
-# Required-Stop:     $network
-# Should-Start:      $named
-# Should-Stop:       $named
-# Default-Start:     S 1 2 3 4 5
-# Default-Stop:      0 6
-### END INIT INFO
-
-test -f /sbin/portmap || exit 0
-
-. /lib/lsb/init-functions
-
-OPTIONS=""
-if [ -f /etc/default/portmap ]; then
-  . /etc/default/portmap
-elif [ -f /etc/portmap.conf ]; then
-  . /etc/portmap.conf
-fi
-
-case "$1" in
-    start)
-       pid=`pidof portmap`
-       if [ -n "$pid" ] ; then
-            log_begin_msg "Not starting portmap daemon.  Already running."
-            log_end_msg 0
-            exit 0
-       fi
-       log_begin_msg "Starting portmap daemon..."
-        start-stop-daemon --start --quiet --oknodo --exec /sbin/portmap -- $OPTIONS
-       log_end_msg $?
-
-       sleep 1 # needs a short pause or pmap_set won't work. :(
-       if [ -f /var/run/portmap.upgrade-state ]; then
-         log_begin_msg "Restoring old RPC service information..."
-         pmap_set </var/run/portmap.upgrade-state
-         log_end_msg $?
-         rm -f /var/run/portmap.upgrade-state
-       else
-         if [ -f /var/run/portmap.state ]; then
-           pmap_set </var/run/portmap.state
-           rm -f /var/run/portmap.state
-         fi
-       fi
-
-       ;;
-    stop)
-       log_begin_msg "Stopping portmap daemon..."
-       pmap_dump >/var/run/portmap.state
-       start-stop-daemon --stop --quiet --oknodo --exec /sbin/portmap
-       log_end_msg $?
-       ;;
-    force-reload)
-       $0 restart
-       ;;
-    restart)
-       $0 stop
-       $0 start
-       ;;
-    *)
-       log_success_msg "Usage: /etc/init.d/portmap {start|stop|force-reload|restart}"
-       exit 1
-       ;;
-esac
-
-exit 0
-
-#!/bin/sh -e
-#
-#   /etc/init.d/ppp: start or stop PPP link.
-#
-# This configuration method is deprecated, please use /etc/network/interfaces.
-
-[ -x /usr/sbin/pppd -a -f /etc/ppp/ppp_on_boot ] || exit 0
-if [ -x /etc/ppp/ppp_on_boot ]; then RUNFILE=1; fi
-. /lib/lsb/init-functions
-
-case "$1" in
-start)
-    log_begin_msg "Starting up PPP link..."
-    if [ "$RUNFILE" = "1" ]; then
-        /etc/ppp/ppp_on_boot
-    else
-        pppd call provider
-    fi
-    log_end_msg $?
-    ;;
-stop)
-    log_begin_msg "Shutting down PPP link..."
-    if [ "$RUNFILE" = "1" ]; then
-        poff -a
-    else
-        poff provider
-    fi
-    log_end_msg $?
-    ;;
-restart|force-reload)
-    log_begin_msg "Restarting PPP link..."
-    if [ "$RUNFILE" = "1" ]; then      
-        poff -a || true
-        sleep 5
-        /etc/ppp/ppp_on_boot
-    else                  
-        poff provider || true
-        sleep 5
-        pppd call provider
-    fi
-    log_end_msg $?
-    ;;
-*)
-    log_success_msg "Usage: /etc/init.d/ppp {start|stop|restart|force-reload}"
-    exit 1
-    ;;
-esac
-
-exit 0
-#!/bin/sh -e
-### BEGIN INIT INFO
-# Provides:          pppd-dns
-# Required-Start:    $local_fs
-# Default-Start:     S
-# Short-Description: Restore resolv.conf if the system crashed.
-### END INIT INFO
-#
-# Restore /etc/resolv.conf if the system crashed before the ppp link
-# was shut down.
-
-[ -x /etc/ppp/ip-down.d/0000usepeerdns ] \
-       && exec /etc/ppp/ip-down.d/0000usepeerdns
-
-#!/bin/sh
-###########################################################################
-# Autostart script for guest tools' service.
-#
-# Copyright (c) 2005-2008 Parallels Software International, Inc.
-# All rights reserved.
-# http://www.parallels.com
-###########################################################################
-
-
-###
-# chkconfig: 2345 99 20
-# description: Autostart script for guest tools' service.
-###
-
-### BEGIN INIT INFO
-# Provides: prltoolsd
-# required-start:
-# required-stop:
-# Default-Start: 2 3 4 5
-# Default-Stop:  0 1 6
-# Description:   Autostart script for guest tools' service.
-### END INIT INFO
-
-
-###########################################################################
-# Set configuration data
-###########################################################################
-
-prlfile="prltoolsd"
-exefile="/usr/bin/${prlfile}"
-pidfile="/var/run/${prlfile}.pid"
-
-# Set custom options if they are required
-PRLTOOLSD_OPTIONS="-p $pidfile"
-
-###########################################################################
-# Install client ID for wireless bridged networking
-###########################################################################
-
-# Install record for client ID sending for each networking card
-# in the system in the dhclient.conf (dhclient is installed)
-dhclient_install() {
-       # Locate dhclient.conf using strings. The directory can be
-       # different on different distributions
-       CONF=`strings /sbin/dhclient | grep etc | grep dhclient.conf`
-       IFACES=$*
-
-       # and can even not exists...
-       mkdir -p `dirname $CONF`
-       touch $CONF
-
-       for IFACE in $IFACES; do
-               HWADDR=`ifconfig -a | grep ^$IFACE | awk '{ print $5 }'`
-               export IFACE HWADDR
-
-               # Install section like
-                # interface "eth0" {
-               #       send dhcp-client-identifier 1:<real_mac>;
-               # }
-                # or leave it untouched if present
-               awk '
-                       BEGIN {
-                               inside_iface = 0
-                               iface_found = 0
-                       }
-                       END {
-                               iface = ENVIRON["IFACE"]
-                               addr = ENVIRON["HWADDR"]
-                               if (!iface_found) {
-                                       print "interface \""iface"\" {"
-                                       print " send dhcp-client-identifier 1:"addr"; # Remove this comment on manual client-id modification"
-                                       print "}"
-                               }
-                       }
-
-                       /^ *interface/ {
-                               iface = ENVIRON["IFACE"]
-                               test_if = $2
-                               gsub(/\"/, "", test_if)
-                               gsub(/ /, "", test_if)
-                               if (test_if == iface)
-                                       iface_found = inside_iface = 1
-                       }
-
-                       /dhcp-client-identifier/ {
-                               str = $0
-                               if (inside_iface &&
-                                   match(str, /Remove this/))
-                                       next
-                               else
-                                       inside_iface = 0
-                       }
-
-                       /\}/ {
-                               addr = ENVIRON["HWADDR"]
-
-                               if (inside_iface)
-                                       print " send dhcp-client-identifier 1:"addr"; # Remove this comment on manual client-id modification"
-                               inside_iface = 0
-                       }
-
-                       {
-                               print $0
-                       }
-               ' $CONF >$CONF.tmp1 || exit 0
-               mv $CONF.tmp1 $CONF
-       done
-}
-
-# Install key to send client ID (dhcpcd is installed)
-# Kludge to do this on the per/interface basis is not found
-dhcpc_install() {
-       CONF="/etc/sysconfig/network/dhcp"
-       HWADDR=`/sbin/ifconfig -a | awk '/HWaddr/ { print $5 ; exit }'`
-       export HWADDR
-       awk '/DHCLIENT_CLIENT_ID=/{
-               str = str1 = $0
-               sub(/\".*\"/, "", str1)
-               if (length(str1) + 2 >= length(str) || match($str, /Remove this/))
-                       print "DHCLIENT_CLIENT_ID=\"1:"ENVIRON["HWADDR"]"\" # Remove this comment on manual client-id modification"
-               else
-                       print $0
-               next
-       }
-       {
-               print $0
-       }
-       ' $CONF >$CONF.tmp1 || exit 0
-       mv $CONF.tmp1 $CONF
-}
-
-clientid_install() {
-       IFACES=`ifconfig -a | awk '/HWaddr/{ print $1 }' | xargs`
-       if [ -n "$IFACES" ]; then
-               [ -f /sbin/dhclient ] && dhclient_install $IFACES
-               [ -f /etc/sysconfig/network/dhcp ] && dhcpc_install $IFACES
-       fi
-}
-
-###########################################################################
-# Start and Stop operations for tools' daemon
-###########################################################################
-
-start() {
-    if [ -f $pidfile ]; then
-        rm -f $pidfile;
-    fi
-
-    echo -n $"Loading Parallels ToolsGate driver: "
-    if modprobe prl_tg; then
-        echo $"done"
-    else
-        echo $"failed"
-    fi
-
-    echo -n $"Loading Parallels Network driver: "
-
-       # Installing client-id to the DHCP client configuration
-       # is temporary disabled.
-
-    #clientid_install
-
-    if modprobe prl_eth; then
-        echo $"done"
-    else
-        echo $"failed"
-    fi
-
-    echo -n $"Loading Parallels Shared Folders driver: "
-    if modprobe prl_fs; then
-        echo $"done"
-    else
-        echo $"failed"
-    fi
-
-    echo -n $"Starting Parallels tools daemon: "
-    $exefile ${PRLTOOLSD_OPTIONS}
-    RETVAL=$?
-    if [ -n $RETVAL ]; then
-        echo $"done"
-    else
-        echo $"failed"
-    fi
-
-    return $RETVAL
-}
-
-stop() {
-    RETVAL=0
-
-    echo -n $"Shutting down Parallels tools daemon: "
-
-    if [ -f $pidfile ]; then
-        prlpid=`cat $pidfile 2>/dev/null`
-
-        if [ -n $prlpid ] && [ -e /proc/$prlpid ]; then
-            kill $prlpid;
-            RETVAL=$?
-        fi
-
-        rm -f $pidfile;
-    fi
-
-    if [ -n $RETVAL ]; then
-        echo $"done"
-    else
-        echo $"failed"
-    fi
-
-    return $RETVAL
-}
-
-###########################################################################
-# Perform initial operations
-###########################################################################
-
-[ -f $exefile ] || exit 0
-
-###########################################################################
-# Start/stop guest tools' service
-###########################################################################
-
-case "$1" in
-    start)
-        start
-    ;;
-    stop)
-        stop
-    ;;
-    restart)
-        stop
-        start
-    ;;
-    *)
-        echo "=> This script starts/stops Parallels guest tools' service"
-        echo "Usage: $0 <start | stop | restart>"
-        exit 1
-    ;;
-esac
-
-exit $?
-#! /bin/sh
-# /etc/init.d/procps: Set kernel variables from /etc/sysctl.conf
-#
-# written by Elrond <Elrond@Wunder-Nett.org>
-
-### BEGIN INIT INFO
-# Provides:          procps
-# Required-Start:    mountkernfs
-# Required-Stop:
-# Default-Start:     S
-# Default-Stop:
-# Short-Description: Configure kernel parameters at boottime
-# Description:  Loads kernel parameters that are specified in /etc/sysctl.conf
-### END INIT INFO
-
-
-# Check for existance of the default file and exit if not there,
-# Closes #52839 for the boot-floppy people
-[ -r /etc/default/rcS ] || exit 0
-. /etc/default/rcS
-. /lib/lsb/init-functions
-
-PATH=/sbin:$PATH
-which sysctl > /dev/null || exit 0
-
-
-case "$1" in
-       start|restart|force-reload)
-               if [ ! -r /etc/sysctl.conf ]
-               then
-                       exit 0
-               fi
-               quiet="-q"
-               if [ "$VERBOSE" = "yes" ]; then
-                       quiet=""
-               fi
-              log_action_begin_msg "Setting kernel variables"
-               sysctl $quiet -p
-              log_action_end_msg $?
-               ;;
-       stop)
-               ;;
-       *)
-               echo "Usage: /etc/init.d/procps {start|stop|restart|force-reload}" >&2
-               exit 3
-               ;;
-esac
-exit 0
-#! /bin/sh
-#
-# rc
-#
-# Starts/stops services on runlevel changes.
-#
-# Optimization: A start script is not run when the service was already
-# configured to run in the previous runlevel.  A stop script is not run
-# when the the service was already configured not to run in the previous
-# runlevel.
-#
-# Authors:
-#      Miquel van Smoorenburg <miquels@cistron.nl>
-#      Bruce Perens <Bruce@Pixar.com>
-
-PATH=/sbin:/bin:/usr/sbin:/usr/bin
-export PATH
-
-# Un-comment the following for debugging.
-# debug=echo
-
-# Specify method used to enable concurrent init.d scripts.
-# Valid options are 'none' and 'shell'.
-CONCURRENCY=none
 
-# Make sure the name survive changing the argument list
-scriptname="$0"
-
-umask 022
-
-#
-# Stub to do progress bar ticks (currently just for usplash) on startup
-#
-startup_progress() {
-    $@
-    step=$(($step + $step_change))
-    progress=$(($step * $progress_size / $num_steps + $first_step))
-    if type usplash_write >/dev/null 2>&1; then
-        usplash_write "PROGRESS $progress" || true
-    fi
-}
-
-#
-# Start script or program.
-#
-case "$CONCURRENCY" in
-  none)
-       startup() {
-               action=$1
-               shift
-               scripts="$@"
-               sh=sh
-               # Debian Policy Â§9.3.1 requires .sh scripts in runlevel S to be sourced
-               # However, some important packages currently contain .sh scripts
-               # that do "exit" at some point, thus killing this process.  Bad!
-               #[ S = "$runlevel" ] && sh=.
-               for script in $scripts ; do
-                       case "$script" in
-                         *.sh)
-                               if [ "." = "$sh" ] ; then
-                                       set "$action"
-                                       RC_SAVE_PATH="$PATH"
-                                       startup_progress $debug . "$script"
-                                       PATH="$RC_SAVE_PATH"
-                               else
-                                       startup_progress $debug $sh "$script" $action
-                               fi
-                               ;;
-                         *)
-                               startup_progress $debug "$script" $action
-                               ;;
-                       esac
-               done
-       }
-       ;;
-  shell)
-       startup() {
-               action=$1
-               shift
-               scripts="$@"
-               sh=sh
-               # Debian Policy Â§9.3.1 requires .sh scripts in runlevel S to be sourced
-               # However, some important packages currently contain .sh scripts
-               # that do "exit" at some point, thus killing this process.  Bad!
-               #[ S = "$runlevel" ] && sh=.
-               backgrounded=0
-               for script in $scripts ; do
-                       case "$script" in
-                         *.sh)
-                               if [ "." = "$sh" ] ; then
-                                       set "$action"
-                                       RC_SAVE_PATH="$PATH"
-                                       startup_progress $debug . "$script"
-                                       PATH="$RC_SAVE_PATH"
-                               else
-                                       startup_progress $debug $sh "$script" $action
-                               fi
-                               ;;
-                         *)
-                               startup_progress $debug "$script" $action &
-                               backgrounded=1
-                               ;;
-                       esac
-               done
-               [ 1 = "$backgrounded" ] && wait
-       }
-       ;;
-  startpar)
-       startup() {
-               action=$1
-               shift
-               scripts="$@"
-               sh=sh
-               # Debian Policy Â§9.3.1 requires .sh scripts in runlevel S to be sourced
-               # However, some important packages currently contain .sh scripts
-               # that do "exit" at some point, thus killing this process.  Bad!
-               #[ S = "$runlevel" ] && sh=.
-               # Make sure .sh scripts are sourced in runlevel S
-               if [ "." = "$sh" ] ; then
-                       newscripts=
-                       for script in $scripts ; do
-                               case "$script" in
-                                 *.sh)
-                                       set "$action"
-                                       RC_SAVE_PATH="$PATH"
-                                       startup_progress $debug . "$script"
-                                       PATH="$RC_SAVE_PATH"
-                                       ;;
-                                 *)
-                                       newscripts="$newscripts $script"
-                                       ;;
-                               esac
-                       done
-                       scripts="$newscripts"
-               fi
-
-               # startpar is not working as it should yet [pere 2005-09-10]
-               [ -n "$scripts" ] && startup_progress $debug startpar -a $action $scripts
-               startup_progress $debug startpar -a $action $scripts
-       }
-       ;;
-esac
-
-on_exit() {
-    echo "error: '$scriptname' exited outside the expected code flow."
-}
-trap on_exit EXIT # Enable emergency handler
-
-# Ignore CTRL-C only in this shell, so we can interrupt subprocesses.
-trap ":" INT QUIT TSTP
-
-# Should we also output to the console?
-# /proc won't be mounted if we don't have an initramfs, but then we're
-# dealing with custom systems so it's their own fault that they'll get
-# output from rcS ;)
-if grep -w -q quiet /proc/cmdline 2>/dev/null; then
-    QUIET=yes
-else
-    QUIET=no
-fi
-export QUIET
-
-# Set onlcr to avoid staircase effect.
-if [ "$QUIET" != yes ]; then
-    stty onlcr </dev/console >/dev/console 2>&1
-fi
-
-# Now find out what the current and what the previous runlevel are.
-runlevel=$RUNLEVEL
-
-# Get first argument. Set new runlevel to this argument.
-[ "$1" != "" ] && runlevel=$1
-if [ "$runlevel" = "" ]
-then
-       echo "Usage: $scriptname <runlevel>" >&2
-       exit 1
-fi
-previous=$PREVLEVEL
-[ "$previous" = "" ] && previous=N
-
-export runlevel previous
-
-if [ S = "$runlevel" ]
-then
-       #
-       # See if system needs to be setup. This is ONLY meant to
-       # be used for the initial setup after a fresh installation!
-       #
-       if [ -x /sbin/unconfigured.sh ]
-       then
-               /sbin/unconfigured.sh
-       fi
-fi
-
-. /etc/default/rcS
-export VERBOSE
-
-# Is there an rc directory for this new runlevel?
-if [ -d /etc/rc$runlevel.d ]
-then
-       # Split the progress bar into thirds
-       progress_size=$((100 / 3))
-
-       case "$runlevel" in
-               0|6)
-                       ACTION=stop
-                       # Count down from 0 to -100 and use the entire bar
-                       first_step=0
-                       progress_size=100
-                       step_change=-1
-                       ;;
-               S)
-                       ACTION=start
-                       # Use 2/3 of the space
-                       first_step=0
-                       progress_size=$(($progress_size * 2))
-                       step_change=1
-                       ;;
-               *)
-                       ACTION=start
-                       # Begin where rcS left off and use the final 1/3 of
-                       # the space (by leaving progress_size unchanged)
-                       first_step=$(($progress_size * 2))
-                       step_change=1
-                       ;;
-       esac
-
-       # Count the number of scripts we need to run (for usplash progress bar)
-       num_steps=0
-       for s in /etc/rc$runlevel.d/[SK]*; do
-            case "${s##/etc/rc$runlevel.d/S??}" in
-                gdm|xdm|kdm|ltsp-client-core|reboot|halt)
-                    break
-                    ;;
-            esac
-            num_steps=$(($num_steps + 1))
-        done
-
-        step=0
-
-       # First, run the KILL scripts.
-       if [ "$previous" != N ]
-       then
-               # Run all scripts with the same level in parallel
-               CURLEVEL=""
-               for s in /etc/rc$runlevel.d/K*
-               do
-                       level=$(echo $s | sed 's/.*\/K\([0-9][0-9]\).*/\1/')
-                       if [ "$level" = "$CURLEVEL" ]
-                       then
-                               continue
-                       fi
-                       CURLEVEL=$level
-                       SCRIPTS=""
-                       for i in /etc/rc$runlevel.d/K$level*
-                       do
-                               # Check if the script is there.
-                               [ ! -f $i ] && continue
-
-                               #
-                               # Find stop script in previous runlevel but
-                               # no start script there.
-                               #
-                               suffix=${i#/etc/rc$runlevel.d/K[0-9][0-9]}
-                               previous_stop=/etc/rc$previous.d/K[0-9][0-9]$suffix
-                               previous_start=/etc/rc$previous.d/S[0-9][0-9]$suffix
-                               #
-                               # If there is a stop script in the previous level
-                               # and _no_ start script there, we don't
-                               # have to re-stop the service.
-                               #
-                               [ -f $previous_stop ] && [ ! -f $previous_start ] && continue
-
-                               # Stop the service.
-                               SCRIPTS="$SCRIPTS $i"
-                       done
-                       startup stop $SCRIPTS
-               done
-       fi
-
-       # Now run the START scripts for this runlevel.
-       # Run all scripts with the same level in parallel
-       CURLEVEL=""
-       for s in /etc/rc$runlevel.d/S*
-       do
-               level=$(echo $s | sed 's/.*\/S\([0-9][0-9]\).*/\1/')
-               if [ "$level" = "$CURLEVEL" ]
-               then
-                       continue
-               fi
-               CURLEVEL=$level
-               SCRIPTS=""
-               for i in /etc/rc$runlevel.d/S$level*
-               do
-                       [ ! -f $i ] && continue
-
-                       if [ "$previous" != N ]
-                       then
-                               #
-                               # Find start script in previous runlevel and
-                               # stop script in this runlevel.
-                               #
-                               suffix=${i#/etc/rc$runlevel.d/S[0-9][0-9]}
-                               stop=/etc/rc$runlevel.d/K[0-9][0-9]$suffix
-                               previous_start=/etc/rc$previous.d/S[0-9][0-9]$suffix
-                               #
-                               # If there is a start script in the previous level
-                               # and _no_ stop script in this level, we don't
-                               # have to re-start the service.
-                               #
-                               [ -f $previous_start ] && [ ! -f $stop ] && continue
-                       fi
-                       SCRIPTS="$SCRIPTS $i"
-               done
-               startup $ACTION $SCRIPTS
-       done
-fi
-
-if [ S = "$runlevel" ]
-then
-       #
-       # For compatibility, run the files in /etc/rc.boot too.
-       #
-       [ -d /etc/rc.boot ] && run-parts /etc/rc.boot
-
-       #
-       # Finish setup if needed. The comment above about
-       # /sbin/unconfigured.sh applies here as well!
-       #
-       if [ -x /sbin/setup.sh ]
-       then
-               /sbin/setup.sh
-       fi
-fi
-
-trap - EXIT # Disable emergency handler
-
-exit 0
-
-#! /bin/sh
-
-PATH=/sbin:/bin:/usr/sbin:/usr/bin
-[ -f /etc/default/rcS ] && . /etc/default/rcS
-. /lib/lsb/init-functions
-
-do_start() {
-       if [ -x /etc/rc.local ]; then
-               log_begin_msg "Running local boot scripts (/etc/rc.local)"
-               /etc/rc.local
-               log_end_msg $?
-       fi
-}
-
-case "$1" in
-    start)
-       do_start
-        ;;
-    restart|reload|force-reload)
-        echo "Error: argument '$1' not supported" >&2
-        exit 3
-        ;;
-    stop)
-        ;;
-    *)
-        echo "Usage: $0 start|stop" >&2
-        exit 3
-        ;;
-esac
-#! /bin/sh
-#
-# rcS
-#
-# Call all S??* scripts in /etc/rcS.d/ in numerical/alphabetical order
-#
-
-exec /etc/init.d/rc S
-       Configuration of System V init under Debian GNU/Linux
-
-Most Unix versions have a file here that describes how the scripts
-in this directory work, and how the links in the /etc/rc?.d/ directories
-influence system startup/shutdown.
-
-For Debian, this information is contained in the policy manual, chapter 
-"System run levels and init.d scripts".  The Debian Policy Manual is 
-available at:
-
-    http://www.debian.org/doc/debian-policy/#contents
-
-The Debian Policy Manual is also available in the Debian package
-"debian-policy".  When this package is installed, the policy manual can be
-found in directory /usr/share/doc/debian-policy. If you have a browser
-installed you can probably read it at
-
-    file://localhost/usr/share/doc/debian-policy/
-
-Some more detailed information can also be found in the files in the
-/usr/share/doc/sysv-rc directory.
-
-Debian Policy dictates that /etc/init.d/*.sh scripts must work properly
-when sourced.  The following additional rules apply:
-
-* /etc/init.d/*.sh scripts may not rely for their correct functioning
-  on their being sourced rather than executed.  That is, they must work
-  properly when executed too. They must include "#!/bin/sh" at the top.
-
-* /etc/init.d/*.sh scripts must conform to the rules for sh scripts as
-  spelled out in the Debian policy section entitled "Scripts" (§10.4).
-
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          reboot
-# Required-Start:    umountroot $network
-# Required-Stop:
-# Should-Start:      lvm raid2
-# Default-Start:     6
-# Default-Stop:
-# Short-Description: Execute the reboot command.
-# Description:
-### END INIT INFO
-
-PATH=/usr/sbin:/usr/bin:/sbin:/bin
-
-. /lib/lsb/init-functions
-
-do_stop () {
-       # Message should end with a newline since kFreeBSD may
-       # print more stuff (see #323749)
-       log_action_msg "Will now restart"
-       reboot -d -f -i
-}
-
-case "$1" in
-  start)
-       # No-op
-       ;;
-  restart|reload|force-reload)
-       echo "Error: argument '$1' not supported" >&2
-       exit 3
-       ;;
-  stop)
-       do_stop
-       ;;
-  *)
-       echo "Usage: $0 start|stop" >&2
-       exit 3
-       ;;
-esac
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          rmnologin
-# Required-Start:    $local_fs $remote_fs
-# Required-Stop: 
-# Should-Start:      kdm xdm gdm $syslog
-# Default-Start:     0 1 2 3 4 5 6
-# Default-Stop:       
-# Short-Description: Remove /etc/nologin at boot
-# Description:       This script removes the /etc/nologin file as the
-#                    last step in the boot process, if DELAYLOGIN=yes.
-#                    If DELAYLOGIN=no, /etc/nologin was not created by
-#                    bootmisc earlier in the boot process.
-### END INIT INFO
-
-PATH=/sbin:/bin
-[ "$DELAYLOGIN" ] || DELAYLOGIN=yes
-. /lib/init/vars.sh
-
-do_start () {
-       #
-       # If login delaying is enabled then remove the flag file
-       #
-       case "$DELAYLOGIN" in
-         Y*|y*)
-               rm -f /var/lib/initscripts/nologin
-               ;;
-       esac
-}
-
-case "$1" in
-  start)
-       do_start
-       ;;
-  restart|reload|force-reload)
-       echo "Error: argument '$1' not supported" >&2
-       exit 3
-       ;;
-  stop)
-       # No-op
-       ;;
-  *)
-       echo "Usage: $0 start|stop" >&2
-       exit 3
-       ;;
-esac
-
-:
-#! /bin/sh
-
-### BEGIN INIT INFO
-# Provides:          rsyncd
-# Required-Start:    $network
-# Required-Stop:     $syslog
-# Should-Start:      $named $syslog
-# Should-Stop:       $syslog network
-# Default-Start:     2 3 4 5
-# Default-Stop:      0 1 6
-# Short-Description: fast remote file copy program daemon
-# Description:       rsync is a program that allows files to be copied to and
-#                    from remote machines in much the same way as rcp.
-#                    This provides rsyncd daemon functionality.
-### END INIT INFO
-
-set -e
-
-# /etc/init.d/rsync: start and stop the rsync daemon
-
-DAEMON=/usr/bin/rsync
-RSYNC_ENABLE=false
-RSYNC_OPTS=''
-RSYNC_DEFAULTS_FILE=/etc/default/rsync
-RSYNC_CONFIG_FILE=/etc/rsyncd.conf
-RSYNC_NICE_PARM=''
-
-test -x $DAEMON || exit 0
-
-. /lib/lsb/init-functions
-. /etc/default/rcS
-
-if [ -s $RSYNC_DEFAULTS_FILE ]; then
-    . $RSYNC_DEFAULTS_FILE
-    case "x$RSYNC_ENABLE" in
-        xtrue|xfalse)   ;;
-        xinetd)         exit 0
-                        ;;
-        *)              log_failure_msg "Value of RSYNC_ENABLE in $RSYNC_DEFAULTS_FILE must be either 'true' or 'false';"
-                        log_failure_msg "not starting rsync daemon."
-                        exit 1
-                        ;;
-    esac
-    case "x$RSYNC_NICE" in
-        x[0-9])         RSYNC_NICE_PARM="--nicelevel $RSYNC_NICE";;
-        x[1-9][0-9])    RSYNC_NICE_PARM="--nicelevel $RSYNC_NICE";;
-        x)              ;;
-        *)              log_warning_msg "Value of RSYNC_NICE in $RSYNC_DEFAULTS_FILE must be a value between 0 and 19 (inclusive);"
-                        log_warning_msg "ignoring RSYNC_NICE now."
-                        ;;
-    esac
-fi
-
-export PATH="${PATH:+$PATH:}/usr/sbin:/sbin"
-
-case "$1" in
-  start)
-       if "$RSYNC_ENABLE"; then
-            log_daemon_msg "Starting rsync daemon" "rsync"
-           if [ -s /var/run/rsync.pid ] && kill -0 $(cat /var/run/rsync.pid) >/dev/null 2>&1; then
-                log_progress_msg "apparently already running"
-                log_end_msg 0
-               exit 0
-           fi
-            if [ ! -s "$RSYNC_CONFIG_FILE" ]; then
-                log_failure_msg "missing or empty config file $RSYNC_CONFIG_FILE"
-               log_end_msg 1
-                exit 1
-            fi
-            if start-stop-daemon --start --quiet --background \
-                --pidfile /var/run/rsync.pid --make-pidfile \
-                $RSYNC_NICE_PARM --exec /usr/bin/rsync \
-                -- --no-detach --daemon --config "$RSYNC_CONFIG_FILE" $RSYNC_OPTS
-            then
-                rc=0
-                sleep 1
-                if ! kill -0 $(cat /var/run/rsync.pid) >/dev/null 2>&1; then
-                    log_failure_msg "rsync daemon failed to start"
-                    rc=1
-                fi
-            else
-                rc=1
-            fi
-            if [ $rc -eq 0 ]; then
-                log_end_msg 0
-            else
-                log_end_msg 1
-                rm -f /var/run/rsync.pid
-            fi
-        else
-            if [ -s "$RSYNC_CONFIG_FILE" ]; then
-               [ "$VERBOSE" != no ] && log_warning_msg "rsync daemon not enabled in /etc/default/rsync, not starting..."
-            fi
-        fi
-       ;;
-  stop)
-        log_daemon_msg "Stopping rsync daemon" "rsync"
-       start-stop-daemon --stop --quiet --oknodo --pidfile /var/run/rsync.pid
-        log_end_msg $?
-       rm -f /var/run/rsync.pid
-       ;;
-
-  reload|force-reload)
-        log_warning_msg "Reloading rsync daemon: not needed, as the daemon"
-        log_warning_msg "re-reads the config file whenever a client connects."
-       ;;
-
-  restart)
-       set +e
-        if $RSYNC_ENABLE; then
-            log_daemon_msg "Restarting rsync daemon" "rsync"
-           if [ -s /var/run/rsync.pid ] && kill -0 $(cat /var/run/rsync.pid) >/dev/null 2>&1; then
-               start-stop-daemon --stop --quiet --oknodo --pidfile /var/run/rsync.pid || true
-               sleep 1
-           else
-                log_warning_msg "rsync daemon not running, attempting to start."
-               rm -f /var/run/rsync.pid
-           fi
-            if start-stop-daemon --start --quiet --background \
-                --pidfile /var/run/rsync.pid --make-pidfile \
-                $RSYNC_NICE_PARM --exec /usr/bin/rsync \
-                -- --no-detach --daemon --config "$RSYNC_CONFIG_FILE" $RSYNC_OPTS
-            then
-                rc=0
-                sleep 1
-                if ! kill -0 $(cat /var/run/rsync.pid) >/dev/null 2>&1; then
-                    log_failure_msg "rsync daemon failed to start"
-                    rc=1
-                fi
-            else
-                rc=1
-            fi
-            if [ $rc -eq 0 ]; then
-                log_end_msg 0
-            else
-                log_end_msg 1
-                rm -f /var/run/rsync.pid
-            fi
-        else
-            [ "$VERBOSE" != no ] && log_warning_msg "rsync daemon not enabled in /etc/default/rsync, not starting..."
-        fi
-       ;;
-
-  *)
-       echo "Usage: /etc/init.d/rsync {start|stop|reload|force-reload|restart}"
-       exit 1
-esac
-
-exit 0
-#!/bin/sh
-
-### BEGIN INIT INFO
-# Provides:          samba
-# Required-Start:    $network $local_fs $remote_fs
-# Required-Stop:     $network $local_fs $remote_fs
-# Default-Start:     2 3 4 5
-# Default-Stop:      0 1 6
-# Short-Description: start Samba daemons (nmbd and smbd)
-### END INIT INFO
-
-
-# Defaults
-RUN_MODE="daemons"
-
-# Reads config file (will override defaults above)
-[ -r /etc/default/samba ] && . /etc/default/samba
-
-DAEMON=/usr/sbin/smbd
-PIDDIR=/var/run/samba
-NMBDPID=$PIDDIR/nmbd.pid
-SMBDPID=$PIDDIR/smbd.pid
-
-# clear conflicting settings from the environment
-unset TMPDIR
-
-# See if the daemons are there
-test -x /usr/sbin/nmbd -a -x /usr/sbin/smbd || exit 0
-
-. /lib/lsb/init-functions
-
-case "$1" in
-       start)
-               log_daemon_msg "Starting Samba daemons"
-               # Make sure we have our PIDDIR, even if it's on a tmpfs
-               install -o root -g root -m 755 -d $PIDDIR
-
-               NMBD_DISABLED=`testparm -s --parameter-name='disable netbios' 2>/dev/null`
-               if [ "$NMBD_DISABLED" != 'Yes' ]; then
-                       log_progress_msg "nmbd"
-                       if ! start-stop-daemon --start --quiet --oknodo --exec /usr/sbin/nmbd -- -D
-                       then
-                               log_end_msg 1
-                               exit 1
-                       fi
-               fi
-
-               if [ "$RUN_MODE" != "inetd" ]; then
-                       log_progress_msg "smbd"
-                       if ! start-stop-daemon --start --quiet --oknodo --exec /usr/sbin/smbd -- -D; then
-                               log_end_msg 1
-                               exit 1
-                       fi
-               fi
-
-               log_end_msg 0
-               ;;
-       stop)
-               log_daemon_msg "Stopping Samba daemons"
-               log_progress_msg "nmbd"
-
-               start-stop-daemon --stop --quiet --pidfile $NMBDPID
-               # Wait a little and remove stale PID file
-               sleep 1
-               if [ -f $NMBDPID ] && ! ps h `cat $NMBDPID` > /dev/null
-               then
-                       # Stale PID file (nmbd was succesfully stopped),
-                       # remove it (should be removed by nmbd itself IMHO.)
-                       rm -f $NMBDPID
-               fi
-
-               if [ "$RUN_MODE" != "inetd" ]; then
-                       log_progress_msg "smbd"
-                       start-stop-daemon --stop --quiet --pidfile $SMBDPID
-                       # Wait a little and remove stale PID file
-                       sleep 1
-                       if [ -f $SMBDPID ] && ! ps h `cat $SMBDPID` > /dev/null
-                       then
-                               # Stale PID file (nmbd was succesfully stopped),
-                               # remove it (should be removed by smbd itself IMHO.)
-                               rm -f $SMBDPID
-                       fi
-               fi
-
-               log_end_msg 0
-
-               ;;
-       reload)
-               log_daemon_msg "Reloading /etc/samba/smb.conf" "smbd only"
-
-               start-stop-daemon --stop --signal HUP --pidfile $SMBDPID
-
-               log_end_msg 0
-               ;;
-       restart|force-reload)
-               $0 stop
-               sleep 1
-               $0 start
-               ;;
-       status)
-               pidofproc -p $SMBDPID $DAEMON >/dev/null
-               status=$?
-               if [ $status -eq 0 ]; then
-                       log_success_msg "SMBD is running"
-               else
-                       log_failure_msg "SMBD is not running"
-               fi
-               exit $status
-               ;;
-       *)
-               echo "Usage: /etc/init.d/samba {start|stop|reload|restart|force-reload|status}"
-               exit 1
-               ;;
-esac
-
-exit 0
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          sendsigs
-# Required-Start:    
-# Required-Stop: 
-# Default-Start:     6
-# Default-Stop:       
-# Short-Description: Kill all remaining processes.
-# Description: 
-### END INIT INFO
-
-PATH=/usr/sbin:/usr/bin:/sbin:/bin
-
-. /lib/lsb/init-functions
-
-do_stop () {
-       OMITPIDS=
-       if [ -e /var/run/sendsigs.omit ]; then
-               for pid in $(cat /var/run/sendsigs.omit); do
-                       OMITPIDS="${OMITPIDS:+$OMITPIDS }-o $pid"
-               done
-       fi
-
-       if [ -d /var/run/sendsigs.omit.d/ ]; then
-               for pidfile in /var/run/sendsigs.omit.d/*; do
-                       [ -f "$pidfile" ] || continue
-                       for pid in $(cat $pidfile); do
-                               OMITPIDS="${OMITPIDS:+$OMITPIDS }-o $pid"
-                       done
-               done
-       fi
-
-       # Kill all processes.
-       log_action_begin_msg "Terminating all remaining processes"
-       killall5 -15 $OMITPIDS
-       log_action_end_msg 0
-       sleep 5
-       log_action_begin_msg "Sending all processes the KILL signal"
-       killall5 -9 $OMITPIDS
-       log_action_end_msg 0
-}
-
-case "$1" in
-  start)
-       # No-op
-       ;;
-  restart|reload|force-reload)
-       echo "Error: argument '$1' not supported" >&2
-       exit 3
-       ;;
-  stop)
-       do_stop
-       if which usplash_down >/dev/null; then
-               usplash_down
-       fi
-       ;;
-  *)
-       echo "Usage: $0 start|stop" >&2
-       exit 3
-       ;;
-esac
-
-:
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          single
-# Required-Start:    $local_fs killprocs
-# Required-Stop:
-# Default-Start:     1
-# Default-Stop:
-# Short-Description: executed by init(8) upon entering runlevel 1 (single).
-### END INIT INFO
-
-PATH=/sbin:/bin
-
-. /lib/lsb/init-functions
-
-do_start () {
-       log_action_msg "Will now switch to single-user mode"
-       exec init -t1 S
-}
-
-case "$1" in
-  start)
-       do_start
-       ;;
-  restart|reload|force-reload)
-       echo "Error: argument '$1' not supported" >&2
-       exit 3
-       ;;
-  stop)
-       # No-op
-       ;;
-  *)
-       echo "Usage: $0 start|stop" >&2
-       exit 3
-       ;;
-esac
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          skeleton
-# Required-Start:    $local_fs $remote_fs
-# Required-Stop:     $local_fs $remote_fs
-# Default-Start:     2 3 4 5
-# Default-Stop:      S 0 1 6
-# Short-Description: Example initscript
-# Description:       This file should be used to construct scripts to be
-#                    placed in /etc/init.d.
-### END INIT INFO
-
-# Author: Foo Bar <foobar@baz.org>
-#
-# Please remove the "Author" lines above and replace them
-# with your own name if you copy and modify this script.
-
-# Do NOT "set -e"
-
-# PATH should only include /usr/* if it runs after the mountnfs.sh script
-PATH=/usr/sbin:/usr/bin:/sbin:/bin
-DESC="Description of the service"
-NAME=daemonexecutablename
-DAEMON=/usr/sbin/$NAME
-DAEMON_ARGS="--options args"
-PIDFILE=/var/run/$NAME.pid
-SCRIPTNAME=/etc/init.d/$NAME
-
-# Exit if the package is not installed
-[ -x "$DAEMON" ] || exit 0
-
-# Read configuration variable file if it is present
-[ -r /etc/default/$NAME ] && . /etc/default/$NAME
-
-# Load the VERBOSE setting and other rcS variables
-[ -f /etc/default/rcS ] && . /etc/default/rcS
-
-# Define LSB log_* functions.
-# Depend on lsb-base (>= 3.0-6) to ensure that this file is present.
-. /lib/lsb/init-functions
-
-#
-# Function that starts the daemon/service
-#
-do_start()
-{
-       # Return
-       #   0 if daemon has been started
-       #   1 if daemon was already running
-       #   2 if daemon could not be started
-       start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON --test > /dev/null \
-               || return 1
-       start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON -- \
-               $DAEMON_ARGS \
-               || return 2
-       # Add code here, if necessary, that waits for the process to be ready
-       # to handle requests from services started subsequently which depend
-       # on this one.  As a last resort, sleep for some time.
-}
+class BupFs(fuse.Fuse):
+    def __init__(self, top):
+        fuse.Fuse.__init__(self)
+        self.top = top
+    
+    def getattr(self, path):
+        log('--getattr(%r)\n' % path)
+        try:
+            node = cache_get(self.top, path)
+            st = Stat()
+            st.st_mode = node.mode
+            st.st_nlink = node.nlinks()
+            st.st_size = node.size()
+            st.st_mtime = node.mtime
+            st.st_ctime = node.ctime
+            st.st_atime = node.atime
+            return st
+        except vfs.NoSuchFile:
+            return -errno.ENOENT
+
+    def readdir(self, path, offset):
+        log('--readdir(%r)\n' % path)
+        node = cache_get(self.top, path)
+        yield fuse.Direntry('.')
+        yield fuse.Direntry('..')
+        for sub in node.subs():
+            yield fuse.Direntry(sub.name)
+
+    def readlink(self, path):
+        log('--readlink(%r)\n' % path)
+        node = cache_get(self.top, path)
+        return node.readlink()
+
+    def open(self, path, flags):
+        log('--open(%r)\n' % path)
+        node = cache_get(self.top, path)
+        accmode = os.O_RDONLY | os.O_WRONLY | os.O_RDWR
+        if (flags & accmode) != os.O_RDONLY:
+            return -errno.EACCES
+        node.open()
+
+    def release(self, path, flags):
+        log('--release(%r)\n' % path)
+
+    def read(self, path, size, offset):
+        log('--read(%r)\n' % path)
+        n = cache_get(self.top, path)
+        o = n.open()
+        o.seek(offset)
+        return o.read(size)
+
+
+if not hasattr(fuse, '__version__'):
+    raise RuntimeError, "your fuse module is too old for fuse.__version__"
+fuse.fuse_python_api = (0, 2)
+
+
+optspec = """
+bup fuse [-d] [-f] <mountpoint>
+--
+d,debug   increase debug level
+f,foreground  run in foreground
+"""
+o = options.Options('bup fuse', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if len(extra) != 1:
+    o.fatal("exactly one argument expected")
+
+git.check_repo_or_die()
+top = vfs.RefList(None)
+f = BupFs(top)
+f.fuse_args.mountpoint = extra[0]
+if opt.debug:
+    f.fuse_args.add('debug')
+if opt.foreground:
+    f.fuse_args.setmod('foreground')
+print f.multithreaded
+f.multithreaded = False
+
+f.main()
+#!/usr/bin/env python
+from bup import git, options, client
+from bup.helpers import *
+
+optspec = """
+[BUP_DIR=...] bup init [-r host:path]
+--
+r,remote=  remote repository path
+"""
+o = options.Options('bup init', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if extra:
+    o.fatal("no arguments expected")
+
+
+if opt.remote:
+    git.init_repo()  # local repo
+    git.check_repo_or_die()
+    cli = client.Client(opt.remote, create=True)
+    cli.close()
+else:
+    git.init_repo()
+#!/usr/bin/env python
+import sys, math, struct, glob
+from bup import options, git
+from bup.helpers import *
+
+PAGE_SIZE=4096
+SHA_PER_PAGE=PAGE_SIZE/200.
+
+
+def merge(idxlist, bits, table):
+    count = 0
+    for e in git.idxmerge(idxlist):
+        count += 1
+        prefix = git.extract_bits(e, bits)
+        table[prefix] = count
+        yield e
+
+
+def do_midx(outdir, outfilename, infilenames):
+    if not outfilename:
+        assert(outdir)
+        sum = Sha1('\0'.join(infilenames)).hexdigest()
+        outfilename = '%s/midx-%s.midx' % (outdir, sum)
+    
+    inp = []
+    total = 0
+    for name in infilenames:
+        ix = git.PackIdx(name)
+        inp.append(ix)
+        total += len(ix)
+
+    log('Merging %d indexes (%d objects).\n' % (len(infilenames), total))
+    if (not opt.force and (total < 1024 and len(infilenames) < 3)) \
+       or (opt.force and not total):
+        log('midx: nothing to do.\n')
+        return
+
+    pages = int(total/SHA_PER_PAGE) or 1
+    bits = int(math.ceil(math.log(pages, 2)))
+    entries = 2**bits
+    log('Table size: %d (%d bits)\n' % (entries*4, bits))
+    
+    table = [0]*entries
+
+    try:
+        os.unlink(outfilename)
+    except OSError:
+        pass
+    f = open(outfilename + '.tmp', 'w+')
+    f.write('MIDX\0\0\0\2')
+    f.write(struct.pack('!I', bits))
+    assert(f.tell() == 12)
+    f.write('\0'*4*entries)
+    
+    for e in merge(inp, bits, table):
+        f.write(e)
+        
+    f.write('\0'.join(os.path.basename(p) for p in infilenames))
+
+    f.seek(12)
+    f.write(struct.pack('!%dI' % entries, *table))
+    f.close()
+    os.rename(outfilename + '.tmp', outfilename)
+
+    # this is just for testing
+    if 0:
+        p = git.PackMidx(outfilename)
+        assert(len(p.idxnames) == len(infilenames))
+        print p.idxnames
+        assert(len(p) == total)
+        pi = iter(p)
+        for i in merge(inp, total, bits, table):
+            assert(i == pi.next())
+            assert(p.exists(i))
+
+    print outfilename
+
+optspec = """
+bup midx [options...] <idxnames...>
+--
+o,output=  output midx filename (default: auto-generated)
+a,auto     automatically create .midx from any unindexed .idx files
+f,force    automatically create .midx from *all* .idx files
+"""
+o = options.Options('bup midx', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if extra and (opt.auto or opt.force):
+    o.fatal("you can't use -f/-a and also provide filenames")
+
+git.check_repo_or_die()
+
+if extra:
+    do_midx(git.repo('objects/pack'), opt.output, extra)
+elif opt.auto or opt.force:
+    paths = [git.repo('objects/pack')]
+    paths += glob.glob(git.repo('index-cache/*/.'))
+    for path in paths:
+        log('midx: scanning %s\n' % path)
+        if opt.force:
+            do_midx(path, opt.output, glob.glob('%s/*.idx' % path))
+        elif opt.auto:
+            m = git.PackIdxList(path)
+            needed = {}
+            for pack in m.packs:  # only .idx files without a .midx are open
+                if pack.name.endswith('.idx'):
+                    needed[pack.name] = 1
+            del m
+            do_midx(path, opt.output, needed.keys())
+        log('\n')
+else:
+    o.fatal("you must use -f or -a or provide input filenames")
+#!/usr/bin/env python
+import sys, os, random
+from bup import options
+from bup.helpers import *
+
+
+def randblock(n):
+    l = []
+    for i in xrange(n):
+        l.append(chr(random.randrange(0,256)))
+    return ''.join(l)
+
+
+optspec = """
+bup damage [-n count] [-s maxsize] [-S seed] <filenames...>
+--
+   WARNING: THIS COMMAND IS EXTREMELY DANGEROUS
+n,num=   number of blocks to damage
+s,size=  maximum size of each damaged block
+percent= maximum size of each damaged block (as a percent of entire file)
+equal    spread damage evenly throughout the file
+S,seed=  random number seed (for repeatable tests)
+"""
+o = options.Options('bup damage', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if not extra:
+    o.fatal('filenames expected')
+
+if opt.seed != None:
+    random.seed(opt.seed)
+
+for name in extra:
+    log('Damaging "%s"...\n' % name)
+    f = open(name, 'r+b')
+    st = os.fstat(f.fileno())
+    size = st.st_size
+    if opt.percent or opt.size:
+        ms1 = int(float(opt.percent or 0)/100.0*size) or size
+        ms2 = opt.size or size
+        maxsize = min(ms1, ms2)
+    else:
+        maxsize = 1
+    chunks = opt.num or 10
+    chunksize = size/chunks
+    for r in range(chunks):
+        sz = random.randrange(1, maxsize+1)
+        if sz > size:
+            sz = size
+        if opt.equal:
+            ofs = r*chunksize
+        else:
+            ofs = random.randrange(0, size - sz + 1)
+        log('  %6d bytes at %d\n' % (sz, ofs))
+        f.seek(ofs)
+        f.write(randblock(sz))
+    f.close()
+#!/usr/bin/env python
+import sys, struct, mmap
+from bup import options, git
+from bup.helpers import *
+
+suspended_w = None
+
+
+def init_dir(conn, arg):
+    git.init_repo(arg)
+    log('bup server: bupdir initialized: %r\n' % git.repodir)
+    conn.ok()
+
+
+def set_dir(conn, arg):
+    git.check_repo_or_die(arg)
+    log('bup server: bupdir is %r\n' % git.repodir)
+    conn.ok()
 
-#
-# Function that stops the daemon/service
-#
-do_stop()
-{
-       # Return
-       #   0 if daemon has been stopped
-       #   1 if daemon was already stopped
-       #   2 if daemon could not be stopped
-       #   other if a failure occurred
-       start-stop-daemon --stop --quiet --retry=TERM/30/KILL/5 --pidfile $PIDFILE --name $NAME
-       RETVAL="$?"
-       [ "$RETVAL" = 2 ] && return 2
-       # Wait for children to finish too if this is a daemon that forks
-       # and if the daemon is only ever run from this initscript.
-       # If the above conditions are not satisfied then add some other code
-       # that waits for the process to drop all resources that could be
-       # needed by services started subsequently.  A last resort is to
-       # sleep for some time.
-       start-stop-daemon --stop --quiet --oknodo --retry=0/30/KILL/5 --exec $DAEMON
-       [ "$?" = 2 ] && return 2
-       # Many daemons don't delete their pidfiles when they exit.
-       rm -f $PIDFILE
-       return "$RETVAL"
+    
+def list_indexes(conn, junk):
+    git.check_repo_or_die()
+    for f in os.listdir(git.repo('objects/pack')):
+        if f.endswith('.idx'):
+            conn.write('%s\n' % f)
+    conn.ok()
+
+
+def send_index(conn, name):
+    git.check_repo_or_die()
+    assert(name.find('/') < 0)
+    assert(name.endswith('.idx'))
+    idx = git.PackIdx(git.repo('objects/pack/%s' % name))
+    conn.write(struct.pack('!I', len(idx.map)))
+    conn.write(idx.map)
+    conn.ok()
+
+
+def receive_objects(conn, junk):
+    global suspended_w
+    git.check_repo_or_die()
+    suggested = {}
+    if suspended_w:
+        w = suspended_w
+        suspended_w = None
+    else:
+        w = git.PackWriter()
+    while 1:
+        ns = conn.read(4)
+        if not ns:
+            w.abort()
+            raise Exception('object read: expected length header, got EOF\n')
+        n = struct.unpack('!I', ns)[0]
+        #log('expecting %d bytes\n' % n)
+        if not n:
+            log('bup server: received %d object%s.\n' 
+                % (w.count, w.count!=1 and "s" or ''))
+            fullpath = w.close()
+            if fullpath:
+                (dir, name) = os.path.split(fullpath)
+                conn.write('%s.idx\n' % name)
+            conn.ok()
+            return
+        elif n == 0xffffffff:
+            log('bup server: receive-objects suspended.\n')
+            suspended_w = w
+            conn.ok()
+            return
+            
+        buf = conn.read(n)  # object sizes in bup are reasonably small
+        #log('read %d bytes\n' % n)
+        if len(buf) < n:
+            w.abort()
+            raise Exception('object read: expected %d bytes, got %d\n'
+                            % (n, len(buf)))
+        (type, content) = git._decode_packobj(buf)
+        sha = git.calc_hash(type, content)
+        oldpack = w.exists(sha)
+        # FIXME: we only suggest a single index per cycle, because the client
+        # is currently dumb to download more than one per cycle anyway.
+        # Actually we should fix the client, but this is a minor optimization
+        # on the server side.
+        if not suggested and \
+          oldpack and (oldpack == True or oldpack.endswith('.midx')):
+            # FIXME: we shouldn't really have to know about midx files
+            # at this layer.  But exists() on a midx doesn't return the
+            # packname (since it doesn't know)... probably we should just
+            # fix that deficiency of midx files eventually, although it'll
+            # make the files bigger.  This method is certainly not very
+            # efficient.
+            w.objcache.refresh(skip_midx = True)
+            oldpack = w.objcache.exists(sha)
+            log('new suggestion: %r\n' % oldpack)
+            assert(oldpack)
+            assert(oldpack != True)
+            assert(not oldpack.endswith('.midx'))
+            w.objcache.refresh(skip_midx = False)
+        if not suggested and oldpack:
+            assert(oldpack.endswith('.idx'))
+            (dir,name) = os.path.split(oldpack)
+            if not (name in suggested):
+                log("bup server: suggesting index %s\n" % name)
+                conn.write('index %s\n' % name)
+                suggested[name] = 1
+        else:
+            w._raw_write([buf])
+    # NOTREACHED
+
+
+def read_ref(conn, refname):
+    git.check_repo_or_die()
+    r = git.read_ref(refname)
+    conn.write('%s\n' % (r or '').encode('hex'))
+    conn.ok()
+
+
+def update_ref(conn, refname):
+    git.check_repo_or_die()
+    newval = conn.readline().strip()
+    oldval = conn.readline().strip()
+    git.update_ref(refname, newval.decode('hex'), oldval.decode('hex'))
+    conn.ok()
+
+
+def cat(conn, id):
+    git.check_repo_or_die()
+    try:
+        for blob in git.cat(id):
+            conn.write(struct.pack('!I', len(blob)))
+            conn.write(blob)
+    except KeyError, e:
+        log('server: error: %s\n' % e)
+        conn.write('\0\0\0\0')
+        conn.error(e)
+    else:
+        conn.write('\0\0\0\0')
+        conn.ok()
+
+
+optspec = """
+bup server
+"""
+o = options.Options('bup server', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if extra:
+    o.fatal('no arguments expected')
+
+log('bup server: reading from stdin.\n')
+
+commands = {
+    'init-dir': init_dir,
+    'set-dir': set_dir,
+    'list-indexes': list_indexes,
+    'send-index': send_index,
+    'receive-objects': receive_objects,
+    'read-ref': read_ref,
+    'update-ref': update_ref,
+    'cat': cat,
 }
 
+# FIXME: this protocol is totally lame and not at all future-proof.
+# (Especially since we abort completely as soon as *anything* bad happens)
+conn = Conn(sys.stdin, sys.stdout)
+lr = linereader(conn)
+for _line in lr:
+    line = _line.strip()
+    if not line:
+        continue
+    log('bup server: command: %r\n' % line)
+    words = line.split(' ', 1)
+    cmd = words[0]
+    rest = len(words)>1 and words[1] or ''
+    if cmd == 'quit':
+        break
+    else:
+        cmd = commands.get(cmd)
+        if cmd:
+            cmd(conn, rest)
+        else:
+            raise Exception('unknown server command: %r\n' % line)
+
+log('bup server: done\n')
+#!/usr/bin/env python
+import sys, time, struct
+from bup import hashsplit, git, options, client
+from bup.helpers import *
+from subprocess import PIPE
+
+
+optspec = """
+bup join [-r host:path] [refs or hashes...]
+--
+r,remote=  remote repository path
+"""
+o = options.Options('bup join', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+git.check_repo_or_die()
+
+if not extra:
+    extra = linereader(sys.stdin)
+
+ret = 0
+
+if opt.remote:
+    cli = client.Client(opt.remote)
+    cat = cli.cat
+else:
+    cp = git.CatPipe()
+    cat = cp.join
+
+for id in extra:
+    try:
+        for blob in cat(id):
+            sys.stdout.write(blob)
+    except KeyError, e:
+        sys.stdout.flush()
+        log('error: %s\n' % e)
+        ret = 1
+
+sys.exit(ret)
+#!/usr/bin/env python
+import sys, re, errno, stat, time, math
+from bup import hashsplit, git, options, index, client
+from bup.helpers import *
+
+
+optspec = """
+bup save [-tc] [-n name] <filenames...>
+--
+r,remote=  remote repository path
+t,tree     output a tree id
+c,commit   output a commit id
+n,name=    name of backup set to update (if any)
+v,verbose  increase log output (can be used more than once)
+q,quiet    don't show progress meter
+smaller=   only back up files smaller than n bytes
+"""
+o = options.Options('bup save', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+git.check_repo_or_die()
+if not (opt.tree or opt.commit or opt.name):
+    o.fatal("use one or more of -t, -c, -n")
+if not extra:
+    o.fatal("no filenames given")
+
+opt.progress = (istty and not opt.quiet)
+opt.smaller = parse_num(opt.smaller or 0)
+
+is_reverse = os.environ.get('BUP_SERVER_REVERSE')
+if is_reverse and opt.remote:
+    o.fatal("don't use -r in reverse mode; it's automatic")
+
+refname = opt.name and 'refs/heads/%s' % opt.name or None
+if opt.remote or is_reverse:
+    cli = client.Client(opt.remote)
+    oldref = refname and cli.read_ref(refname) or None
+    w = cli.new_packwriter()
+else:
+    cli = None
+    oldref = refname and git.read_ref(refname) or None
+    w = git.PackWriter()
+
+handle_ctrl_c()
+
+
+def eatslash(dir):
+    if dir.endswith('/'):
+        return dir[:-1]
+    else:
+        return dir
+
+
+parts = ['']
+shalists = [[]]
+
+def _push(part):
+    assert(part)
+    parts.append(part)
+    shalists.append([])
+
+def _pop(force_tree):
+    assert(len(parts) >= 1)
+    part = parts.pop()
+    shalist = shalists.pop()
+    tree = force_tree or w.new_tree(shalist)
+    if shalists:
+        shalists[-1].append(('40000', part, tree))
+    else:  # this was the toplevel, so put it back for sanity
+        shalists.append(shalist)
+    return tree
+
+lastremain = None
+def progress_report(n):
+    global count, subcount, lastremain
+    subcount += n
+    cc = count + subcount
+    pct = total and (cc*100.0/total) or 0
+    now = time.time()
+    elapsed = now - tstart
+    kps = elapsed and int(cc/1024./elapsed)
+    kps_frac = 10 ** int(math.log(kps+1, 10) - 1)
+    kps = int(kps/kps_frac)*kps_frac
+    if cc:
+        remain = elapsed*1.0/cc * (total-cc)
+    else:
+        remain = 0.0
+    if (lastremain and (remain > lastremain)
+          and ((remain - lastremain)/lastremain < 0.05)):
+        remain = lastremain
+    else:
+        lastremain = remain
+    hours = int(remain/60/60)
+    mins = int(remain/60 - hours*60)
+    secs = int(remain - hours*60*60 - mins*60)
+    if elapsed < 30:
+        remainstr = ''
+        kpsstr = ''
+    else:
+        kpsstr = '%dk/s' % kps
+        if hours:
+            remainstr = '%dh%dm' % (hours, mins)
+        elif mins:
+            remainstr = '%dm%d' % (mins, secs)
+        else:
+            remainstr = '%ds' % secs
+    progress('Saving: %.2f%% (%d/%dk, %d/%d files) %s %s\r'
+             % (pct, cc/1024, total/1024, fcount, ftotal,
+                remainstr, kpsstr))
+
+
+r = index.Reader(git.repo('bupindex'))
+
+def already_saved(ent):
+    return ent.is_valid() and w.exists(ent.sha) and ent.sha
+
+def wantrecurse_pre(ent):
+    return not already_saved(ent)
+
+def wantrecurse_during(ent):
+    return not already_saved(ent) or ent.sha_missing()
+
+total = ftotal = 0
+if opt.progress:
+    for (transname,ent) in r.filter(extra, wantrecurse=wantrecurse_pre):
+        if not (ftotal % 10024):
+            progress('Reading index: %d\r' % ftotal)
+        exists = ent.exists()
+        hashvalid = already_saved(ent)
+        ent.set_sha_missing(not hashvalid)
+        if not opt.smaller or ent.size < opt.smaller:
+            if exists and not hashvalid:
+                total += ent.size
+        ftotal += 1
+    progress('Reading index: %d, done.\n' % ftotal)
+    hashsplit.progress_callback = progress_report
+
+tstart = time.time()
+count = subcount = fcount = 0
+lastskip_name = None
+lastdir = ''
+for (transname,ent) in r.filter(extra, wantrecurse=wantrecurse_during):
+    (dir, file) = os.path.split(ent.name)
+    exists = (ent.flags & index.IX_EXISTS)
+    hashvalid = already_saved(ent)
+    wasmissing = ent.sha_missing()
+    oldsize = ent.size
+    if opt.verbose:
+        if not exists:
+            status = 'D'
+        elif not hashvalid:
+            if ent.sha == index.EMPTY_SHA:
+                status = 'A'
+            else:
+                status = 'M'
+        else:
+            status = ' '
+        if opt.verbose >= 2:
+            log('%s %-70s\n' % (status, ent.name))
+        elif not stat.S_ISDIR(ent.mode) and lastdir != dir:
+            if not lastdir.startswith(dir):
+                log('%s %-70s\n' % (status, os.path.join(dir, '')))
+            lastdir = dir
+
+    if opt.progress:
+        progress_report(0)
+    fcount += 1
+    
+    if not exists:
+        continue
+    if opt.smaller and ent.size >= opt.smaller:
+        if exists and not hashvalid:
+            add_error('skipping large file "%s"' % ent.name)
+            lastskip_name = ent.name
+        continue
+
+    assert(dir.startswith('/'))
+    dirp = dir.split('/')
+    while parts > dirp:
+        _pop(force_tree = None)
+    if dir != '/':
+        for part in dirp[len(parts):]:
+            _push(part)
+
+    if not file:
+        # no filename portion means this is a subdir.  But
+        # sub/parentdirectories already handled in the pop/push() part above.
+        oldtree = already_saved(ent) # may be None
+        newtree = _pop(force_tree = oldtree)
+        if not oldtree:
+            if lastskip_name and lastskip_name.startswith(ent.name):
+                ent.invalidate()
+            else:
+                ent.validate(040000, newtree)
+            ent.repack()
+        if exists and wasmissing:
+            count += oldsize
+        continue
+
+    # it's not a directory
+    id = None
+    if hashvalid:
+        mode = '%o' % ent.gitmode
+        id = ent.sha
+        shalists[-1].append((mode, 
+                             git.mangle_name(file, ent.mode, ent.gitmode),
+                             id))
+    else:
+        if stat.S_ISREG(ent.mode):
+            try:
+                f = hashsplit.open_noatime(ent.name)
+            except IOError, e:
+                add_error(e)
+                lastskip_name = ent.name
+            except OSError, e:
+                add_error(e)
+                lastskip_name = ent.name
+            else:
+                (mode, id) = hashsplit.split_to_blob_or_tree(w, [f])
+        else:
+            if stat.S_ISDIR(ent.mode):
+                assert(0)  # handled above
+            elif stat.S_ISLNK(ent.mode):
+                try:
+                    rl = os.readlink(ent.name)
+                except OSError, e:
+                    add_error(e)
+                    lastskip_name = ent.name
+                except IOError, e:
+                    add_error(e)
+                    lastskip_name = ent.name
+                else:
+                    (mode, id) = ('120000', w.new_blob(rl))
+            else:
+                add_error(Exception('skipping special file "%s"' % ent.name))
+                lastskip_name = ent.name
+        if id:
+            ent.validate(int(mode, 8), id)
+            ent.repack()
+            shalists[-1].append((mode,
+                                 git.mangle_name(file, ent.mode, ent.gitmode),
+                                 id))
+    if exists and wasmissing:
+        count += oldsize
+        subcount = 0
+
+
+if opt.progress:
+    pct = total and count*100.0/total or 100
+    progress('Saving: %.2f%% (%d/%dk, %d/%d files), done.    \n'
+             % (pct, count/1024, total/1024, fcount, ftotal))
+
+while len(parts) > 1:
+    _pop(force_tree = None)
+assert(len(shalists) == 1)
+tree = w.new_tree(shalists[-1])
+if opt.tree:
+    print tree.encode('hex')
+if opt.commit or opt.name:
+    msg = 'bup save\n\nGenerated by command:\n%r' % sys.argv
+    ref = opt.name and ('refs/heads/%s' % opt.name) or None
+    commit = w.new_commit(oldref, tree, msg)
+    if opt.commit:
+        print commit.encode('hex')
+
+w.close()  # must close before we can update the ref
+        
+if opt.name:
+    if cli:
+        cli.update_ref(refname, commit, oldref)
+    else:
+        git.update_ref(refname, commit, oldref)
+
+if cli:
+    cli.close()
+
+if saved_errors:
+    log('WARNING: %d errors encountered while saving.\n' % len(saved_errors))
+    sys.exit(1)
+#!/usr/bin/env python
+import sys, time
+from bup import options
+
+optspec = """
+bup tick
+"""
+o = options.Options('bup tick', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if extra:
+    o.fatal("no arguments expected")
+
+t = time.time()
+tleft = 1 - (t - int(t))
+time.sleep(tleft)
+#!/usr/bin/env python
+import os, sys, stat, time
+from bup import options, git, index, drecurse
+from bup.helpers import *
+
+
+def merge_indexes(out, r1, r2):
+    for e in index.MergeIter([r1, r2]):
+        # FIXME: shouldn't we remove deleted entries eventually?  When?
+        out.add_ixentry(e)
+
+
+class IterHelper:
+    def __init__(self, l):
+        self.i = iter(l)
+        self.cur = None
+        self.next()
+
+    def next(self):
+        try:
+            self.cur = self.i.next()
+        except StopIteration:
+            self.cur = None
+        return self.cur
+
+
+def check_index(reader):
+    try:
+        log('check: checking forward iteration...\n')
+        e = None
+        d = {}
+        for e in reader.forward_iter():
+            if e.children_n:
+                if opt.verbose:
+                    log('%08x+%-4d %r\n' % (e.children_ofs, e.children_n,
+                                            e.name))
+                assert(e.children_ofs)
+                assert(e.name.endswith('/'))
+                assert(not d.get(e.children_ofs))
+                d[e.children_ofs] = 1
+            if e.flags & index.IX_HASHVALID:
+                assert(e.sha != index.EMPTY_SHA)
+                assert(e.gitmode)
+        assert(not e or e.name == '/')  # last entry is *always* /
+        log('check: checking normal iteration...\n')
+        last = None
+        for e in reader:
+            if last:
+                assert(last > e.name)
+            last = e.name
+    except:
+        log('index error! at %r\n' % e)
+        raise
+    log('check: passed.\n')
+
+
+def update_index(top):
+    ri = index.Reader(indexfile)
+    wi = index.Writer(indexfile)
+    rig = IterHelper(ri.iter(name=top))
+    tstart = int(time.time())
+
+    hashgen = None
+    if opt.fake_valid:
+        def hashgen(name):
+            return (0100644, index.FAKE_SHA)
+
+    total = 0
+    for (path,pst) in drecurse.recursive_dirlist([top], xdev=opt.xdev):
+        if opt.verbose>=2 or (opt.verbose==1 and stat.S_ISDIR(pst.st_mode)):
+            sys.stdout.write('%s\n' % path)
+            sys.stdout.flush()
+            progress('Indexing: %d\r' % total)
+        elif not (total % 128):
+            progress('Indexing: %d\r' % total)
+        total += 1
+        while rig.cur and rig.cur.name > path:  # deleted paths
+            if rig.cur.exists():
+                rig.cur.set_deleted()
+                rig.cur.repack()
+            rig.next()
+        if rig.cur and rig.cur.name == path:    # paths that already existed
+            if pst:
+                rig.cur.from_stat(pst, tstart)
+            if not (rig.cur.flags & index.IX_HASHVALID):
+                if hashgen:
+                    (rig.cur.gitmode, rig.cur.sha) = hashgen(path)
+                    rig.cur.flags |= index.IX_HASHVALID
+            if opt.fake_invalid:
+                rig.cur.invalidate()
+            rig.cur.repack()
+            rig.next()
+        else:  # new paths
+            wi.add(path, pst, hashgen = hashgen)
+    progress('Indexing: %d, done.\n' % total)
+    
+    if ri.exists():
+        ri.save()
+        wi.flush()
+        if wi.count:
+            wr = wi.new_reader()
+            if opt.check:
+                log('check: before merging: oldfile\n')
+                check_index(ri)
+                log('check: before merging: newfile\n')
+                check_index(wr)
+            mi = index.Writer(indexfile)
+            merge_indexes(mi, ri, wr)
+            ri.close()
+            mi.close()
+            wr.close()
+        wi.abort()
+    else:
+        wi.close()
+
+
+optspec = """
+bup index <-p|m|u> [options...] <filenames...>
+--
+p,print    print the index entries for the given names (also works with -u)
+m,modified print only added/deleted/modified files (implies -p)
+s,status   print each filename with a status char (A/M/D) (implies -p)
+H,hash     print the hash for each object next to its name (implies -p)
+l,long     print more information about each file
+u,update   (recursively) update the index entries for the given filenames
+x,xdev,one-file-system  don't cross filesystem boundaries
+fake-valid mark all index entries as up-to-date even if they aren't
+fake-invalid mark all index entries as invalid
+check      carefully check index file integrity
+f,indexfile=  the name of the index file (default 'index')
+v,verbose  increase log output (can be used more than once)
+"""
+o = options.Options('bup index', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if not (opt.modified or opt['print'] or opt.status or opt.update or opt.check):
+    o.fatal('supply one or more of -p, -s, -m, -u, or --check')
+if (opt.fake_valid or opt.fake_invalid) and not opt.update:
+    o.fatal('--fake-{in,}valid are meaningless without -u')
+if opt.fake_valid and opt.fake_invalid:
+    o.fatal('--fake-valid is incompatible with --fake-invalid')
+
+git.check_repo_or_die()
+indexfile = opt.indexfile or git.repo('bupindex')
+
+handle_ctrl_c()
+
+if opt.check:
+    log('check: starting initial check.\n')
+    check_index(index.Reader(indexfile))
+
+paths = index.reduce_paths(extra)
+
+if opt.update:
+    if not paths:
+        o.fatal('update (-u) requested but no paths given')
+    for (rp,path) in paths:
+        update_index(rp)
+
+if opt['print'] or opt.status or opt.modified:
+    for (name, ent) in index.Reader(indexfile).filter(extra or ['']):
+        if (opt.modified 
+            and (ent.is_valid() or ent.is_deleted() or not ent.mode)):
+            continue
+        line = ''
+        if opt.status:
+            if ent.is_deleted():
+                line += 'D '
+            elif not ent.is_valid():
+                if ent.sha == index.EMPTY_SHA:
+                    line += 'A '
+                else:
+                    line += 'M '
+            else:
+                line += '  '
+        if opt.hash:
+            line += ent.sha.encode('hex') + ' '
+        if opt.long:
+            line += "%7s %7s " % (oct(ent.mode), oct(ent.gitmode))
+        print line + (name or './')
+
+if opt.check and (opt['print'] or opt.status or opt.modified or opt.update):
+    log('check: starting final check.\n')
+    check_index(index.Reader(indexfile))
+
+if saved_errors:
+    log('WARNING: %d errors encountered.\n' % len(saved_errors))
+    sys.exit(1)
+#!/usr/bin/env python
+import sys, os, struct
+from bup import options, helpers
+
+optspec = """
+bup rbackup-server
+--
+    This command is not intended to be run manually.
+"""
+o = options.Options('bup rbackup-server', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+if extra:
+    o.fatal('no arguments expected')
+
+# get the subcommand's argv.
+# Normally we could just pass this on the command line, but since we'll often
+# be getting called on the other end of an ssh pipe, which tends to mangle
+# argv (by sending it via the shell), this way is much safer.
+buf = sys.stdin.read(4)
+sz = struct.unpack('!I', buf)[0]
+assert(sz > 0)
+assert(sz < 1000000)
+buf = sys.stdin.read(sz)
+assert(len(buf) == sz)
+argv = buf.split('\0')
+
+# stdin/stdout are supposedly connected to 'bup server' that the caller
+# started for us (often on the other end of an ssh tunnel), so we don't want
+# to misuse them.  Move them out of the way, then replace stdout with
+# a pointer to stderr in case our subcommand wants to do something with it.
 #
-# Function that sends a SIGHUP to the daemon/service
+# It might be nice to do the same with stdin, but my experiments showed that
+# ssh seems to make its child's stderr a readable-but-never-reads-anything
+# socket.  They really should have used shutdown(SHUT_WR) on the other end
+# of it, but probably didn't.  Anyway, it's too messy, so let's just make sure
+# anyone reading from stdin is disappointed.
 #
-do_reload() {
-       #
-       # If the daemon can reload its configuration without
-       # restarting (for example, when it is sent a SIGHUP),
-       # then implement that here.
-       #
-       start-stop-daemon --stop --signal 1 --quiet --pidfile $PIDFILE --name $NAME
-       return 0
-}
-
-case "$1" in
-  start)
-       [ "$VERBOSE" != no ] && log_daemon_msg "Starting $DESC" "$NAME"
-       do_start
-       case "$?" in
-               0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
-               2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
-       esac
-       ;;
-  stop)
-       [ "$VERBOSE" != no ] && log_daemon_msg "Stopping $DESC" "$NAME"
-       do_stop
-       case "$?" in
-               0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
-               2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
-       esac
-       ;;
-  #reload|force-reload)
-       #
-       # If do_reload() is not implemented then leave this commented out
-       # and leave 'force-reload' as an alias for 'restart'.
-       #
-       #log_daemon_msg "Reloading $DESC" "$NAME"
-       #do_reload
-       #log_end_msg $?
-       #;;
-  restart|force-reload)
-       #
-       # If the "reload" option is implemented then remove the
-       # 'force-reload' alias
-       #
-       log_daemon_msg "Restarting $DESC" "$NAME"
-       do_stop
-       case "$?" in
-         0|1)
-               do_start
-               case "$?" in
-                       0) log_end_msg 0 ;;
-                       1) log_end_msg 1 ;; # Old process is still running
-                       *) log_end_msg 1 ;; # Failed to start
-               esac
-               ;;
-         *)
-               # Failed to stop
-               log_end_msg 1
-               ;;
-       esac
-       ;;
-  *)
-       #echo "Usage: $SCRIPTNAME {start|stop|restart|reload|force-reload}" >&2
-       echo "Usage: $SCRIPTNAME {start|stop|restart|force-reload}" >&2
-       exit 3
-       ;;
-esac
-
-:
-#! /bin/sh
-
-### BEGIN INIT INFO
-# Provides:            sshd
-# Required-Start:      $network $local_fs $remote_fs
-# Required-Stop:
-# Default-Start:       2 3 4 5
-# Default-Stop:                0 1 6
-# Short-Description:   OpenBSD Secure Shell server
-### END INIT INFO
-
-set -e
-
-# /etc/init.d/ssh: start and stop the OpenBSD "secure shell(tm)" daemon
-
-test -x /usr/sbin/sshd || exit 0
-( /usr/sbin/sshd -\? 2>&1 | grep -q OpenSSH ) 2>/dev/null || exit 0
-
-SSHD_OOM_ADJUST=-17
-if test -f /etc/default/ssh; then
-    . /etc/default/ssh
-fi
-
-. /lib/lsb/init-functions
-
-if [ -n "$2" ]; then
-    SSHD_OPTS="$SSHD_OPTS $2"
-fi
-
-# Are we running from init?
-run_by_init() {
-    ([ "$previous" ] && [ "$runlevel" ]) || [ "$runlevel" = S ]
-}
-
-check_for_no_start() {
-    # forget it if we're trying to start, and /etc/ssh/sshd_not_to_be_run exists
-    if [ -e /etc/ssh/sshd_not_to_be_run ]; then 
-       if [ "$1" = log_end_msg ]; then
-           log_end_msg 0
-       fi
-       if ! run_by_init; then
-           log_action_msg "OpenBSD Secure Shell server not in use (/etc/ssh/sshd_not_to_be_run)"
-       fi
-       exit 0
-    fi
-}
-
-check_dev_null() {
-    if [ ! -c /dev/null ]; then
-       if [ "$1" = log_end_msg ]; then
-           log_end_msg 1 || true
-       fi
-       if ! run_by_init; then
-           log_action_msg "/dev/null is not a character device!"
-       fi
-       exit 1
-    fi
-}
-
-check_privsep_dir() {
-    # Create the PrivSep empty dir if necessary
-    if [ ! -d /var/run/sshd ]; then
-       mkdir /var/run/sshd
-       chmod 0755 /var/run/sshd
-    fi
-}
-
-check_config() {
-    if [ ! -e /etc/ssh/sshd_not_to_be_run ]; then
-       /usr/sbin/sshd -t || exit 1
-    fi
-}
+# (You can't just leave stdin/stdout "not open" by closing the file
+# descriptors.  Then the next file that opens is automatically assigned 0 or 1,
+# and people *trying* to read/write stdin/stdout get screwed.)
+os.dup2(0, 3)
+os.dup2(1, 4)
+os.dup2(2, 1)
+fd = os.open('/dev/null', os.O_RDONLY)
+os.dup2(fd, 0)
+os.close(fd)
+
+os.environ['BUP_SERVER_REVERSE'] = helpers.hostname()
+os.execvp(argv[0], argv)
+sys.exit(99)
+#!/usr/bin/env python
+import sys, os, glob, subprocess, time
+from bup import options, git
+from bup.helpers import *
+
+par2_ok = 0
+nullf = open('/dev/null')
+
+def debug(s):
+    if opt.verbose:
+        log(s)
+
+def run(argv):
+    # at least in python 2.5, using "stdout=2" or "stdout=sys.stderr" below
+    # doesn't actually work, because subprocess closes fd #2 right before
+    # execing for some reason.  So we work around it by duplicating the fd
+    # first.
+    fd = os.dup(2)  # copy stderr
+    try:
+        p = subprocess.Popen(argv, stdout=fd, close_fds=False)
+        return p.wait()
+    finally:
+        os.close(fd)
+
+def par2_setup():
+    global par2_ok
+    rv = 1
+    try:
+        p = subprocess.Popen(['par2', '--help'],
+                             stdout=nullf, stderr=nullf, stdin=nullf)
+        rv = p.wait()
+    except OSError:
+        log('fsck: warning: par2 not found; disabling recovery features.\n')
+    else:
+        par2_ok = 1
+
+def parv(lvl):
+    if opt.verbose >= lvl:
+        if istty:
+            return []
+        else:
+            return ['-q']
+    else:
+        return ['-qq']
+
+def par2_generate(base):
+    return run(['par2', 'create', '-n1', '-c200'] + parv(2)
+               + ['--', base, base+'.pack', base+'.idx'])
+
+def par2_verify(base):
+    return run(['par2', 'verify'] + parv(3) + ['--', base])
+
+def par2_repair(base):
+    return run(['par2', 'repair'] + parv(2) + ['--', base])
+
+def quick_verify(base):
+    f = open(base + '.pack', 'rb')
+    f.seek(-20, 2)
+    wantsum = f.read(20)
+    assert(len(wantsum) == 20)
+    f.seek(0)
+    sum = Sha1()
+    for b in chunkyreader(f, os.fstat(f.fileno()).st_size - 20):
+        sum.update(b)
+    if sum.digest() != wantsum:
+        raise ValueError('expected %r, got %r' % (wantsum.encode('hex'),
+                                                  sum.hexdigest()))
+        
 
-adjust_oom() {
-    if [ -e /var/run/sshd.pid ]; then
-       PID="$(head -n1 /var/run/sshd.pid)"
-       if [ -e "/proc/$PID/oom_adj" ]; then
-           printf '%s' "$SSHD_OOM_ADJUST" >"/proc/$PID/oom_adj" || true
-       fi
-    fi
-}
+def git_verify(base):
+    if opt.quick:
+        try:
+            quick_verify(base)
+        except Exception, e:
+            debug('error: %s\n' % e)
+            return 1
+        return 0
+    else:
+        return run(['git', 'verify-pack', '--', base])
+    
+    
+def do_pack(base, last):
+    code = 0
+    if par2_ok and par2_exists and (opt.repair or not opt.generate):
+        vresult = par2_verify(base)
+        if vresult != 0:
+            if opt.repair:
+                rresult = par2_repair(base)
+                if rresult != 0:
+                    print '%s par2 repair: failed (%d)' % (last, rresult)
+                    code = rresult
+                else:
+                    print '%s par2 repair: succeeded (0)' % last
+                    code = 100
+            else:
+                print '%s par2 verify: failed (%d)' % (last, vresult)
+                code = vresult
+        else:
+            print '%s ok' % last
+    elif not opt.generate or (par2_ok and not par2_exists):
+        gresult = git_verify(base)
+        if gresult != 0:
+            print '%s git verify: failed (%d)' % (last, gresult)
+            code = gresult
+        else:
+            if par2_ok and opt.generate:
+                presult = par2_generate(base)
+                if presult != 0:
+                    print '%s par2 create: failed (%d)' % (last, presult)
+                    code = presult
+                else:
+                    print '%s ok' % last
+            else:
+                print '%s ok' % last
+    else:
+        assert(opt.generate and (not par2_ok or par2_exists))
+        debug('    skipped: par2 file already generated.\n')
+    return code
+
+
+optspec = """
+bup fsck [options...] [filenames...]
+--
+r,repair    attempt to repair errors using par2 (dangerous!)
+g,generate  generate auto-repair information using par2
+v,verbose   increase verbosity (can be used more than once)
+quick       just check pack sha1sum, don't use git verify-pack
+j,jobs=     run 'n' jobs in parallel
+par2-ok     immediately return 0 if par2 is ok, 1 if not
+disable-par2  ignore par2 even if it is available
+"""
+o = options.Options('bup fsck', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+par2_setup()
+if opt.par2_ok:
+    if par2_ok:
+        sys.exit(0)  # 'true' in sh
+    else:
+        sys.exit(1)
+if opt.disable_par2:
+    par2_ok = 0
+
+git.check_repo_or_die()
+
+if not extra:
+    debug('fsck: No filenames given: checking all packs.\n')
+    extra = glob.glob(git.repo('objects/pack/*.pack'))
+
+code = 0
+count = 0
+outstanding = {}
+for name in extra:
+    if name.endswith('.pack'):
+        base = name[:-5]
+    elif name.endswith('.idx'):
+        base = name[:-4]
+    elif name.endswith('.par2'):
+        base = name[:-5]
+    elif os.path.exists(name + '.pack'):
+        base = name
+    else:
+        raise Exception('%s is not a pack file!' % name)
+    (dir,last) = os.path.split(base)
+    par2_exists = os.path.exists(base + '.par2')
+    if par2_exists and os.stat(base + '.par2').st_size == 0:
+        par2_exists = 0
+    sys.stdout.flush()
+    debug('fsck: checking %s (%s)\n' 
+          % (last, par2_ok and par2_exists and 'par2' or 'git'))
+    if not opt.verbose:
+        progress('fsck (%d/%d)\r' % (count, len(extra)))
+    
+    if not opt.jobs:
+        nc = do_pack(base, last)
+        code = code or nc
+        count += 1
+    else:
+        while len(outstanding) >= opt.jobs:
+            (pid,nc) = os.wait()
+            nc >>= 8
+            if pid in outstanding:
+                del outstanding[pid]
+                code = code or nc
+                count += 1
+        pid = os.fork()
+        if pid:  # parent
+            outstanding[pid] = 1
+        else: # child
+            try:
+                sys.exit(do_pack(base, last))
+            except Exception, e:
+                log('exception: %r\n' % e)
+                sys.exit(99)
+                
+while len(outstanding):
+    (pid,nc) = os.wait()
+    nc >>= 8
+    if pid in outstanding:
+        del outstanding[pid]
+        code = code or nc
+        count += 1
+    if not opt.verbose:
+        progress('fsck (%d/%d)\r' % (count, len(extra)))
+
+if not opt.verbose and istty:
+    log('fsck done.           \n')
+sys.exit(code)
+#!/usr/bin/env python
+import sys, os, struct, getopt, subprocess, signal
+from bup import options, ssh
+from bup.helpers import *
+
+optspec = """
+bup rbackup <hostname> index ...
+bup rbackup <hostname> save ...
+bup rbackup <hostname> split ...
+"""
+o = options.Options('bup rbackup', optspec, optfunc=getopt.getopt)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+if len(extra) < 2:
+    o.fatal('arguments expected')
+
+class SigException(Exception):
+    def __init__(self, signum):
+        self.signum = signum
+        Exception.__init__(self, 'signal %d received' % signum)
+def handler(signum, frame):
+    raise SigException(signum)
+
+signal.signal(signal.SIGTERM, handler)
+signal.signal(signal.SIGINT, handler)
+
+sp = None
+p = None
+ret = 99
+
+try:
+    hostname = extra[0]
+    argv = extra[1:]
+    p = ssh.connect(hostname, 'rbackup-server')
+
+    argvs = '\0'.join(['bup'] + argv)
+    p.stdin.write(struct.pack('!I', len(argvs)) + argvs)
+    p.stdin.flush()
+
+    main_exe = os.environ.get('BUP_MAIN_EXE') or sys.argv[0]
+    sp = subprocess.Popen([main_exe, 'server'], stdin=p.stdout, stdout=p.stdin)
+
+    p.stdin.close()
+    p.stdout.close()
+
+finally:
+    while 1:
+        # if we get a signal while waiting, we have to keep waiting, just
+        # in case our child doesn't die.
+        try:
+            ret = p.wait()
+            sp.wait()
+            break
+        except SigException, e:
+            log('\nbup rbackup: %s\n' % e)
+            os.kill(p.pid, e.signum)
+            ret = 84
+sys.exit(ret)
+#!/usr/bin/env python
+import sys, os, re
+from bup import options
+
+optspec = """
+bup newliner
+"""
+o = options.Options('bup newliner', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if extra:
+    o.fatal("no arguments expected")
+
+r = re.compile(r'([\r\n])')
+lastlen = 0
+all = ''
+while 1:
+    l = r.split(all, 1)
+    if len(l) <= 1:
+        try:
+            b = os.read(sys.stdin.fileno(), 4096)
+        except KeyboardInterrupt:
+            break
+        if not b:
+            break
+        all += b
+    else:
+        assert(len(l) == 3)
+        (line, splitchar, all) = l
+        #splitchar = '\n'
+        sys.stdout.write('%-*s%s' % (lastlen, line, splitchar))
+        if splitchar == '\r':
+            lastlen = len(line)
+        else:
+            lastlen = 0
+        sys.stdout.flush()
+
+if lastlen or all:
+    sys.stdout.write('%-*s\n' % (lastlen, all))
+#!/usr/bin/env python
+import sys
+from bup import options, git, _hashsplit
+from bup.helpers import *
+
+
+optspec = """
+bup margin
+"""
+o = options.Options('bup margin', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if extra:
+    o.fatal("no arguments expected")
+
+git.check_repo_or_die()
+#git.ignore_midx = 1
+
+mi = git.PackIdxList(git.repo('objects/pack'))
+last = '\0'*20
+longmatch = 0
+for i in mi:
+    if i == last:
+        continue
+    #assert(str(i) >= last)
+    pm = _hashsplit.bitmatch(last, i)
+    longmatch = max(longmatch, pm)
+    last = i
+print longmatch
+#!/usr/bin/env python
+from bup import options, drecurse
+from bup.helpers import *
+
+optspec = """
+bup drecurse <path>
+--
+x,xdev,one-file-system   don't cross filesystem boundaries
+q,quiet  don't actually print filenames
+profile  run under the python profiler
+"""
+o = options.Options('bup drecurse', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if len(extra) != 1:
+    o.fatal("exactly one filename expected")
+
+it = drecurse.recursive_dirlist(extra, opt.xdev)
+if opt.profile:
+    import cProfile
+    def do_it():
+        for i in it:
+            pass
+    cProfile.run('do_it()')
+else:
+    if opt.quiet:
+        for i in it:
+            pass
+    else:
+        for (name,st) in it:
+            print name
+
+if saved_errors:
+    log('WARNING: %d errors encountered.\n' % len(saved_errors))
+    sys.exit(1)
+#!/usr/bin/env python
+import sys, time, struct
+from bup import hashsplit, git, options, client
+from bup.helpers import *
+from subprocess import PIPE
+
+
+optspec = """
+bup split [-tcb] [-n name] [--bench] [filenames...]
+--
+r,remote=  remote repository path
+b,blobs    output a series of blob ids
+t,tree     output a tree id
+c,commit   output a commit id
+n,name=    name of backup set to update (if any)
+N,noop     don't actually save the data anywhere
+q,quiet    don't print progress messages
+v,verbose  increase log output (can be used more than once)
+copy       just copy input to output, hashsplitting along the way
+bench      print benchmark timings to stderr
+max-pack-size=  maximum bytes in a single pack
+max-pack-objects=  maximum number of objects in a single pack
+fanout=  maximum number of blobs in a single tree
+"""
+o = options.Options('bup split', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+git.check_repo_or_die()
+if not (opt.blobs or opt.tree or opt.commit or opt.name or
+        opt.noop or opt.copy):
+    o.fatal("use one or more of -b, -t, -c, -n, -N, --copy")
+if (opt.noop or opt.copy) and (opt.blobs or opt.tree or 
+                               opt.commit or opt.name):
+    o.fatal('-N is incompatible with -b, -t, -c, -n')
+
+if opt.verbose >= 2:
+    git.verbose = opt.verbose - 1
+    opt.bench = 1
+if opt.max_pack_size:
+    hashsplit.max_pack_size = parse_num(opt.max_pack_size)
+if opt.max_pack_objects:
+    hashsplit.max_pack_objects = parse_num(opt.max_pack_objects)
+if opt.fanout:
+    hashsplit.fanout = parse_num(opt.fanout)
+if opt.blobs:
+    hashsplit.fanout = 0
+
+is_reverse = os.environ.get('BUP_SERVER_REVERSE')
+if is_reverse and opt.remote:
+    o.fatal("don't use -r in reverse mode; it's automatic")
+start_time = time.time()
+
+refname = opt.name and 'refs/heads/%s' % opt.name or None
+if opt.noop or opt.copy:
+    cli = w = oldref = None
+elif opt.remote or is_reverse:
+    cli = client.Client(opt.remote)
+    oldref = refname and cli.read_ref(refname) or None
+    w = cli.new_packwriter()
+else:
+    cli = None
+    oldref = refname and git.read_ref(refname) or None
+    w = git.PackWriter()
+
+files = extra and (open(fn) for fn in extra) or [sys.stdin]
+if w:
+    shalist = hashsplit.split_to_shalist(w, files)
+    tree = w.new_tree(shalist)
+else:
+    last = 0
+    for (blob, bits) in hashsplit.hashsplit_iter(files):
+        hashsplit.total_split += len(blob)
+        if opt.copy:
+            sys.stdout.write(str(blob))
+        megs = hashsplit.total_split/1024/1024
+        if not opt.quiet and last != megs:
+            progress('%d Mbytes read\r' % megs)
+            last = megs
+    progress('%d Mbytes read, done.\n' % megs)
+
+if opt.verbose:
+    log('\n')
+if opt.blobs:
+    for (mode,name,bin) in shalist:
+        print bin.encode('hex')
+if opt.tree:
+    print tree.encode('hex')
+if opt.commit or opt.name:
+    msg = 'bup split\n\nGenerated by command:\n%r' % sys.argv
+    ref = opt.name and ('refs/heads/%s' % opt.name) or None
+    commit = w.new_commit(oldref, tree, msg)
+    if opt.commit:
+        print commit.encode('hex')
+
+if w:
+    w.close()  # must close before we can update the ref
+        
+if opt.name:
+    if cli:
+        cli.update_ref(refname, commit, oldref)
+    else:
+        git.update_ref(refname, commit, oldref)
+
+if cli:
+    cli.close()
+
+secs = time.time() - start_time
+size = hashsplit.total_split
+if opt.bench:
+    log('\nbup: %.2fkbytes in %.2f secs = %.2f kbytes/sec\n'
+        % (size/1024., secs, size/1024./secs))
+#!/usr/bin/env python
+import sys, re, struct, mmap
+from bup import git, options
+from bup.helpers import *
+
+
+def s_from_bytes(bytes):
+    clist = [chr(b) for b in bytes]
+    return ''.join(clist)
+
+
+def report(count):
+    fields = ['VmSize', 'VmRSS', 'VmData', 'VmStk']
+    d = {}
+    for line in open('/proc/self/status').readlines():
+        l = re.split(r':\s*', line.strip(), 1)
+        d[l[0]] = l[1]
+    if count >= 0:
+        e1 = count
+        fields = [d[k] for k in fields]
+    else:
+        e1 = ''
+    print ('%9s  ' + ('%10s ' * len(fields))) % tuple([e1] + fields)
+    sys.stdout.flush()
+
+
+optspec = """
+bup memtest [-n elements] [-c cycles]
+--
+n,number=  number of objects per cycle
+c,cycles=  number of cycles to run
+ignore-midx  ignore .midx files, use only .idx files
+"""
+o = options.Options('bup memtest', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if extra:
+    o.fatal('no arguments expected')
+
+git.ignore_midx = opt.ignore_midx
+
+git.check_repo_or_die()
+m = git.PackIdxList(git.repo('objects/pack'))
+
+cycles = opt.cycles or 100
+number = opt.number or 10000
+
+report(-1)
+f = open('/dev/urandom')
+a = mmap.mmap(-1, 20)
+report(0)
+for c in xrange(cycles):
+    for n in xrange(number):
+        b = f.read(3)
+        if 0:
+            bytes = list(struct.unpack('!BBB', b)) + [0]*17
+            bytes[2] &= 0xf0
+            bin = struct.pack('!20s', s_from_bytes(bytes))
+        else:
+            a[0:2] = b[0:2]
+            a[2] = chr(ord(b[2]) & 0xf0)
+            bin = str(a[0:20])
+        #print bin.encode('hex')
+        m.exists(bin)
+    report((c+1)*number)
+#!/usr/bin/env python
+import sys, os, stat
+from bup import options, git, vfs
+from bup.helpers import *
+
+def print_node(text, n):
+    prefix = ''
+    if opt.hash:
+        prefix += "%s " % n.hash.encode('hex')
+    if stat.S_ISDIR(n.mode):
+        print '%s%s/' % (prefix, text)
+    elif stat.S_ISLNK(n.mode):
+        print '%s%s@' % (prefix, text)
+    else:
+        print '%s%s' % (prefix, text)
+
+
+optspec = """
+bup ls <dirs...>
+--
+s,hash   show hash for each file
+"""
+o = options.Options('bup ls', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+git.check_repo_or_die()
+top = vfs.RefList(None)
+
+if not extra:
+    extra = ['/']
+
+ret = 0
+for d in extra:
+    try:
+        n = top.lresolve(d)
+        if stat.S_ISDIR(n.mode):
+            for sub in n:
+                print_node(sub.name, sub)
+        else:
+            print_node(d, n)
+    except vfs.NodeError, e:
+        log('error: %s\n' % e)
+        ret = 1
+
+sys.exit(ret)
+#!/usr/bin/env python
+import sys, os, re, stat, readline, fnmatch
+from bup import options, git, shquote, vfs
+from bup.helpers import *
+
+def node_name(text, n):
+    if stat.S_ISDIR(n.mode):
+        return '%s/' % text
+    elif stat.S_ISLNK(n.mode):
+        return '%s@' % text
+    else:
+        return '%s' % text
+
+
+def do_ls(path, n):
+    l = []
+    if stat.S_ISDIR(n.mode):
+        for sub in n:
+            l.append(node_name(sub.name, sub))
+    else:
+        l.append(node_name(path, n))
+    print columnate(l, '')
+    
 
-export PATH="${PATH:+$PATH:}/usr/sbin:/sbin"
-
-case "$1" in
-  start)
-       check_privsep_dir
-       check_for_no_start
-       check_dev_null
-       log_daemon_msg "Starting OpenBSD Secure Shell server" "sshd"
-       if start-stop-daemon --start --quiet --oknodo --pidfile /var/run/sshd.pid --exec /usr/sbin/sshd -- $SSHD_OPTS; then
-           log_end_msg 0
-           adjust_oom
-       else
-           log_end_msg 1
-       fi
-       ;;
-  stop)
-       log_daemon_msg "Stopping OpenBSD Secure Shell server" "sshd"
-       if start-stop-daemon --stop --quiet --oknodo --pidfile /var/run/sshd.pid; then
-           log_end_msg 0
-       else
-           log_end_msg 1
-       fi
-       ;;
-
-  reload|force-reload)
-       check_for_no_start
-       check_config
-       log_daemon_msg "Reloading OpenBSD Secure Shell server's configuration" "sshd"
-       if start-stop-daemon --stop --signal 1 --quiet --oknodo --pidfile /var/run/sshd.pid --exec /usr/sbin/sshd; then
-           log_end_msg 0
-       else
-           log_end_msg 1
-       fi
-       ;;
-
-  restart)
-       check_privsep_dir
-       check_config
-       log_daemon_msg "Restarting OpenBSD Secure Shell server" "sshd"
-       start-stop-daemon --stop --quiet --oknodo --retry 30 --pidfile /var/run/sshd.pid
-       check_for_no_start log_end_msg
-       check_dev_null log_end_msg
-       if start-stop-daemon --start --quiet --oknodo --pidfile /var/run/sshd.pid --exec /usr/sbin/sshd -- $SSHD_OPTS; then
-           log_end_msg 0
-           adjust_oom
-       else
-           log_end_msg 1
-       fi
-       ;;
-
-  try-restart)
-       check_privsep_dir
-       check_config
-       log_daemon_msg "Restarting OpenBSD Secure Shell server" "sshd"
-       set +e
-       start-stop-daemon --stop --quiet --retry 30 --pidfile /var/run/sshd.pid
-       RET="$?"
-       set -e
-       case $RET in
-           0)
-               # old daemon stopped
-               check_for_no_start log_end_msg
-               check_dev_null log_end_msg
-               if start-stop-daemon --start --quiet --oknodo --pidfile /var/run/sshd.pid --exec /usr/sbin/sshd -- $SSHD_OPTS; then
-                   log_end_msg 0
-               else
-                   log_end_msg 1
-               fi
-               ;;
-           1)
-               # daemon not running
-               log_progress_msg "(not running)"
-               log_end_msg 0
-               ;;
-           *)
-               # failed to stop
-               log_progress_msg "(failed to stop)"
-               log_end_msg 1
-               ;;
-       esac
-       ;;
-
-  *)
-       log_action_msg "Usage: /etc/init.d/ssh {start|stop|reload|force-reload|restart|try-restart}"
-       exit 1
-esac
-
-exit 0
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          stop-bootlogd
-# Required-Start:    $remote_fs
-# Required-Stop:
-# Default-Start:     1 2 3 4 5
-# Default-Stop:
-# Short-Description: Stop bootlogd
-# Description:       See the bootlogd script
-### END INIT INFO
-
-NAME=stop-bootlogd
-DAEMON=/sbin/bootlogd
-
-[ -x "$DAEMON" ] || exit 0
-
-case "$1" in
-  start)
-       /etc/init.d/bootlogd stop
-       ;;
-  stop|restart|force-reload)
-       # No-op
-       ;;
-  *)
-       echo "Usage: $NAME {start|stop|restart|force-reload}" >&2
-       exit 3
-       ;;
-esac
-
-:
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          stop-bootlogd-single
-# Required-Start:    $remote_fs
-# Required-Stop:
-# Default-Start:     S
-# Default-Stop:
-# Short-Description: Stop bootlogd in single user mode
-# Description:       See the bootlogd script
-### END INIT INFO
-
-PATH=/usr/sbin:/usr/bin:/sbin:/bin
-NAME=stop-bootlogd-single
-DAEMON=/sbin/bootlogd
-
-[ -x "$DAEMON" ] || exit 0
-
-case "$1" in
-  start)
-       if [ ! -e /proc/cmdline ] || grep -q '\<single\>' /proc/cmdline
-       then
-               /etc/init.d/bootlogd stop
-       fi
-       ;;
-  stop|restart|force-reload)
-       # No-op
-       ;;
-  *)
-       echo "Usage: $NAME {start|stop|restart|force-reload}" >&2
-       exit 3
-       ;;
-esac
-
-:
-#! /bin/sh
-# /etc/init.d/sysklogd: start the system log daemon.
-
-### BEGIN INIT INFO
-# Provides:             syslog
-# Required-Start:       $local_fs $time
-# Required-Stop:        $local_fs $time
-# Should-Start:         $network $named
-# Should-Stop:          $network $named
-# Default-Start:        S 1 2 3 4 5
-# Default-Stop:         0 6
-# Short-Description:    System logger
-### END INIT INFO
-
-PATH=/bin:/usr/bin:/sbin:/usr/sbin
-
-pidfile=/var/run/syslogd.pid
-binpath=/sbin/syslogd
-
-test -x $binpath || exit 0
-
-# syslogd options should be set in /etc/default/syslogd
-SYSLOGD=""
-
-# user to run syslogd as - this can overriden in /etc/default/syslogd
-USER="syslog"
-
-test ! -r /etc/default/syslogd || . /etc/default/syslogd
-
-# allow ltsp to override
-test ! -r /etc/ltsp/syslogd || . /etc/ltsp/syslogd
-
-# Figure out under which user syslogd should be running as
-if echo ${SYSLOGD} | grep -q '^.*-u[[:space:]]*\([[:alnum:]]*\)[[:space:]]*.*$'
-then
-       # A specific user has been set on the command line, try to extract it.
-       USER=$(echo ${SYSLOGD} | sed -e 's/^.*-u[[:space:]]*\([[:alnum:]]*\)[[:space:]]*.*$/\1/')
-else
-       # By default, run syslogd under the syslog user
-       SYSLOGD="${SYSLOGD} -u ${USER}"
-fi
-
-# Unable to get the user under which syslogd should be running, stop.
-if [ -z "${USER}" ]
-then
-       log_failure_msg "Unable to get syslog user"
-       exit 1
-fi
-
-. /lib/lsb/init-functions
-
-create_xconsole()
-{
-    # Only proceed if /dev/xconsole is used at all
-    if ! grep -q '^[^#].*/dev/xconsole' /etc/syslog.conf
-    then
-       return
-    fi
-
-    if [ ! -e /dev/xconsole ]; then
-       mknod -m 640 /dev/xconsole p
-    else
-       chmod 0640 /dev/xconsole
-    fi
-
-    chown ${USER}:adm /dev/xconsole
+def write_to_file(inf, outf):
+    for blob in chunkyreader(inf):
+        outf.write(blob)
+    
 
-}
+def inputiter():
+    if os.isatty(sys.stdin.fileno()):
+        while 1:
+            try:
+                yield raw_input('bup> ')
+            except EOFError:
+                break
+    else:
+        for line in sys.stdin:
+            yield line
+
+
+def _completer_get_subs(line):
+    (qtype, lastword) = shquote.unfinished_word(line)
+    (dir,name) = os.path.split(lastword)
+    #log('\ncompleter: %r %r %r\n' % (qtype, lastword, text))
+    n = pwd.resolve(dir)
+    subs = list(filter(lambda x: x.name.startswith(name),
+                       n.subs()))
+    return (dir, name, qtype, lastword, subs)
+
+
+_last_line = None
+_last_res = None
+def completer(text, state):
+    global _last_line
+    global _last_res
+    try:
+        line = readline.get_line_buffer()[:readline.get_endidx()]
+        if _last_line != line:
+            _last_res = _completer_get_subs(line)
+            _last_line = line
+        (dir, name, qtype, lastword, subs) = _last_res
+        if state < len(subs):
+            sn = subs[state]
+            sn1 = sn.resolve('')  # deref symlinks
+            fullname = os.path.join(dir, sn.name)
+            if stat.S_ISDIR(sn1.mode):
+                ret = shquote.what_to_add(qtype, lastword, fullname+'/',
+                                          terminate=False)
+            else:
+                ret = shquote.what_to_add(qtype, lastword, fullname,
+                                          terminate=True) + ' '
+            return text + ret
+    except Exception, e:
+        log('\nerror in completion: %s\n' % e)
+
+            
+optspec = """
+bup ftp
+"""
+o = options.Options('bup ftp', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+git.check_repo_or_die()
+
+top = vfs.RefList(None)
+pwd = top
+
+if extra:
+    lines = extra
+else:
+    readline.set_completer_delims(' \t\n\r/')
+    readline.set_completer(completer)
+    readline.parse_and_bind("tab: complete")
+    lines = inputiter()
+
+for line in lines:
+    if not line.strip():
+        continue
+    words = [word for (wordstart,word) in shquote.quotesplit(line)]
+    cmd = words[0].lower()
+    #log('execute: %r %r\n' % (cmd, parm))
+    try:
+        if cmd == 'ls':
+            for parm in (words[1:] or ['.']):
+                do_ls(parm, pwd.resolve(parm))
+        elif cmd == 'cd':
+            for parm in words[1:]:
+                pwd = pwd.resolve(parm)
+        elif cmd == 'pwd':
+            print pwd.fullname()
+        elif cmd == 'cat':
+            for parm in words[1:]:
+                write_to_file(pwd.resolve(parm).open(), sys.stdout)
+        elif cmd == 'get':
+            if len(words) not in [2,3]:
+                raise Exception('Usage: get <filename> [localname]')
+            rname = words[1]
+            (dir,base) = os.path.split(rname)
+            lname = len(words)>2 and words[2] or base
+            inf = pwd.resolve(rname).open()
+            log('Saving %r\n' % lname)
+            write_to_file(inf, open(lname, 'wb'))
+        elif cmd == 'mget':
+            for parm in words[1:]:
+                (dir,base) = os.path.split(parm)
+                for n in pwd.resolve(dir).subs():
+                    if fnmatch.fnmatch(n.name, base):
+                        try:
+                            log('Saving %r\n' % n.name)
+                            inf = n.open()
+                            outf = open(n.name, 'wb')
+                            write_to_file(inf, outf)
+                            outf.close()
+                        except Exception, e:
+                            log('  error: %s\n' % e)
+        elif cmd == 'help' or cmd == '?':
+            log('Commands: ls cd pwd cat get mget help quit\n')
+        elif cmd == 'quit' or cmd == 'exit' or cmd == 'bye':
+            break
+        else:
+            raise Exception('no such command %r' % cmd)
+    except Exception, e:
+        log('error: %s\n' % e)
+        #raise
+#!/usr/bin/env python
+import sys, mmap
+from bup import options, _hashsplit
+from bup.helpers import *
+
+optspec = """
+bup random [-S seed] <numbytes>
+--
+S,seed=   optional random number seed (default 1)
+f,force   print random data to stdout even if it's a tty
+"""
+o = options.Options('bup random', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if len(extra) != 1:
+    o.fatal("exactly one argument expected")
+
+total = parse_num(extra[0])
+
+if opt.force or (not os.isatty(1) and
+                 not atoi(os.environ.get('BUP_FORCE_TTY')) & 1):
+    _hashsplit.write_random(sys.stdout.fileno(), total, opt.seed or 0)
+else:
+    log('error: not writing binary data to a terminal. Use -f to force.\n')
+    sys.exit(1)
+#!/usr/bin/env python
+import sys, os, glob
+from bup import options
+
+optspec = """
+bup help <command>
+"""
+o = options.Options('bup help', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if len(extra) == 0:
+    # the wrapper program provides the default usage string
+    os.execvp(os.environ['BUP_MAIN_EXE'], ['bup'])
+elif len(extra) == 1:
+    docname = (extra[0]=='bup' and 'bup' or ('bup-%s' % extra[0]))
+    exe = sys.argv[0]
+    (exepath, exefile) = os.path.split(exe)
+    manpath = os.path.join(exepath, '../Documentation/' + docname + '.[1-9]')
+    g = glob.glob(manpath)
+    if g:
+        os.execvp('man', ['man', '-l', g[0]])
+    else:
+        os.execvp('man', ['man', docname])
+else:
+    o.fatal("exactly one command name expected")
+#!/usr/bin/env python
+import sys, os, stat, errno, fuse, re, time, tempfile
+from bup import options, git, vfs
+from bup.helpers import *
+
+
+class Stat(fuse.Stat):
+    def __init__(self):
+        self.st_mode = 0
+        self.st_ino = 0
+        self.st_dev = 0
+        self.st_nlink = 0
+        self.st_uid = 0
+        self.st_gid = 0
+        self.st_size = 0
+        self.st_atime = 0
+        self.st_mtime = 0
+        self.st_ctime = 0
+        self.st_blocks = 0
+        self.st_blksize = 0
+        self.st_rdev = 0
+
+
+cache = {}
+def cache_get(top, path):
+    parts = path.split('/')
+    cache[('',)] = top
+    c = None
+    max = len(parts)
+    #log('cache: %r\n' % cache.keys())
+    for i in range(max):
+        pre = parts[:max-i]
+        #log('cache trying: %r\n' % pre)
+        c = cache.get(tuple(pre))
+        if c:
+            rest = parts[max-i:]
+            for r in rest:
+                #log('resolving %r from %r\n' % (r, c.fullname()))
+                c = c.lresolve(r)
+                key = tuple(pre + [r])
+                #log('saving: %r\n' % (key,))
+                cache[key] = c
+            break
+    assert(c)
+    return c
+        
+    
 
-fix_log_ownership()
-{
-       for l in `syslogd-listfiles -a`
-       do
-               chown ${USER}:adm $l
-       done
-}
+class BupFs(fuse.Fuse):
+    def __init__(self, top):
+        fuse.Fuse.__init__(self)
+        self.top = top
+    
+    def getattr(self, path):
+        log('--getattr(%r)\n' % path)
+        try:
+            node = cache_get(self.top, path)
+            st = Stat()
+            st.st_mode = node.mode
+            st.st_nlink = node.nlinks()
+            st.st_size = node.size()
+            st.st_mtime = node.mtime
+            st.st_ctime = node.ctime
+            st.st_atime = node.atime
+            return st
+        except vfs.NoSuchFile:
+            return -errno.ENOENT
+
+    def readdir(self, path, offset):
+        log('--readdir(%r)\n' % path)
+        node = cache_get(self.top, path)
+        yield fuse.Direntry('.')
+        yield fuse.Direntry('..')
+        for sub in node.subs():
+            yield fuse.Direntry(sub.name)
+
+    def readlink(self, path):
+        log('--readlink(%r)\n' % path)
+        node = cache_get(self.top, path)
+        return node.readlink()
+
+    def open(self, path, flags):
+        log('--open(%r)\n' % path)
+        node = cache_get(self.top, path)
+        accmode = os.O_RDONLY | os.O_WRONLY | os.O_RDWR
+        if (flags & accmode) != os.O_RDONLY:
+            return -errno.EACCES
+        node.open()
+
+    def release(self, path, flags):
+        log('--release(%r)\n' % path)
+
+    def read(self, path, size, offset):
+        log('--read(%r)\n' % path)
+        n = cache_get(self.top, path)
+        o = n.open()
+        o.seek(offset)
+        return o.read(size)
+
+
+if not hasattr(fuse, '__version__'):
+    raise RuntimeError, "your fuse module is too old for fuse.__version__"
+fuse.fuse_python_api = (0, 2)
+
+
+optspec = """
+bup fuse [-d] [-f] <mountpoint>
+--
+d,debug   increase debug level
+f,foreground  run in foreground
+"""
+o = options.Options('bup fuse', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if len(extra) != 1:
+    o.fatal("exactly one argument expected")
+
+git.check_repo_or_die()
+top = vfs.RefList(None)
+f = BupFs(top)
+f.fuse_args.mountpoint = extra[0]
+if opt.debug:
+    f.fuse_args.add('debug')
+if opt.foreground:
+    f.fuse_args.setmod('foreground')
+print f.multithreaded
+f.multithreaded = False
+
+f.main()
+#!/usr/bin/env python
+from bup import git, options, client
+from bup.helpers import *
+
+optspec = """
+[BUP_DIR=...] bup init [-r host:path]
+--
+r,remote=  remote repository path
+"""
+o = options.Options('bup init', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if extra:
+    o.fatal("no arguments expected")
+
+
+if opt.remote:
+    git.init_repo()  # local repo
+    git.check_repo_or_die()
+    cli = client.Client(opt.remote, create=True)
+    cli.close()
+else:
+    git.init_repo()
+#!/usr/bin/env python
+import sys, math, struct, glob
+from bup import options, git
+from bup.helpers import *
+
+PAGE_SIZE=4096
+SHA_PER_PAGE=PAGE_SIZE/200.
+
+
+def merge(idxlist, bits, table):
+    count = 0
+    for e in git.idxmerge(idxlist):
+        count += 1
+        prefix = git.extract_bits(e, bits)
+        table[prefix] = count
+        yield e
+
+
+def do_midx(outdir, outfilename, infilenames):
+    if not outfilename:
+        assert(outdir)
+        sum = Sha1('\0'.join(infilenames)).hexdigest()
+        outfilename = '%s/midx-%s.midx' % (outdir, sum)
+    
+    inp = []
+    total = 0
+    for name in infilenames:
+        ix = git.PackIdx(name)
+        inp.append(ix)
+        total += len(ix)
+
+    log('Merging %d indexes (%d objects).\n' % (len(infilenames), total))
+    if (not opt.force and (total < 1024 and len(infilenames) < 3)) \
+       or (opt.force and not total):
+        log('midx: nothing to do.\n')
+        return
+
+    pages = int(total/SHA_PER_PAGE) or 1
+    bits = int(math.ceil(math.log(pages, 2)))
+    entries = 2**bits
+    log('Table size: %d (%d bits)\n' % (entries*4, bits))
+    
+    table = [0]*entries
+
+    try:
+        os.unlink(outfilename)
+    except OSError:
+        pass
+    f = open(outfilename + '.tmp', 'w+')
+    f.write('MIDX\0\0\0\2')
+    f.write(struct.pack('!I', bits))
+    assert(f.tell() == 12)
+    f.write('\0'*4*entries)
+    
+    for e in merge(inp, bits, table):
+        f.write(e)
+        
+    f.write('\0'.join(os.path.basename(p) for p in infilenames))
+
+    f.seek(12)
+    f.write(struct.pack('!%dI' % entries, *table))
+    f.close()
+    os.rename(outfilename + '.tmp', outfilename)
+
+    # this is just for testing
+    if 0:
+        p = git.PackMidx(outfilename)
+        assert(len(p.idxnames) == len(infilenames))
+        print p.idxnames
+        assert(len(p) == total)
+        pi = iter(p)
+        for i in merge(inp, total, bits, table):
+            assert(i == pi.next())
+            assert(p.exists(i))
+
+    print outfilename
+
+optspec = """
+bup midx [options...] <idxnames...>
+--
+o,output=  output midx filename (default: auto-generated)
+a,auto     automatically create .midx from any unindexed .idx files
+f,force    automatically create .midx from *all* .idx files
+"""
+o = options.Options('bup midx', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if extra and (opt.auto or opt.force):
+    o.fatal("you can't use -f/-a and also provide filenames")
+
+git.check_repo_or_die()
+
+if extra:
+    do_midx(git.repo('objects/pack'), opt.output, extra)
+elif opt.auto or opt.force:
+    paths = [git.repo('objects/pack')]
+    paths += glob.glob(git.repo('index-cache/*/.'))
+    for path in paths:
+        log('midx: scanning %s\n' % path)
+        if opt.force:
+            do_midx(path, opt.output, glob.glob('%s/*.idx' % path))
+        elif opt.auto:
+            m = git.PackIdxList(path)
+            needed = {}
+            for pack in m.packs:  # only .idx files without a .midx are open
+                if pack.name.endswith('.idx'):
+                    needed[pack.name] = 1
+            del m
+            do_midx(path, opt.output, needed.keys())
+        log('\n')
+else:
+    o.fatal("you must use -f or -a or provide input filenames")
+#!/usr/bin/env python
+import sys, os, random
+from bup import options
+from bup.helpers import *
+
+
+def randblock(n):
+    l = []
+    for i in xrange(n):
+        l.append(chr(random.randrange(0,256)))
+    return ''.join(l)
+
+
+optspec = """
+bup damage [-n count] [-s maxsize] [-S seed] <filenames...>
+--
+   WARNING: THIS COMMAND IS EXTREMELY DANGEROUS
+n,num=   number of blocks to damage
+s,size=  maximum size of each damaged block
+percent= maximum size of each damaged block (as a percent of entire file)
+equal    spread damage evenly throughout the file
+S,seed=  random number seed (for repeatable tests)
+"""
+o = options.Options('bup damage', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if not extra:
+    o.fatal('filenames expected')
+
+if opt.seed != None:
+    random.seed(opt.seed)
+
+for name in extra:
+    log('Damaging "%s"...\n' % name)
+    f = open(name, 'r+b')
+    st = os.fstat(f.fileno())
+    size = st.st_size
+    if opt.percent or opt.size:
+        ms1 = int(float(opt.percent or 0)/100.0*size) or size
+        ms2 = opt.size or size
+        maxsize = min(ms1, ms2)
+    else:
+        maxsize = 1
+    chunks = opt.num or 10
+    chunksize = size/chunks
+    for r in range(chunks):
+        sz = random.randrange(1, maxsize+1)
+        if sz > size:
+            sz = size
+        if opt.equal:
+            ofs = r*chunksize
+        else:
+            ofs = random.randrange(0, size - sz + 1)
+        log('  %6d bytes at %d\n' % (sz, ofs))
+        f.seek(ofs)
+        f.write(randblock(sz))
+    f.close()
+#!/usr/bin/env python
+import sys, struct, mmap
+from bup import options, git
+from bup.helpers import *
+
+suspended_w = None
+
+
+def init_dir(conn, arg):
+    git.init_repo(arg)
+    log('bup server: bupdir initialized: %r\n' % git.repodir)
+    conn.ok()
+
+
+def set_dir(conn, arg):
+    git.check_repo_or_die(arg)
+    log('bup server: bupdir is %r\n' % git.repodir)
+    conn.ok()
 
-running()
-{
-    # No pidfile, probably no daemon present
-    #
-    if [ ! -f $pidfile ]
-    then
-       return 1
-    fi
-
-    pid=`cat $pidfile`
-
-    # No pid, probably no daemon present
-    #
-    if [ -z "$pid" ]
-    then
-       return 1
-    fi
-
-    if [ ! -d /proc/$pid ]
-    then
-       return 1
-    fi
-
-    cmd=`cat /proc/$pid/cmdline | tr "\000" "\n"|head -n 1`
-
-    # No syslogd?
-    #
-    if [ "$cmd" != "$binpath" ]
-    then
-       return 1
-    fi
-
-    return 0
+    
+def list_indexes(conn, junk):
+    git.check_repo_or_die()
+    for f in os.listdir(git.repo('objects/pack')):
+        if f.endswith('.idx'):
+            conn.write('%s\n' % f)
+    conn.ok()
+
+
+def send_index(conn, name):
+    git.check_repo_or_die()
+    assert(name.find('/') < 0)
+    assert(name.endswith('.idx'))
+    idx = git.PackIdx(git.repo('objects/pack/%s' % name))
+    conn.write(struct.pack('!I', len(idx.map)))
+    conn.write(idx.map)
+    conn.ok()
+
+
+def receive_objects(conn, junk):
+    global suspended_w
+    git.check_repo_or_die()
+    suggested = {}
+    if suspended_w:
+        w = suspended_w
+        suspended_w = None
+    else:
+        w = git.PackWriter()
+    while 1:
+        ns = conn.read(4)
+        if not ns:
+            w.abort()
+            raise Exception('object read: expected length header, got EOF\n')
+        n = struct.unpack('!I', ns)[0]
+        #log('expecting %d bytes\n' % n)
+        if not n:
+            log('bup server: received %d object%s.\n' 
+                % (w.count, w.count!=1 and "s" or ''))
+            fullpath = w.close()
+            if fullpath:
+                (dir, name) = os.path.split(fullpath)
+                conn.write('%s.idx\n' % name)
+            conn.ok()
+            return
+        elif n == 0xffffffff:
+            log('bup server: receive-objects suspended.\n')
+            suspended_w = w
+            conn.ok()
+            return
+            
+        buf = conn.read(n)  # object sizes in bup are reasonably small
+        #log('read %d bytes\n' % n)
+        if len(buf) < n:
+            w.abort()
+            raise Exception('object read: expected %d bytes, got %d\n'
+                            % (n, len(buf)))
+        (type, content) = git._decode_packobj(buf)
+        sha = git.calc_hash(type, content)
+        oldpack = w.exists(sha)
+        # FIXME: we only suggest a single index per cycle, because the client
+        # is currently dumb to download more than one per cycle anyway.
+        # Actually we should fix the client, but this is a minor optimization
+        # on the server side.
+        if not suggested and \
+          oldpack and (oldpack == True or oldpack.endswith('.midx')):
+            # FIXME: we shouldn't really have to know about midx files
+            # at this layer.  But exists() on a midx doesn't return the
+            # packname (since it doesn't know)... probably we should just
+            # fix that deficiency of midx files eventually, although it'll
+            # make the files bigger.  This method is certainly not very
+            # efficient.
+            w.objcache.refresh(skip_midx = True)
+            oldpack = w.objcache.exists(sha)
+            log('new suggestion: %r\n' % oldpack)
+            assert(oldpack)
+            assert(oldpack != True)
+            assert(not oldpack.endswith('.midx'))
+            w.objcache.refresh(skip_midx = False)
+        if not suggested and oldpack:
+            assert(oldpack.endswith('.idx'))
+            (dir,name) = os.path.split(oldpack)
+            if not (name in suggested):
+                log("bup server: suggesting index %s\n" % name)
+                conn.write('index %s\n' % name)
+                suggested[name] = 1
+        else:
+            w._raw_write([buf])
+    # NOTREACHED
+
+
+def read_ref(conn, refname):
+    git.check_repo_or_die()
+    r = git.read_ref(refname)
+    conn.write('%s\n' % (r or '').encode('hex'))
+    conn.ok()
+
+
+def update_ref(conn, refname):
+    git.check_repo_or_die()
+    newval = conn.readline().strip()
+    oldval = conn.readline().strip()
+    git.update_ref(refname, newval.decode('hex'), oldval.decode('hex'))
+    conn.ok()
+
+
+def cat(conn, id):
+    git.check_repo_or_die()
+    try:
+        for blob in git.cat(id):
+            conn.write(struct.pack('!I', len(blob)))
+            conn.write(blob)
+    except KeyError, e:
+        log('server: error: %s\n' % e)
+        conn.write('\0\0\0\0')
+        conn.error(e)
+    else:
+        conn.write('\0\0\0\0')
+        conn.ok()
+
+
+optspec = """
+bup server
+"""
+o = options.Options('bup server', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if extra:
+    o.fatal('no arguments expected')
+
+log('bup server: reading from stdin.\n')
+
+commands = {
+    'init-dir': init_dir,
+    'set-dir': set_dir,
+    'list-indexes': list_indexes,
+    'send-index': send_index,
+    'receive-objects': receive_objects,
+    'read-ref': read_ref,
+    'update-ref': update_ref,
+    'cat': cat,
 }
 
-case "$1" in
-  start)
-    log_begin_msg "Starting system log daemon..."
-    create_xconsole
-    fix_log_ownership
-    start-stop-daemon --start --quiet --pidfile $pidfile --name syslogd --startas $binpath -- $SYSLOGD
-    log_end_msg $?
-    ;;
-  stop)
-    log_begin_msg "Stopping system log daemon..."
-    start-stop-daemon --stop --quiet --pidfile $pidfile --name syslogd
-    log_end_msg $?
-    ;;
-  reload|force-reload)
-    log_begin_msg "Reloading system log daemon..."
-    fix_log_ownership
-    start-stop-daemon --stop --quiet --signal 1 --pidfile $pidfile --name syslogd
-    log_end_msg $?
-    ;;
-  restart)
-    log_begin_msg "Restarting system log daemon..."
-    start-stop-daemon --stop --retry 5 --quiet --pidfile $pidfile --name syslogd
-    fix_log_ownership
-    start-stop-daemon --start --quiet --pidfile $pidfile --name syslogd --startas $binpath -- $SYSLOGD
-    log_end_msg $?
-    ;;
-  reload-or-restart)
-    if running
-    then
-       $0 reload
-    else
-       $0 start
-    fi
-    ;;
-  *)
-    log_success_msg "Usage: /etc/init.d/sysklogd {start|stop|reload|restart|force-reload|reload-or-restart}"
-    exit 1
-esac
-
-exit 0
-#!/bin/sh -e
-# init script for udev
-
-# Check the package is still installed
-[ -x /sbin/udevd ] || exit 0
-
-# Get LSB functions
-. /lib/lsb/init-functions
-. /etc/default/rcS
-
-
-case "$1" in
-    start)
-       # We need the uevent support introduced in 2.6.15, bail out if we
-       # don't have it and fall back to a static /dev
-       if [ ! -f /sys/class/mem/null/uevent ]; then
-           if mountpoint -q /dev; then
-               # uh-oh, initramfs made some kind of /dev, get rid of it
-               umount -l /dev/.static/dev
-               umount -l /dev
-           fi
-           exit 1
-       fi
-
-       if ! mountpoint -q /dev; then
-           # initramfs didn't mount /dev, so we'll need to do that
-           mount -n --bind /dev /etc/udev
-           mount -n -t tmpfs -o mode=0755 udev /dev
-           mkdir -m 0700 -p /dev/.static/dev
-           mount -n --move /etc/udev /dev/.static/dev
-       fi
-
-       # Copy over default device tree
-       cp -a -f /lib/udev/devices/* /dev
-
-       # It's all over netlink now
-       if [ -e /proc/sys/kernel/hotplug ]; then
-           echo "" > /proc/sys/kernel/hotplug
-       fi
-       
-       # Start udevd
-       log_begin_msg "Starting kernel event manager..."
-       if start-stop-daemon --start --quiet --exec /sbin/udevd -- --daemon; then
-           log_end_msg 0
-       else
-           log_end_msg $?
-       fi
-
-       # This next bit can take a while
-       if type usplash_write >/dev/null 2>&1; then
-           usplash_write "TIMEOUT 360" ||:
-           trap "usplash_write 'TIMEOUT 15' ||:" 0
-       fi
-
-       # Log things that trigger does
-       /sbin/udevadm monitor -e >/dev/.udev.log &
-       UDEV_MONITOR_PID=$!
-
-       # Fix permissions and missing symlinks/programs for devices made in
-       # initramfs, and catch up on everything we missed
-       log_begin_msg "Loading hardware drivers..."
-       /sbin/udevadm trigger
-       if /sbin/udevadm settle; then
-           log_end_msg 0
-       else
-           log_end_msg $?
-       fi
-
-       # Kill the udev monitor again
-       kill $UDEV_MONITOR_PID
-       ;;
-    stop)
-       log_begin_msg "Stopping kernel event manager..."
-       if start-stop-daemon --stop --quiet --oknodo --exec /sbin/udevd; then
-           log_end_msg 0
-       else
-           log_end_msg $?
-       fi
-       umount -l /dev/.static/dev
-       umount -l /dev
-       ;;
-    restart)
-       cp -au /lib/udev/devices/* /dev
-
-       log_begin_msg "Loading additional hardware drivers..."
-       /sbin/udevadm trigger
-       if /sbin/udevadm settle; then
-           log_end_msg 0
-       else
-           log_end_msg $?
-       fi
-       ;;
-    reload|force-reload)
-       log_begin_msg "Reloading kernel event manager..."
-       if start-stop-daemon --stop --signal 1 --exec /sbin/udevd; then
-           log_end_msg 0
-       else
-           log_end_msg $?
-       fi
-       ;;
-*)
-       echo "Usage: /etc/init.d/udev {start|stop|restart|reload|force-reload}"
-       exit 1
-       ;;
-esac
-
-exit 0
-#!/bin/sh -e
-# init script to finish up udev
-
-# Check the package is still installed
-[ -x /sbin/udevd ] || exit 0
-
-# Get LSB functions
-. /lib/lsb/init-functions
-. /etc/default/rcS
-
-
-case "$1" in
-    start)
-       # Save udev log in /var/log/udev
-       if [ -e /dev/.udev.log ]; then
-           mv -f /dev/.udev.log /var/log/udev
-       fi
-
-       # Copy any rules generated while the root filesystem was read-only
-       for file in /dev/.udev/tmp-rules--*; do
-           dest=${file##*tmp-rules--}
-           [ "$dest" = '*' ] && break
-           cat $file >> /etc/udev/rules.d/$dest
-           rm -f $file
-       done
-       ;;
-    stop|restart|reload|force-reload)
-       ;;
-*)
-       echo "Usage: /etc/init.d/udev {start|stop|restart|reload|force-reload}"
-       exit 1
-       ;;
-esac
-
-exit 0
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          umountfs
-# Required-Start:    umountnfs urandom
-# Required-Stop:
-# Default-Start:     0 6
-# Default-Stop:
-# Short-Description: Turn off swap and unmount all local file systems.
-# Description:
-### END INIT INFO
-
-PATH=/usr/sbin:/usr/bin:/sbin:/bin
-. /lib/init/vars.sh
-
-. /lib/lsb/init-functions
-
-umask 022
-
-# Print in order of decreasing length
-#
-# Algorithm: Find and print longest argument, then call self
-# to print remaining arguments in order of decreasing length
-#
-# This function runs at one tenth the speed of the sort program
-# but we use the function because we don't want to rely on any
-# programs in /usr/.
+# FIXME: this protocol is totally lame and not at all future-proof.
+# (Especially since we abort completely as soon as *anything* bad happens)
+conn = Conn(sys.stdin, sys.stdout)
+lr = linereader(conn)
+for _line in lr:
+    line = _line.strip()
+    if not line:
+        continue
+    log('bup server: command: %r\n' % line)
+    words = line.split(' ', 1)
+    cmd = words[0]
+    rest = len(words)>1 and words[1] or ''
+    if cmd == 'quit':
+        break
+    else:
+        cmd = commands.get(cmd)
+        if cmd:
+            cmd(conn, rest)
+        else:
+            raise Exception('unknown server command: %r\n' % line)
+
+log('bup server: done\n')
+#!/usr/bin/env python
+import sys, time, struct
+from bup import hashsplit, git, options, client
+from bup.helpers import *
+from subprocess import PIPE
+
+
+optspec = """
+bup join [-r host:path] [refs or hashes...]
+--
+r,remote=  remote repository path
+"""
+o = options.Options('bup join', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+git.check_repo_or_die()
+
+if not extra:
+    extra = linereader(sys.stdin)
+
+ret = 0
+
+if opt.remote:
+    cli = client.Client(opt.remote)
+    cat = cli.cat
+else:
+    cp = git.CatPipe()
+    cat = cp.join
+
+for id in extra:
+    try:
+        for blob in cat(id):
+            sys.stdout.write(blob)
+    except KeyError, e:
+        sys.stdout.flush()
+        log('error: %s\n' % e)
+        ret = 1
+
+sys.exit(ret)
+#!/usr/bin/env python
+import sys, re, errno, stat, time, math
+from bup import hashsplit, git, options, index, client
+from bup.helpers import *
+
+
+optspec = """
+bup save [-tc] [-n name] <filenames...>
+--
+r,remote=  remote repository path
+t,tree     output a tree id
+c,commit   output a commit id
+n,name=    name of backup set to update (if any)
+v,verbose  increase log output (can be used more than once)
+q,quiet    don't show progress meter
+smaller=   only back up files smaller than n bytes
+"""
+o = options.Options('bup save', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+git.check_repo_or_die()
+if not (opt.tree or opt.commit or opt.name):
+    o.fatal("use one or more of -t, -c, -n")
+if not extra:
+    o.fatal("no filenames given")
+
+opt.progress = (istty and not opt.quiet)
+opt.smaller = parse_num(opt.smaller or 0)
+
+is_reverse = os.environ.get('BUP_SERVER_REVERSE')
+if is_reverse and opt.remote:
+    o.fatal("don't use -r in reverse mode; it's automatic")
+
+refname = opt.name and 'refs/heads/%s' % opt.name or None
+if opt.remote or is_reverse:
+    cli = client.Client(opt.remote)
+    oldref = refname and cli.read_ref(refname) or None
+    w = cli.new_packwriter()
+else:
+    cli = None
+    oldref = refname and git.read_ref(refname) or None
+    w = git.PackWriter()
+
+handle_ctrl_c()
+
+
+def eatslash(dir):
+    if dir.endswith('/'):
+        return dir[:-1]
+    else:
+        return dir
+
+
+parts = ['']
+shalists = [[]]
+
+def _push(part):
+    assert(part)
+    parts.append(part)
+    shalists.append([])
+
+def _pop(force_tree):
+    assert(len(parts) >= 1)
+    part = parts.pop()
+    shalist = shalists.pop()
+    tree = force_tree or w.new_tree(shalist)
+    if shalists:
+        shalists[-1].append(('40000', part, tree))
+    else:  # this was the toplevel, so put it back for sanity
+        shalists.append(shalist)
+    return tree
+
+lastremain = None
+def progress_report(n):
+    global count, subcount, lastremain
+    subcount += n
+    cc = count + subcount
+    pct = total and (cc*100.0/total) or 0
+    now = time.time()
+    elapsed = now - tstart
+    kps = elapsed and int(cc/1024./elapsed)
+    kps_frac = 10 ** int(math.log(kps+1, 10) - 1)
+    kps = int(kps/kps_frac)*kps_frac
+    if cc:
+        remain = elapsed*1.0/cc * (total-cc)
+    else:
+        remain = 0.0
+    if (lastremain and (remain > lastremain)
+          and ((remain - lastremain)/lastremain < 0.05)):
+        remain = lastremain
+    else:
+        lastremain = remain
+    hours = int(remain/60/60)
+    mins = int(remain/60 - hours*60)
+    secs = int(remain - hours*60*60 - mins*60)
+    if elapsed < 30:
+        remainstr = ''
+        kpsstr = ''
+    else:
+        kpsstr = '%dk/s' % kps
+        if hours:
+            remainstr = '%dh%dm' % (hours, mins)
+        elif mins:
+            remainstr = '%dm%d' % (mins, secs)
+        else:
+            remainstr = '%ds' % secs
+    progress('Saving: %.2f%% (%d/%dk, %d/%d files) %s %s\r'
+             % (pct, cc/1024, total/1024, fcount, ftotal,
+                remainstr, kpsstr))
+
+
+r = index.Reader(git.repo('bupindex'))
+
+def already_saved(ent):
+    return ent.is_valid() and w.exists(ent.sha) and ent.sha
+
+def wantrecurse_pre(ent):
+    return not already_saved(ent)
+
+def wantrecurse_during(ent):
+    return not already_saved(ent) or ent.sha_missing()
+
+total = ftotal = 0
+if opt.progress:
+    for (transname,ent) in r.filter(extra, wantrecurse=wantrecurse_pre):
+        if not (ftotal % 10024):
+            progress('Reading index: %d\r' % ftotal)
+        exists = ent.exists()
+        hashvalid = already_saved(ent)
+        ent.set_sha_missing(not hashvalid)
+        if not opt.smaller or ent.size < opt.smaller:
+            if exists and not hashvalid:
+                total += ent.size
+        ftotal += 1
+    progress('Reading index: %d, done.\n' % ftotal)
+    hashsplit.progress_callback = progress_report
+
+tstart = time.time()
+count = subcount = fcount = 0
+lastskip_name = None
+lastdir = ''
+for (transname,ent) in r.filter(extra, wantrecurse=wantrecurse_during):
+    (dir, file) = os.path.split(ent.name)
+    exists = (ent.flags & index.IX_EXISTS)
+    hashvalid = already_saved(ent)
+    wasmissing = ent.sha_missing()
+    oldsize = ent.size
+    if opt.verbose:
+        if not exists:
+            status = 'D'
+        elif not hashvalid:
+            if ent.sha == index.EMPTY_SHA:
+                status = 'A'
+            else:
+                status = 'M'
+        else:
+            status = ' '
+        if opt.verbose >= 2:
+            log('%s %-70s\n' % (status, ent.name))
+        elif not stat.S_ISDIR(ent.mode) and lastdir != dir:
+            if not lastdir.startswith(dir):
+                log('%s %-70s\n' % (status, os.path.join(dir, '')))
+            lastdir = dir
+
+    if opt.progress:
+        progress_report(0)
+    fcount += 1
+    
+    if not exists:
+        continue
+    if opt.smaller and ent.size >= opt.smaller:
+        if exists and not hashvalid:
+            add_error('skipping large file "%s"' % ent.name)
+            lastskip_name = ent.name
+        continue
+
+    assert(dir.startswith('/'))
+    dirp = dir.split('/')
+    while parts > dirp:
+        _pop(force_tree = None)
+    if dir != '/':
+        for part in dirp[len(parts):]:
+            _push(part)
+
+    if not file:
+        # no filename portion means this is a subdir.  But
+        # sub/parentdirectories already handled in the pop/push() part above.
+        oldtree = already_saved(ent) # may be None
+        newtree = _pop(force_tree = oldtree)
+        if not oldtree:
+            if lastskip_name and lastskip_name.startswith(ent.name):
+                ent.invalidate()
+            else:
+                ent.validate(040000, newtree)
+            ent.repack()
+        if exists and wasmissing:
+            count += oldsize
+        continue
+
+    # it's not a directory
+    id = None
+    if hashvalid:
+        mode = '%o' % ent.gitmode
+        id = ent.sha
+        shalists[-1].append((mode, 
+                             git.mangle_name(file, ent.mode, ent.gitmode),
+                             id))
+    else:
+        if stat.S_ISREG(ent.mode):
+            try:
+                f = hashsplit.open_noatime(ent.name)
+            except IOError, e:
+                add_error(e)
+                lastskip_name = ent.name
+            except OSError, e:
+                add_error(e)
+                lastskip_name = ent.name
+            else:
+                (mode, id) = hashsplit.split_to_blob_or_tree(w, [f])
+        else:
+            if stat.S_ISDIR(ent.mode):
+                assert(0)  # handled above
+            elif stat.S_ISLNK(ent.mode):
+                try:
+                    rl = os.readlink(ent.name)
+                except OSError, e:
+                    add_error(e)
+                    lastskip_name = ent.name
+                except IOError, e:
+                    add_error(e)
+                    lastskip_name = ent.name
+                else:
+                    (mode, id) = ('120000', w.new_blob(rl))
+            else:
+                add_error(Exception('skipping special file "%s"' % ent.name))
+                lastskip_name = ent.name
+        if id:
+            ent.validate(int(mode, 8), id)
+            ent.repack()
+            shalists[-1].append((mode,
+                                 git.mangle_name(file, ent.mode, ent.gitmode),
+                                 id))
+    if exists and wasmissing:
+        count += oldsize
+        subcount = 0
+
+
+if opt.progress:
+    pct = total and count*100.0/total or 100
+    progress('Saving: %.2f%% (%d/%dk, %d/%d files), done.    \n'
+             % (pct, count/1024, total/1024, fcount, ftotal))
+
+while len(parts) > 1:
+    _pop(force_tree = None)
+assert(len(shalists) == 1)
+tree = w.new_tree(shalists[-1])
+if opt.tree:
+    print tree.encode('hex')
+if opt.commit or opt.name:
+    msg = 'bup save\n\nGenerated by command:\n%r' % sys.argv
+    ref = opt.name and ('refs/heads/%s' % opt.name) or None
+    commit = w.new_commit(oldref, tree, msg)
+    if opt.commit:
+        print commit.encode('hex')
+
+w.close()  # must close before we can update the ref
+        
+if opt.name:
+    if cli:
+        cli.update_ref(refname, commit, oldref)
+    else:
+        git.update_ref(refname, commit, oldref)
+
+if cli:
+    cli.close()
+
+if saved_errors:
+    log('WARNING: %d errors encountered while saving.\n' % len(saved_errors))
+    sys.exit(1)
+#!/usr/bin/env python
+import sys, time
+from bup import options
+
+optspec = """
+bup tick
+"""
+o = options.Options('bup tick', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if extra:
+    o.fatal("no arguments expected")
+
+t = time.time()
+tleft = 1 - (t - int(t))
+time.sleep(tleft)
+#!/usr/bin/env python
+import os, sys, stat, time
+from bup import options, git, index, drecurse
+from bup.helpers import *
+
+
+def merge_indexes(out, r1, r2):
+    for e in index.MergeIter([r1, r2]):
+        # FIXME: shouldn't we remove deleted entries eventually?  When?
+        out.add_ixentry(e)
+
+
+class IterHelper:
+    def __init__(self, l):
+        self.i = iter(l)
+        self.cur = None
+        self.next()
+
+    def next(self):
+        try:
+            self.cur = self.i.next()
+        except StopIteration:
+            self.cur = None
+        return self.cur
+
+
+def check_index(reader):
+    try:
+        log('check: checking forward iteration...\n')
+        e = None
+        d = {}
+        for e in reader.forward_iter():
+            if e.children_n:
+                if opt.verbose:
+                    log('%08x+%-4d %r\n' % (e.children_ofs, e.children_n,
+                                            e.name))
+                assert(e.children_ofs)
+                assert(e.name.endswith('/'))
+                assert(not d.get(e.children_ofs))
+                d[e.children_ofs] = 1
+            if e.flags & index.IX_HASHVALID:
+                assert(e.sha != index.EMPTY_SHA)
+                assert(e.gitmode)
+        assert(not e or e.name == '/')  # last entry is *always* /
+        log('check: checking normal iteration...\n')
+        last = None
+        for e in reader:
+            if last:
+                assert(last > e.name)
+            last = e.name
+    except:
+        log('index error! at %r\n' % e)
+        raise
+    log('check: passed.\n')
+
+
+def update_index(top):
+    ri = index.Reader(indexfile)
+    wi = index.Writer(indexfile)
+    rig = IterHelper(ri.iter(name=top))
+    tstart = int(time.time())
+
+    hashgen = None
+    if opt.fake_valid:
+        def hashgen(name):
+            return (0100644, index.FAKE_SHA)
+
+    total = 0
+    for (path,pst) in drecurse.recursive_dirlist([top], xdev=opt.xdev):
+        if opt.verbose>=2 or (opt.verbose==1 and stat.S_ISDIR(pst.st_mode)):
+            sys.stdout.write('%s\n' % path)
+            sys.stdout.flush()
+            progress('Indexing: %d\r' % total)
+        elif not (total % 128):
+            progress('Indexing: %d\r' % total)
+        total += 1
+        while rig.cur and rig.cur.name > path:  # deleted paths
+            if rig.cur.exists():
+                rig.cur.set_deleted()
+                rig.cur.repack()
+            rig.next()
+        if rig.cur and rig.cur.name == path:    # paths that already existed
+            if pst:
+                rig.cur.from_stat(pst, tstart)
+            if not (rig.cur.flags & index.IX_HASHVALID):
+                if hashgen:
+                    (rig.cur.gitmode, rig.cur.sha) = hashgen(path)
+                    rig.cur.flags |= index.IX_HASHVALID
+            if opt.fake_invalid:
+                rig.cur.invalidate()
+            rig.cur.repack()
+            rig.next()
+        else:  # new paths
+            wi.add(path, pst, hashgen = hashgen)
+    progress('Indexing: %d, done.\n' % total)
+    
+    if ri.exists():
+        ri.save()
+        wi.flush()
+        if wi.count:
+            wr = wi.new_reader()
+            if opt.check:
+                log('check: before merging: oldfile\n')
+                check_index(ri)
+                log('check: before merging: newfile\n')
+                check_index(wr)
+            mi = index.Writer(indexfile)
+            merge_indexes(mi, ri, wr)
+            ri.close()
+            mi.close()
+            wr.close()
+        wi.abort()
+    else:
+        wi.close()
+
+
+optspec = """
+bup index <-p|m|u> [options...] <filenames...>
+--
+p,print    print the index entries for the given names (also works with -u)
+m,modified print only added/deleted/modified files (implies -p)
+s,status   print each filename with a status char (A/M/D) (implies -p)
+H,hash     print the hash for each object next to its name (implies -p)
+l,long     print more information about each file
+u,update   (recursively) update the index entries for the given filenames
+x,xdev,one-file-system  don't cross filesystem boundaries
+fake-valid mark all index entries as up-to-date even if they aren't
+fake-invalid mark all index entries as invalid
+check      carefully check index file integrity
+f,indexfile=  the name of the index file (default 'index')
+v,verbose  increase log output (can be used more than once)
+"""
+o = options.Options('bup index', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if not (opt.modified or opt['print'] or opt.status or opt.update or opt.check):
+    o.fatal('supply one or more of -p, -s, -m, -u, or --check')
+if (opt.fake_valid or opt.fake_invalid) and not opt.update:
+    o.fatal('--fake-{in,}valid are meaningless without -u')
+if opt.fake_valid and opt.fake_invalid:
+    o.fatal('--fake-valid is incompatible with --fake-invalid')
+
+git.check_repo_or_die()
+indexfile = opt.indexfile or git.repo('bupindex')
+
+handle_ctrl_c()
+
+if opt.check:
+    log('check: starting initial check.\n')
+    check_index(index.Reader(indexfile))
+
+paths = index.reduce_paths(extra)
+
+if opt.update:
+    if not paths:
+        o.fatal('update (-u) requested but no paths given')
+    for (rp,path) in paths:
+        update_index(rp)
+
+if opt['print'] or opt.status or opt.modified:
+    for (name, ent) in index.Reader(indexfile).filter(extra or ['']):
+        if (opt.modified 
+            and (ent.is_valid() or ent.is_deleted() or not ent.mode)):
+            continue
+        line = ''
+        if opt.status:
+            if ent.is_deleted():
+                line += 'D '
+            elif not ent.is_valid():
+                if ent.sha == index.EMPTY_SHA:
+                    line += 'A '
+                else:
+                    line += 'M '
+            else:
+                line += '  '
+        if opt.hash:
+            line += ent.sha.encode('hex') + ' '
+        if opt.long:
+            line += "%7s %7s " % (oct(ent.mode), oct(ent.gitmode))
+        print line + (name or './')
+
+if opt.check and (opt['print'] or opt.status or opt.modified or opt.update):
+    log('check: starting final check.\n')
+    check_index(index.Reader(indexfile))
+
+if saved_errors:
+    log('WARNING: %d errors encountered.\n' % len(saved_errors))
+    sys.exit(1)
+#!/usr/bin/env python
+import sys, os, struct
+from bup import options, helpers
+
+optspec = """
+bup rbackup-server
+--
+    This command is not intended to be run manually.
+"""
+o = options.Options('bup rbackup-server', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+if extra:
+    o.fatal('no arguments expected')
+
+# get the subcommand's argv.
+# Normally we could just pass this on the command line, but since we'll often
+# be getting called on the other end of an ssh pipe, which tends to mangle
+# argv (by sending it via the shell), this way is much safer.
+buf = sys.stdin.read(4)
+sz = struct.unpack('!I', buf)[0]
+assert(sz > 0)
+assert(sz < 1000000)
+buf = sys.stdin.read(sz)
+assert(len(buf) == sz)
+argv = buf.split('\0')
+
+# stdin/stdout are supposedly connected to 'bup server' that the caller
+# started for us (often on the other end of an ssh tunnel), so we don't want
+# to misuse them.  Move them out of the way, then replace stdout with
+# a pointer to stderr in case our subcommand wants to do something with it.
 #
-# N.B.: Arguments must not be null and must not contain whitespace
+# It might be nice to do the same with stdin, but my experiments showed that
+# ssh seems to make its child's stderr a readable-but-never-reads-anything
+# socket.  They really should have used shutdown(SHUT_WR) on the other end
+# of it, but probably didn't.  Anyway, it's too messy, so let's just make sure
+# anyone reading from stdin is disappointed.
 #
-pioodl() {
-       [ "$1" ] || return 0
-       ARGNUM=1
-       ARGNUM_LONGEST=0
-       ARGLENGTH_LONGEST=0
-       for ARG in "$@"
-       do
-               ARGLENGTH="${#ARG}"
-               if [ "$ARGLENGTH" -gt "$ARGLENGTH_LONGEST" ]
-               then
-                       ARGLENGTH_LONGEST="$ARGLENGTH"
-                       ARGNUM_LONGEST="$ARGNUM"
-               fi
-               ARGNUM=$(($ARGNUM + 1))
-       done
-       # The method of passing prevargs assumes that args can be
-       # delimited with spaces
-       ARGNUM=1
-       PREVARGS=""
-       while [ "$ARGNUM" -lt "$ARGNUM_LONGEST" ]
-       do
-               PREVARGS="$PREVARGS $1"
-               shift
-               ARGNUM=$(($ARGNUM + 1))
-       done
-       echo "$1"
-       shift
-       pioodl $PREVARGS "$@"
-}
+# (You can't just leave stdin/stdout "not open" by closing the file
+# descriptors.  Then the next file that opens is automatically assigned 0 or 1,
+# and people *trying* to read/write stdin/stdout get screwed.)
+os.dup2(0, 3)
+os.dup2(1, 4)
+os.dup2(2, 1)
+fd = os.open('/dev/null', os.O_RDONLY)
+os.dup2(fd, 0)
+os.close(fd)
+
+os.environ['BUP_SERVER_REVERSE'] = helpers.hostname()
+os.execvp(argv[0], argv)
+sys.exit(99)
+#!/usr/bin/env python
+import sys, os, glob, subprocess, time
+from bup import options, git
+from bup.helpers import *
+
+par2_ok = 0
+nullf = open('/dev/null')
+
+def debug(s):
+    if opt.verbose:
+        log(s)
+
+def run(argv):
+    # at least in python 2.5, using "stdout=2" or "stdout=sys.stderr" below
+    # doesn't actually work, because subprocess closes fd #2 right before
+    # execing for some reason.  So we work around it by duplicating the fd
+    # first.
+    fd = os.dup(2)  # copy stderr
+    try:
+        p = subprocess.Popen(argv, stdout=fd, close_fds=False)
+        return p.wait()
+    finally:
+        os.close(fd)
+
+def par2_setup():
+    global par2_ok
+    rv = 1
+    try:
+        p = subprocess.Popen(['par2', '--help'],
+                             stdout=nullf, stderr=nullf, stdin=nullf)
+        rv = p.wait()
+    except OSError:
+        log('fsck: warning: par2 not found; disabling recovery features.\n')
+    else:
+        par2_ok = 1
+
+def parv(lvl):
+    if opt.verbose >= lvl:
+        if istty:
+            return []
+        else:
+            return ['-q']
+    else:
+        return ['-qq']
+
+def par2_generate(base):
+    return run(['par2', 'create', '-n1', '-c200'] + parv(2)
+               + ['--', base, base+'.pack', base+'.idx'])
+
+def par2_verify(base):
+    return run(['par2', 'verify'] + parv(3) + ['--', base])
+
+def par2_repair(base):
+    return run(['par2', 'repair'] + parv(2) + ['--', base])
+
+def quick_verify(base):
+    f = open(base + '.pack', 'rb')
+    f.seek(-20, 2)
+    wantsum = f.read(20)
+    assert(len(wantsum) == 20)
+    f.seek(0)
+    sum = Sha1()
+    for b in chunkyreader(f, os.fstat(f.fileno()).st_size - 20):
+        sum.update(b)
+    if sum.digest() != wantsum:
+        raise ValueError('expected %r, got %r' % (wantsum.encode('hex'),
+                                                  sum.hexdigest()))
+        
 
+def git_verify(base):
+    if opt.quick:
+        try:
+            quick_verify(base)
+        except Exception, e:
+            debug('error: %s\n' % e)
+            return 1
+        return 0
+    else:
+        return run(['git', 'verify-pack', '--', base])
+    
+    
+def do_pack(base, last):
+    code = 0
+    if par2_ok and par2_exists and (opt.repair or not opt.generate):
+        vresult = par2_verify(base)
+        if vresult != 0:
+            if opt.repair:
+                rresult = par2_repair(base)
+                if rresult != 0:
+                    print '%s par2 repair: failed (%d)' % (last, rresult)
+                    code = rresult
+                else:
+                    print '%s par2 repair: succeeded (0)' % last
+                    code = 100
+            else:
+                print '%s par2 verify: failed (%d)' % (last, vresult)
+                code = vresult
+        else:
+            print '%s ok' % last
+    elif not opt.generate or (par2_ok and not par2_exists):
+        gresult = git_verify(base)
+        if gresult != 0:
+            print '%s git verify: failed (%d)' % (last, gresult)
+            code = gresult
+        else:
+            if par2_ok and opt.generate:
+                presult = par2_generate(base)
+                if presult != 0:
+                    print '%s par2 create: failed (%d)' % (last, presult)
+                    code = presult
+                else:
+                    print '%s ok' % last
+            else:
+                print '%s ok' % last
+    else:
+        assert(opt.generate and (not par2_ok or par2_exists))
+        debug('    skipped: par2 file already generated.\n')
+    return code
+
+
+optspec = """
+bup fsck [options...] [filenames...]
+--
+r,repair    attempt to repair errors using par2 (dangerous!)
+g,generate  generate auto-repair information using par2
+v,verbose   increase verbosity (can be used more than once)
+quick       just check pack sha1sum, don't use git verify-pack
+j,jobs=     run 'n' jobs in parallel
+par2-ok     immediately return 0 if par2 is ok, 1 if not
+disable-par2  ignore par2 even if it is available
+"""
+o = options.Options('bup fsck', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+par2_setup()
+if opt.par2_ok:
+    if par2_ok:
+        sys.exit(0)  # 'true' in sh
+    else:
+        sys.exit(1)
+if opt.disable_par2:
+    par2_ok = 0
+
+git.check_repo_or_die()
+
+if not extra:
+    debug('fsck: No filenames given: checking all packs.\n')
+    extra = glob.glob(git.repo('objects/pack/*.pack'))
+
+code = 0
+count = 0
+outstanding = {}
+for name in extra:
+    if name.endswith('.pack'):
+        base = name[:-5]
+    elif name.endswith('.idx'):
+        base = name[:-4]
+    elif name.endswith('.par2'):
+        base = name[:-5]
+    elif os.path.exists(name + '.pack'):
+        base = name
+    else:
+        raise Exception('%s is not a pack file!' % name)
+    (dir,last) = os.path.split(base)
+    par2_exists = os.path.exists(base + '.par2')
+    if par2_exists and os.stat(base + '.par2').st_size == 0:
+        par2_exists = 0
+    sys.stdout.flush()
+    debug('fsck: checking %s (%s)\n' 
+          % (last, par2_ok and par2_exists and 'par2' or 'git'))
+    if not opt.verbose:
+        progress('fsck (%d/%d)\r' % (count, len(extra)))
+    
+    if not opt.jobs:
+        nc = do_pack(base, last)
+        code = code or nc
+        count += 1
+    else:
+        while len(outstanding) >= opt.jobs:
+            (pid,nc) = os.wait()
+            nc >>= 8
+            if pid in outstanding:
+                del outstanding[pid]
+                code = code or nc
+                count += 1
+        pid = os.fork()
+        if pid:  # parent
+            outstanding[pid] = 1
+        else: # child
+            try:
+                sys.exit(do_pack(base, last))
+            except Exception, e:
+                log('exception: %r\n' % e)
+                sys.exit(99)
+                
+while len(outstanding):
+    (pid,nc) = os.wait()
+    nc >>= 8
+    if pid in outstanding:
+        del outstanding[pid]
+        code = code or nc
+        count += 1
+    if not opt.verbose:
+        progress('fsck (%d/%d)\r' % (count, len(extra)))
+
+if not opt.verbose and istty:
+    log('fsck done.           \n')
+sys.exit(code)
+#!/usr/bin/env python
+import sys, os, struct, getopt, subprocess, signal
+from bup import options, ssh
+from bup.helpers import *
+
+optspec = """
+bup rbackup <hostname> index ...
+bup rbackup <hostname> save ...
+bup rbackup <hostname> split ...
+"""
+o = options.Options('bup rbackup', optspec, optfunc=getopt.getopt)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+if len(extra) < 2:
+    o.fatal('arguments expected')
+
+class SigException(Exception):
+    def __init__(self, signum):
+        self.signum = signum
+        Exception.__init__(self, 'signal %d received' % signum)
+def handler(signum, frame):
+    raise SigException(signum)
+
+signal.signal(signal.SIGTERM, handler)
+signal.signal(signal.SIGINT, handler)
+
+sp = None
+p = None
+ret = 99
+
+try:
+    hostname = extra[0]
+    argv = extra[1:]
+    p = ssh.connect(hostname, 'rbackup-server')
+
+    argvs = '\0'.join(['bup'] + argv)
+    p.stdin.write(struct.pack('!I', len(argvs)) + argvs)
+    p.stdin.flush()
+
+    main_exe = os.environ.get('BUP_MAIN_EXE') or sys.argv[0]
+    sp = subprocess.Popen([main_exe, 'server'], stdin=p.stdout, stdout=p.stdin)
+
+    p.stdin.close()
+    p.stdout.close()
+
+finally:
+    while 1:
+        # if we get a signal while waiting, we have to keep waiting, just
+        # in case our child doesn't die.
+        try:
+            ret = p.wait()
+            sp.wait()
+            break
+        except SigException, e:
+            log('\nbup rbackup: %s\n' % e)
+            os.kill(p.pid, e.signum)
+            ret = 84
+sys.exit(ret)
+#!/usr/bin/env python
+import sys, os, re
+from bup import options
+
+optspec = """
+bup newliner
+"""
+o = options.Options('bup newliner', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if extra:
+    o.fatal("no arguments expected")
+
+r = re.compile(r'([\r\n])')
+lastlen = 0
+all = ''
+while 1:
+    l = r.split(all, 1)
+    if len(l) <= 1:
+        try:
+            b = os.read(sys.stdin.fileno(), 4096)
+        except KeyboardInterrupt:
+            break
+        if not b:
+            break
+        all += b
+    else:
+        assert(len(l) == 3)
+        (line, splitchar, all) = l
+        #splitchar = '\n'
+        sys.stdout.write('%-*s%s' % (lastlen, line, splitchar))
+        if splitchar == '\r':
+            lastlen = len(line)
+        else:
+            lastlen = 0
+        sys.stdout.flush()
+
+if lastlen or all:
+    sys.stdout.write('%-*s\n' % (lastlen, all))
+#!/usr/bin/env python
+import sys
+from bup import options, git, _hashsplit
+from bup.helpers import *
+
+
+optspec = """
+bup margin
+"""
+o = options.Options('bup margin', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if extra:
+    o.fatal("no arguments expected")
+
+git.check_repo_or_die()
+#git.ignore_midx = 1
+
+mi = git.PackIdxList(git.repo('objects/pack'))
+last = '\0'*20
+longmatch = 0
+for i in mi:
+    if i == last:
+        continue
+    #assert(str(i) >= last)
+    pm = _hashsplit.bitmatch(last, i)
+    longmatch = max(longmatch, pm)
+    last = i
+print longmatch
+#!/usr/bin/env python
+from bup import options, drecurse
+from bup.helpers import *
+
+optspec = """
+bup drecurse <path>
+--
+x,xdev,one-file-system   don't cross filesystem boundaries
+q,quiet  don't actually print filenames
+profile  run under the python profiler
+"""
+o = options.Options('bup drecurse', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if len(extra) != 1:
+    o.fatal("exactly one filename expected")
+
+it = drecurse.recursive_dirlist(extra, opt.xdev)
+if opt.profile:
+    import cProfile
+    def do_it():
+        for i in it:
+            pass
+    cProfile.run('do_it()')
+else:
+    if opt.quiet:
+        for i in it:
+            pass
+    else:
+        for (name,st) in it:
+            print name
+
+if saved_errors:
+    log('WARNING: %d errors encountered.\n' % len(saved_errors))
+    sys.exit(1)
+#!/usr/bin/env python
+import sys, time, struct
+from bup import hashsplit, git, options, client
+from bup.helpers import *
+from subprocess import PIPE
+
+
+optspec = """
+bup split [-tcb] [-n name] [--bench] [filenames...]
+--
+r,remote=  remote repository path
+b,blobs    output a series of blob ids
+t,tree     output a tree id
+c,commit   output a commit id
+n,name=    name of backup set to update (if any)
+N,noop     don't actually save the data anywhere
+q,quiet    don't print progress messages
+v,verbose  increase log output (can be used more than once)
+copy       just copy input to output, hashsplitting along the way
+bench      print benchmark timings to stderr
+max-pack-size=  maximum bytes in a single pack
+max-pack-objects=  maximum number of objects in a single pack
+fanout=  maximum number of blobs in a single tree
+"""
+o = options.Options('bup split', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+git.check_repo_or_die()
+if not (opt.blobs or opt.tree or opt.commit or opt.name or
+        opt.noop or opt.copy):
+    o.fatal("use one or more of -b, -t, -c, -n, -N, --copy")
+if (opt.noop or opt.copy) and (opt.blobs or opt.tree or 
+                               opt.commit or opt.name):
+    o.fatal('-N is incompatible with -b, -t, -c, -n')
+
+if opt.verbose >= 2:
+    git.verbose = opt.verbose - 1
+    opt.bench = 1
+if opt.max_pack_size:
+    hashsplit.max_pack_size = parse_num(opt.max_pack_size)
+if opt.max_pack_objects:
+    hashsplit.max_pack_objects = parse_num(opt.max_pack_objects)
+if opt.fanout:
+    hashsplit.fanout = parse_num(opt.fanout)
+if opt.blobs:
+    hashsplit.fanout = 0
+
+is_reverse = os.environ.get('BUP_SERVER_REVERSE')
+if is_reverse and opt.remote:
+    o.fatal("don't use -r in reverse mode; it's automatic")
+start_time = time.time()
+
+refname = opt.name and 'refs/heads/%s' % opt.name or None
+if opt.noop or opt.copy:
+    cli = w = oldref = None
+elif opt.remote or is_reverse:
+    cli = client.Client(opt.remote)
+    oldref = refname and cli.read_ref(refname) or None
+    w = cli.new_packwriter()
+else:
+    cli = None
+    oldref = refname and git.read_ref(refname) or None
+    w = git.PackWriter()
+
+files = extra and (open(fn) for fn in extra) or [sys.stdin]
+if w:
+    shalist = hashsplit.split_to_shalist(w, files)
+    tree = w.new_tree(shalist)
+else:
+    last = 0
+    for (blob, bits) in hashsplit.hashsplit_iter(files):
+        hashsplit.total_split += len(blob)
+        if opt.copy:
+            sys.stdout.write(str(blob))
+        megs = hashsplit.total_split/1024/1024
+        if not opt.quiet and last != megs:
+            progress('%d Mbytes read\r' % megs)
+            last = megs
+    progress('%d Mbytes read, done.\n' % megs)
+
+if opt.verbose:
+    log('\n')
+if opt.blobs:
+    for (mode,name,bin) in shalist:
+        print bin.encode('hex')
+if opt.tree:
+    print tree.encode('hex')
+if opt.commit or opt.name:
+    msg = 'bup split\n\nGenerated by command:\n%r' % sys.argv
+    ref = opt.name and ('refs/heads/%s' % opt.name) or None
+    commit = w.new_commit(oldref, tree, msg)
+    if opt.commit:
+        print commit.encode('hex')
+
+if w:
+    w.close()  # must close before we can update the ref
+        
+if opt.name:
+    if cli:
+        cli.update_ref(refname, commit, oldref)
+    else:
+        git.update_ref(refname, commit, oldref)
+
+if cli:
+    cli.close()
+
+secs = time.time() - start_time
+size = hashsplit.total_split
+if opt.bench:
+    log('\nbup: %.2fkbytes in %.2f secs = %.2f kbytes/sec\n'
+        % (size/1024., secs, size/1024./secs))
+#!/usr/bin/env python
+import sys, re, struct, mmap
+from bup import git, options
+from bup.helpers import *
+
+
+def s_from_bytes(bytes):
+    clist = [chr(b) for b in bytes]
+    return ''.join(clist)
+
+
+def report(count):
+    fields = ['VmSize', 'VmRSS', 'VmData', 'VmStk']
+    d = {}
+    for line in open('/proc/self/status').readlines():
+        l = re.split(r':\s*', line.strip(), 1)
+        d[l[0]] = l[1]
+    if count >= 0:
+        e1 = count
+        fields = [d[k] for k in fields]
+    else:
+        e1 = ''
+    print ('%9s  ' + ('%10s ' * len(fields))) % tuple([e1] + fields)
+    sys.stdout.flush()
+
+
+optspec = """
+bup memtest [-n elements] [-c cycles]
+--
+n,number=  number of objects per cycle
+c,cycles=  number of cycles to run
+ignore-midx  ignore .midx files, use only .idx files
+"""
+o = options.Options('bup memtest', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if extra:
+    o.fatal('no arguments expected')
+
+git.ignore_midx = opt.ignore_midx
+
+git.check_repo_or_die()
+m = git.PackIdxList(git.repo('objects/pack'))
+
+cycles = opt.cycles or 100
+number = opt.number or 10000
+
+report(-1)
+f = open('/dev/urandom')
+a = mmap.mmap(-1, 20)
+report(0)
+for c in xrange(cycles):
+    for n in xrange(number):
+        b = f.read(3)
+        if 0:
+            bytes = list(struct.unpack('!BBB', b)) + [0]*17
+            bytes[2] &= 0xf0
+            bin = struct.pack('!20s', s_from_bytes(bytes))
+        else:
+            a[0:2] = b[0:2]
+            a[2] = chr(ord(b[2]) & 0xf0)
+            bin = str(a[0:20])
+        #print bin.encode('hex')
+        m.exists(bin)
+    report((c+1)*number)
+#!/usr/bin/env python
+import sys, os, stat
+from bup import options, git, vfs
+from bup.helpers import *
+
+def print_node(text, n):
+    prefix = ''
+    if opt.hash:
+        prefix += "%s " % n.hash.encode('hex')
+    if stat.S_ISDIR(n.mode):
+        print '%s%s/' % (prefix, text)
+    elif stat.S_ISLNK(n.mode):
+        print '%s%s@' % (prefix, text)
+    else:
+        print '%s%s' % (prefix, text)
+
+
+optspec = """
+bup ls <dirs...>
+--
+s,hash   show hash for each file
+"""
+o = options.Options('bup ls', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+git.check_repo_or_die()
+top = vfs.RefList(None)
+
+if not extra:
+    extra = ['/']
+
+ret = 0
+for d in extra:
+    try:
+        n = top.lresolve(d)
+        if stat.S_ISDIR(n.mode):
+            for sub in n:
+                print_node(sub.name, sub)
+        else:
+            print_node(d, n)
+    except vfs.NodeError, e:
+        log('error: %s\n' % e)
+        ret = 1
+
+sys.exit(ret)
+#!/usr/bin/env python
+import sys, os, re, stat, readline, fnmatch
+from bup import options, git, shquote, vfs
+from bup.helpers import *
+
+def node_name(text, n):
+    if stat.S_ISDIR(n.mode):
+        return '%s/' % text
+    elif stat.S_ISLNK(n.mode):
+        return '%s@' % text
+    else:
+        return '%s' % text
+
+
+def do_ls(path, n):
+    l = []
+    if stat.S_ISDIR(n.mode):
+        for sub in n:
+            l.append(node_name(sub.name, sub))
+    else:
+        l.append(node_name(path, n))
+    print columnate(l, '')
+    
 
-do_stop () {
-       exec 9<&0 </proc/mounts
-       PROTECTED_MOUNTS="$(sed -n '0,/^\/[^ ]* \/ /p' /proc/mounts)"
-       WEAK_MTPTS="" #be gentle, don't use force
-       REG_MTPTS=""
-       TMPFS_MTPTS=""
-       while read DEV MTPT FSTYPE REST
-       do
-               echo "$PROTECTED_MOUNTS" | grep -qs "^$DEV $MTPT " && continue
-               case "$MTPT" in
-                       /|/proc|/dev|/.dev|/dev/pts|/dev/shm|/proc/*|/sys|/var/run|/var/lock)
-                       continue
-                       ;;
-               esac
-               case "$FSTYPE" in
-                       proc|procfs|linprocfs|devfs|sysfs|usbfs|usbdevfs|devpts|securityfs)
-                       continue
-                       ;;
-                 tmpfs)
-                       if [ -d "$MTPT" ]; then
-                               TMPFS_MTPTS="$TMPFS_MTPTS $MTPT"
-                       fi
-                       ;;
-                 *)
-                       REG_MTPTS="$REG_MTPTS $MTPT"
-                       if echo "$PROTECTED_MOUNTS" | grep -qs "^$DEV "; then
-                               WEAK_MTPTS="$WEAK_MTPTS $MTPT "
-                       fi
-                       ;;
-               esac
-       done
-
-       exec 0<&9 9<&-
-
-       #
-       # Make sure tmpfs file systems are umounted before turning off
-       # swap, to avoid running out of memory if the tmpfs filesystems
-       # use a lot of space.
-       #
-       if [ "$TMPFS_MTPTS" ]
-       then
-               if [ "$VERBOSE" = no ]
-               then
-                       log_action_begin_msg "Unmounting temporary filesystems"
-                       umount $TMPFS_MTPTS
-                       log_action_end_msg $?
-               else
-                       log_action_msg "Will now unmount temporary filesystems"
-                       umount -v $TMPFS_MTPTS
-                       ES=$?
-                       if [ "$ES" = 0 ]
-                       then
-                               log_success_msg "Done unmounting temporary filesystems."
-                       else
-                               log_failure_msg "Unmounting temporary filesystems failed with error code ${ES}."
-                       fi
-               fi
-       fi
-
-       #
-       # Deactivate swap
-       #
-       if [ "$VERBOSE" = no ]
-       then
-               log_action_begin_msg "Deactivating swap"
-               swapoff -a >/dev/null
-               log_action_end_msg $?
-       else
-               log_action_msg "Will now deactivate swap"
-               swapoff -a -v
-               ES=$?
-               if [ "$ES" = 0 ]
-               then
-                       log_success_msg "Done deactivating swap."
-               else
-                       log_failure_msg "Swap deactivation failed with error code ${ES}."
-               fi
-       fi
-
-       #
-       # Unmount local filesystems
-       #
-       [ -z "$REG_MTPTS" ] && return
-       [ "$VERBOSE" = no ] && log_action_begin_msg "Unmounting local filesystems"
-       REG_MTPTS="$(pioodl $REG_MTPTS)"
-       local ES2=0
-       for MTPT in $REG_MTPTS; do
-               if echo "$WEAK_MTPTS" | grep -qs " $MTPT "; then
-                       FORCE=""
-               else
-                       FORCE="-f"
-               fi
-               if [ "$VERBOSE" = no ]; then
-                       umount $FORCE -r -d $MTPT
-                       ES=$?
-                       [ "$ES" != 0 ] && [ "$ES2" = 0 ] && ES2=$ES
-               else
-                       log_action_begin_msg "Unmounting local filesystem $MTPT"
-                       umount $FORCE -v -r -d $MTPT
-                       ES=$?
-                       if [ "$ES" = 0 ]; then
-                               log_success_msg "Done unmounting local filesystem $MTPT."
-                       else
-                               log_failure_msg "Unmounting local filesystem $MTPT failed with error code $ES."
-                       fi
-               fi
-       done
-       [ "$VERBOSE" = no ] && log_action_end_msg $ES2
-}
+def write_to_file(inf, outf):
+    for blob in chunkyreader(inf):
+        outf.write(blob)
+    
 
-case "$1" in
-  start)
-       # No-op
-       ;;
-  restart|reload|force-reload)
-       echo "Error: argument '$1' not supported" >&2
-       exit 3
-       ;;
-  stop)
-       do_stop
-       ;;
-  *)
-       echo "Usage: $0 start|stop" >&2
-       exit 3
-       ;;
-esac
-
-:
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          umountnfs
-# Required-Start:    sendsigs
-# Required-Stop:
-# Default-Start:     6
-# Default-Stop:
-# Short-Description: Unmount all network filesystems except the root file system.
-# Description:       Also unmounts all virtual filesystems (proc, devfs, devpts,
-#                    usbfs, sysfs) that are not mounted at the top level.
-### END INIT INFO
-
-PATH=/usr/sbin:/usr/bin:/sbin:/bin
-KERNEL="$(uname -s)"
-RELEASE="$(uname -r)"
-. /lib/init/vars.sh
-
-. /lib/lsb/init-functions
-
-case "${KERNEL}:${RELEASE}" in
-  Linux:[01].*|Linux:2.[01].*)
-       FLAGS=""
-       ;;
-  Linux:2.[23].*|Linux:2.4.?|Linux:2.4.?-*|Linux:2.4.10|Linux:2.4.10-*)
-       FLAGS="-f"
-       ;;
-  *)
-       FLAGS="-f -l"
-       ;;
-esac
-
-do_stop () {
-       # Write a reboot record to /var/log/wtmp before unmounting
-       halt -w
-
-       # Remove bootclean flag files (precaution against symlink attacks)
-       rm -f /tmp/.clean /var/lock/.clean /var/run/.clean
-
-       [ "$VERBOSE" = no ] || log_action_begin_msg "Unmounting remote and non-toplevel virtual filesystems"
-
-       #
-       # Make list of points to unmount in reverse order of their creation
-       #
-
-       exec 9<&0 </proc/mounts
-
-       DIRS=""
-       while read DEV MTPT FSTYPE REST
-       do
-               case "$MTPT" in
-                 /|/proc|/dev|/dev/pts|/dev/shm|/proc/*|/sys|/var/run|/var/lock)
-                       continue
-                       ;;
-               esac
-               case "$FSTYPE" in
-                 nfs|nfs4|smbfs|ncp|ncpfs|cifs|coda|ocfs2|gfs)
-                       DIRS="$MTPT $DIRS"
-                       ;;
-                 proc|procfs|linprocfs|devfs|devpts|usbfs|usbdevfs|sysfs)
-                       DIRS="$MTPT $DIRS"
-                       ;;
-               esac
-       done
-
-       exec 0<&9 9<&-
-
-       if [ "$DIRS" ]
-       then
-               umount $FLAGS $DIRS
-       fi
-       ES=$?
-
-       [ "$VERBOSE" = no ] || log_action_end_msg $ES
-}
+def inputiter():
+    if os.isatty(sys.stdin.fileno()):
+        while 1:
+            try:
+                yield raw_input('bup> ')
+            except EOFError:
+                break
+    else:
+        for line in sys.stdin:
+            yield line
+
+
+def _completer_get_subs(line):
+    (qtype, lastword) = shquote.unfinished_word(line)
+    (dir,name) = os.path.split(lastword)
+    #log('\ncompleter: %r %r %r\n' % (qtype, lastword, text))
+    n = pwd.resolve(dir)
+    subs = list(filter(lambda x: x.name.startswith(name),
+                       n.subs()))
+    return (dir, name, qtype, lastword, subs)
+
+
+_last_line = None
+_last_res = None
+def completer(text, state):
+    global _last_line
+    global _last_res
+    try:
+        line = readline.get_line_buffer()[:readline.get_endidx()]
+        if _last_line != line:
+            _last_res = _completer_get_subs(line)
+            _last_line = line
+        (dir, name, qtype, lastword, subs) = _last_res
+        if state < len(subs):
+            sn = subs[state]
+            sn1 = sn.resolve('')  # deref symlinks
+            fullname = os.path.join(dir, sn.name)
+            if stat.S_ISDIR(sn1.mode):
+                ret = shquote.what_to_add(qtype, lastword, fullname+'/',
+                                          terminate=False)
+            else:
+                ret = shquote.what_to_add(qtype, lastword, fullname,
+                                          terminate=True) + ' '
+            return text + ret
+    except Exception, e:
+        log('\nerror in completion: %s\n' % e)
+
+            
+optspec = """
+bup ftp
+"""
+o = options.Options('bup ftp', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+git.check_repo_or_die()
+
+top = vfs.RefList(None)
+pwd = top
+
+if extra:
+    lines = extra
+else:
+    readline.set_completer_delims(' \t\n\r/')
+    readline.set_completer(completer)
+    readline.parse_and_bind("tab: complete")
+    lines = inputiter()
+
+for line in lines:
+    if not line.strip():
+        continue
+    words = [word for (wordstart,word) in shquote.quotesplit(line)]
+    cmd = words[0].lower()
+    #log('execute: %r %r\n' % (cmd, parm))
+    try:
+        if cmd == 'ls':
+            for parm in (words[1:] or ['.']):
+                do_ls(parm, pwd.resolve(parm))
+        elif cmd == 'cd':
+            for parm in words[1:]:
+                pwd = pwd.resolve(parm)
+        elif cmd == 'pwd':
+            print pwd.fullname()
+        elif cmd == 'cat':
+            for parm in words[1:]:
+                write_to_file(pwd.resolve(parm).open(), sys.stdout)
+        elif cmd == 'get':
+            if len(words) not in [2,3]:
+                raise Exception('Usage: get <filename> [localname]')
+            rname = words[1]
+            (dir,base) = os.path.split(rname)
+            lname = len(words)>2 and words[2] or base
+            inf = pwd.resolve(rname).open()
+            log('Saving %r\n' % lname)
+            write_to_file(inf, open(lname, 'wb'))
+        elif cmd == 'mget':
+            for parm in words[1:]:
+                (dir,base) = os.path.split(parm)
+                for n in pwd.resolve(dir).subs():
+                    if fnmatch.fnmatch(n.name, base):
+                        try:
+                            log('Saving %r\n' % n.name)
+                            inf = n.open()
+                            outf = open(n.name, 'wb')
+                            write_to_file(inf, outf)
+                            outf.close()
+                        except Exception, e:
+                            log('  error: %s\n' % e)
+        elif cmd == 'help' or cmd == '?':
+            log('Commands: ls cd pwd cat get mget help quit\n')
+        elif cmd == 'quit' or cmd == 'exit' or cmd == 'bye':
+            break
+        else:
+            raise Exception('no such command %r' % cmd)
+    except Exception, e:
+        log('error: %s\n' % e)
+        #raise
+#!/usr/bin/env python
+import sys, mmap
+from bup import options, _hashsplit
+from bup.helpers import *
+
+optspec = """
+bup random [-S seed] <numbytes>
+--
+S,seed=   optional random number seed (default 1)
+f,force   print random data to stdout even if it's a tty
+"""
+o = options.Options('bup random', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if len(extra) != 1:
+    o.fatal("exactly one argument expected")
+
+total = parse_num(extra[0])
+
+if opt.force or (not os.isatty(1) and
+                 not atoi(os.environ.get('BUP_FORCE_TTY')) & 1):
+    _hashsplit.write_random(sys.stdout.fileno(), total, opt.seed or 0)
+else:
+    log('error: not writing binary data to a terminal. Use -f to force.\n')
+    sys.exit(1)
+#!/usr/bin/env python
+import sys, os, glob
+from bup import options
+
+optspec = """
+bup help <command>
+"""
+o = options.Options('bup help', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if len(extra) == 0:
+    # the wrapper program provides the default usage string
+    os.execvp(os.environ['BUP_MAIN_EXE'], ['bup'])
+elif len(extra) == 1:
+    docname = (extra[0]=='bup' and 'bup' or ('bup-%s' % extra[0]))
+    exe = sys.argv[0]
+    (exepath, exefile) = os.path.split(exe)
+    manpath = os.path.join(exepath, '../Documentation/' + docname + '.[1-9]')
+    g = glob.glob(manpath)
+    if g:
+        os.execvp('man', ['man', '-l', g[0]])
+    else:
+        os.execvp('man', ['man', docname])
+else:
+    o.fatal("exactly one command name expected")
+#!/usr/bin/env python
+import sys, os, stat, errno, fuse, re, time, tempfile
+from bup import options, git, vfs
+from bup.helpers import *
+
+
+class Stat(fuse.Stat):
+    def __init__(self):
+        self.st_mode = 0
+        self.st_ino = 0
+        self.st_dev = 0
+        self.st_nlink = 0
+        self.st_uid = 0
+        self.st_gid = 0
+        self.st_size = 0
+        self.st_atime = 0
+        self.st_mtime = 0
+        self.st_ctime = 0
+        self.st_blocks = 0
+        self.st_blksize = 0
+        self.st_rdev = 0
+
+
+cache = {}
+def cache_get(top, path):
+    parts = path.split('/')
+    cache[('',)] = top
+    c = None
+    max = len(parts)
+    #log('cache: %r\n' % cache.keys())
+    for i in range(max):
+        pre = parts[:max-i]
+        #log('cache trying: %r\n' % pre)
+        c = cache.get(tuple(pre))
+        if c:
+            rest = parts[max-i:]
+            for r in rest:
+                #log('resolving %r from %r\n' % (r, c.fullname()))
+                c = c.lresolve(r)
+                key = tuple(pre + [r])
+                #log('saving: %r\n' % (key,))
+                cache[key] = c
+            break
+    assert(c)
+    return c
+        
+    
 
-case "$1" in
-  start)
-       # No-op
-       ;;
-  restart|reload|force-reload)
-       echo "Error: argument '$1' not supported" >&2
-       exit 3
-       ;;
-  stop|"")
-       do_stop
-       ;;
-  *)
-       echo "Usage: umountnfs.sh [start|stop]" >&2
-       exit 3
-       ;;
-esac
-
-:
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          umountroot
-# Required-Start:    umountfs
-# Required-Stop:     umountfs
-# Default-Start:     6
-# Default-Stop:
-# Short-Description: Mount the root filesystem read-only.
-### END INIT INFO
-
-PATH=/sbin:/bin
-. /lib/init/vars.sh
-
-. /lib/lsb/init-functions
-
-remount_ro () {
-       local MTPT=$1
-       [ "$VERBOSE" = no ] || log_action_begin_msg "Mounting $MTPT filesystem read-only"
-       MOUNT_FORCE_OPT=
-       [ "$(uname -s)" = "GNU/kFreeBSD" ] && MOUNT_FORCE_OPT=-f
-       # This:
-       #     mount -n -o remount,ro /
-       # will act on a bind mount of / if there is one.
-       # See #339023 and the comment in checkroot.sh
-       mount    $MOUNT_FORCE_OPT -n -o remount,ro -t dummytype dummydev $MTPT 2>/dev/null \
-       || mount $MOUNT_FORCE_OPT -n -o remount,ro              dummydev $MTPT 2>/dev/null \
-       || mount $MOUNT_FORCE_OPT -n -o remount,ro                       $MTPT
-       ES=$?
-       [ "$VERBOSE" = no ] || log_action_end_msg $ES
-}
+class BupFs(fuse.Fuse):
+    def __init__(self, top):
+        fuse.Fuse.__init__(self)
+        self.top = top
+    
+    def getattr(self, path):
+        log('--getattr(%r)\n' % path)
+        try:
+            node = cache_get(self.top, path)
+            st = Stat()
+            st.st_mode = node.mode
+            st.st_nlink = node.nlinks()
+            st.st_size = node.size()
+            st.st_mtime = node.mtime
+            st.st_ctime = node.ctime
+            st.st_atime = node.atime
+            return st
+        except vfs.NoSuchFile:
+            return -errno.ENOENT
+
+    def readdir(self, path, offset):
+        log('--readdir(%r)\n' % path)
+        node = cache_get(self.top, path)
+        yield fuse.Direntry('.')
+        yield fuse.Direntry('..')
+        for sub in node.subs():
+            yield fuse.Direntry(sub.name)
+
+    def readlink(self, path):
+        log('--readlink(%r)\n' % path)
+        node = cache_get(self.top, path)
+        return node.readlink()
+
+    def open(self, path, flags):
+        log('--open(%r)\n' % path)
+        node = cache_get(self.top, path)
+        accmode = os.O_RDONLY | os.O_WRONLY | os.O_RDWR
+        if (flags & accmode) != os.O_RDONLY:
+            return -errno.EACCES
+        node.open()
+
+    def release(self, path, flags):
+        log('--release(%r)\n' % path)
+
+    def read(self, path, size, offset):
+        log('--read(%r)\n' % path)
+        n = cache_get(self.top, path)
+        o = n.open()
+        o.seek(offset)
+        return o.read(size)
+
+
+if not hasattr(fuse, '__version__'):
+    raise RuntimeError, "your fuse module is too old for fuse.__version__"
+fuse.fuse_python_api = (0, 2)
+
+
+optspec = """
+bup fuse [-d] [-f] <mountpoint>
+--
+d,debug   increase debug level
+f,foreground  run in foreground
+"""
+o = options.Options('bup fuse', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if len(extra) != 1:
+    o.fatal("exactly one argument expected")
+
+git.check_repo_or_die()
+top = vfs.RefList(None)
+f = BupFs(top)
+f.fuse_args.mountpoint = extra[0]
+if opt.debug:
+    f.fuse_args.add('debug')
+if opt.foreground:
+    f.fuse_args.setmod('foreground')
+print f.multithreaded
+f.multithreaded = False
+
+f.main()
+#!/usr/bin/env python
+from bup import git, options, client
+from bup.helpers import *
+
+optspec = """
+[BUP_DIR=...] bup init [-r host:path]
+--
+r,remote=  remote repository path
+"""
+o = options.Options('bup init', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if extra:
+    o.fatal("no arguments expected")
+
+
+if opt.remote:
+    git.init_repo()  # local repo
+    git.check_repo_or_die()
+    cli = client.Client(opt.remote, create=True)
+    cli.close()
+else:
+    git.init_repo()
+#!/usr/bin/env python
+import sys, math, struct, glob
+from bup import options, git
+from bup.helpers import *
+
+PAGE_SIZE=4096
+SHA_PER_PAGE=PAGE_SIZE/200.
+
+
+def merge(idxlist, bits, table):
+    count = 0
+    for e in git.idxmerge(idxlist):
+        count += 1
+        prefix = git.extract_bits(e, bits)
+        table[prefix] = count
+        yield e
+
+
+def do_midx(outdir, outfilename, infilenames):
+    if not outfilename:
+        assert(outdir)
+        sum = Sha1('\0'.join(infilenames)).hexdigest()
+        outfilename = '%s/midx-%s.midx' % (outdir, sum)
+    
+    inp = []
+    total = 0
+    for name in infilenames:
+        ix = git.PackIdx(name)
+        inp.append(ix)
+        total += len(ix)
+
+    log('Merging %d indexes (%d objects).\n' % (len(infilenames), total))
+    if (not opt.force and (total < 1024 and len(infilenames) < 3)) \
+       or (opt.force and not total):
+        log('midx: nothing to do.\n')
+        return
+
+    pages = int(total/SHA_PER_PAGE) or 1
+    bits = int(math.ceil(math.log(pages, 2)))
+    entries = 2**bits
+    log('Table size: %d (%d bits)\n' % (entries*4, bits))
+    
+    table = [0]*entries
+
+    try:
+        os.unlink(outfilename)
+    except OSError:
+        pass
+    f = open(outfilename + '.tmp', 'w+')
+    f.write('MIDX\0\0\0\2')
+    f.write(struct.pack('!I', bits))
+    assert(f.tell() == 12)
+    f.write('\0'*4*entries)
+    
+    for e in merge(inp, bits, table):
+        f.write(e)
+        
+    f.write('\0'.join(os.path.basename(p) for p in infilenames))
+
+    f.seek(12)
+    f.write(struct.pack('!%dI' % entries, *table))
+    f.close()
+    os.rename(outfilename + '.tmp', outfilename)
+
+    # this is just for testing
+    if 0:
+        p = git.PackMidx(outfilename)
+        assert(len(p.idxnames) == len(infilenames))
+        print p.idxnames
+        assert(len(p) == total)
+        pi = iter(p)
+        for i in merge(inp, total, bits, table):
+            assert(i == pi.next())
+            assert(p.exists(i))
+
+    print outfilename
+
+optspec = """
+bup midx [options...] <idxnames...>
+--
+o,output=  output midx filename (default: auto-generated)
+a,auto     automatically create .midx from any unindexed .idx files
+f,force    automatically create .midx from *all* .idx files
+"""
+o = options.Options('bup midx', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if extra and (opt.auto or opt.force):
+    o.fatal("you can't use -f/-a and also provide filenames")
+
+git.check_repo_or_die()
+
+if extra:
+    do_midx(git.repo('objects/pack'), opt.output, extra)
+elif opt.auto or opt.force:
+    paths = [git.repo('objects/pack')]
+    paths += glob.glob(git.repo('index-cache/*/.'))
+    for path in paths:
+        log('midx: scanning %s\n' % path)
+        if opt.force:
+            do_midx(path, opt.output, glob.glob('%s/*.idx' % path))
+        elif opt.auto:
+            m = git.PackIdxList(path)
+            needed = {}
+            for pack in m.packs:  # only .idx files without a .midx are open
+                if pack.name.endswith('.idx'):
+                    needed[pack.name] = 1
+            del m
+            do_midx(path, opt.output, needed.keys())
+        log('\n')
+else:
+    o.fatal("you must use -f or -a or provide input filenames")
+#!/usr/bin/env python
+import sys, os, random
+from bup import options
+from bup.helpers import *
+
+
+def randblock(n):
+    l = []
+    for i in xrange(n):
+        l.append(chr(random.randrange(0,256)))
+    return ''.join(l)
+
+
+optspec = """
+bup damage [-n count] [-s maxsize] [-S seed] <filenames...>
+--
+   WARNING: THIS COMMAND IS EXTREMELY DANGEROUS
+n,num=   number of blocks to damage
+s,size=  maximum size of each damaged block
+percent= maximum size of each damaged block (as a percent of entire file)
+equal    spread damage evenly throughout the file
+S,seed=  random number seed (for repeatable tests)
+"""
+o = options.Options('bup damage', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if not extra:
+    o.fatal('filenames expected')
+
+if opt.seed != None:
+    random.seed(opt.seed)
+
+for name in extra:
+    log('Damaging "%s"...\n' % name)
+    f = open(name, 'r+b')
+    st = os.fstat(f.fileno())
+    size = st.st_size
+    if opt.percent or opt.size:
+        ms1 = int(float(opt.percent or 0)/100.0*size) or size
+        ms2 = opt.size or size
+        maxsize = min(ms1, ms2)
+    else:
+        maxsize = 1
+    chunks = opt.num or 10
+    chunksize = size/chunks
+    for r in range(chunks):
+        sz = random.randrange(1, maxsize+1)
+        if sz > size:
+            sz = size
+        if opt.equal:
+            ofs = r*chunksize
+        else:
+            ofs = random.randrange(0, size - sz + 1)
+        log('  %6d bytes at %d\n' % (sz, ofs))
+        f.seek(ofs)
+        f.write(randblock(sz))
+    f.close()
+#!/usr/bin/env python
+import sys, struct, mmap
+from bup import options, git
+from bup.helpers import *
+
+suspended_w = None
+
+
+def init_dir(conn, arg):
+    git.init_repo(arg)
+    log('bup server: bupdir initialized: %r\n' % git.repodir)
+    conn.ok()
+
+
+def set_dir(conn, arg):
+    git.check_repo_or_die(arg)
+    log('bup server: bupdir is %r\n' % git.repodir)
+    conn.ok()
 
-do_stop () {
-       # These directories must exist on the root filesystem as they are
-       # targets for system mountpoints.  We've just unmounted all other
-       # filesystems, so either they are mounted now (in which case the
-       # mount point exists) or we can make the mountpoint.
-       for dir in /proc /sys /var/run /var/lock; do
-           mkdir -p $dir || true
-       done
-       exec 9<&0 < /proc/mounts
-
-       REG_MTPTS=""
-       TMPFS_MTPTS=""
-       while read DEV MTPT FSTYPE REST
-       do
-               case "$MTPT" in
-                 /proc|/dev|/.dev|/dev/pts|/dev/shm|/proc/*|/sys|/var/run|/var/lock)
-                       continue
-                       ;;
-               esac
-               case "$FSTYPE" in 
-                 proc|procfs|linprocfs|devfs|sysfs|usbfs|usbdevfs|devpts|tmpfs)
-                       continue
-                       ;;
-                 *)
-                       remount_ro $MTPT
-                       ;;
-               esac
-       done
-
-       exec 0<&9 9<&-
+    
+def list_indexes(conn, junk):
+    git.check_repo_or_die()
+    for f in os.listdir(git.repo('objects/pack')):
+        if f.endswith('.idx'):
+            conn.write('%s\n' % f)
+    conn.ok()
+
+
+def send_index(conn, name):
+    git.check_repo_or_die()
+    assert(name.find('/') < 0)
+    assert(name.endswith('.idx'))
+    idx = git.PackIdx(git.repo('objects/pack/%s' % name))
+    conn.write(struct.pack('!I', len(idx.map)))
+    conn.write(idx.map)
+    conn.ok()
+
+
+def receive_objects(conn, junk):
+    global suspended_w
+    git.check_repo_or_die()
+    suggested = {}
+    if suspended_w:
+        w = suspended_w
+        suspended_w = None
+    else:
+        w = git.PackWriter()
+    while 1:
+        ns = conn.read(4)
+        if not ns:
+            w.abort()
+            raise Exception('object read: expected length header, got EOF\n')
+        n = struct.unpack('!I', ns)[0]
+        #log('expecting %d bytes\n' % n)
+        if not n:
+            log('bup server: received %d object%s.\n' 
+                % (w.count, w.count!=1 and "s" or ''))
+            fullpath = w.close()
+            if fullpath:
+                (dir, name) = os.path.split(fullpath)
+                conn.write('%s.idx\n' % name)
+            conn.ok()
+            return
+        elif n == 0xffffffff:
+            log('bup server: receive-objects suspended.\n')
+            suspended_w = w
+            conn.ok()
+            return
+            
+        buf = conn.read(n)  # object sizes in bup are reasonably small
+        #log('read %d bytes\n' % n)
+        if len(buf) < n:
+            w.abort()
+            raise Exception('object read: expected %d bytes, got %d\n'
+                            % (n, len(buf)))
+        (type, content) = git._decode_packobj(buf)
+        sha = git.calc_hash(type, content)
+        oldpack = w.exists(sha)
+        # FIXME: we only suggest a single index per cycle, because the client
+        # is currently dumb to download more than one per cycle anyway.
+        # Actually we should fix the client, but this is a minor optimization
+        # on the server side.
+        if not suggested and \
+          oldpack and (oldpack == True or oldpack.endswith('.midx')):
+            # FIXME: we shouldn't really have to know about midx files
+            # at this layer.  But exists() on a midx doesn't return the
+            # packname (since it doesn't know)... probably we should just
+            # fix that deficiency of midx files eventually, although it'll
+            # make the files bigger.  This method is certainly not very
+            # efficient.
+            w.objcache.refresh(skip_midx = True)
+            oldpack = w.objcache.exists(sha)
+            log('new suggestion: %r\n' % oldpack)
+            assert(oldpack)
+            assert(oldpack != True)
+            assert(not oldpack.endswith('.midx'))
+            w.objcache.refresh(skip_midx = False)
+        if not suggested and oldpack:
+            assert(oldpack.endswith('.idx'))
+            (dir,name) = os.path.split(oldpack)
+            if not (name in suggested):
+                log("bup server: suggesting index %s\n" % name)
+                conn.write('index %s\n' % name)
+                suggested[name] = 1
+        else:
+            w._raw_write([buf])
+    # NOTREACHED
+
+
+def read_ref(conn, refname):
+    git.check_repo_or_die()
+    r = git.read_ref(refname)
+    conn.write('%s\n' % (r or '').encode('hex'))
+    conn.ok()
+
+
+def update_ref(conn, refname):
+    git.check_repo_or_die()
+    newval = conn.readline().strip()
+    oldval = conn.readline().strip()
+    git.update_ref(refname, newval.decode('hex'), oldval.decode('hex'))
+    conn.ok()
+
+
+def cat(conn, id):
+    git.check_repo_or_die()
+    try:
+        for blob in git.cat(id):
+            conn.write(struct.pack('!I', len(blob)))
+            conn.write(blob)
+    except KeyError, e:
+        log('server: error: %s\n' % e)
+        conn.write('\0\0\0\0')
+        conn.error(e)
+    else:
+        conn.write('\0\0\0\0')
+        conn.ok()
+
+
+optspec = """
+bup server
+"""
+o = options.Options('bup server', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if extra:
+    o.fatal('no arguments expected')
+
+log('bup server: reading from stdin.\n')
+
+commands = {
+    'init-dir': init_dir,
+    'set-dir': set_dir,
+    'list-indexes': list_indexes,
+    'send-index': send_index,
+    'receive-objects': receive_objects,
+    'read-ref': read_ref,
+    'update-ref': update_ref,
+    'cat': cat,
 }
 
-case "$1" in
-  start)
-       # No-op
-       ;;
-  restart|reload|force-reload)
-       echo "Error: argument '$1' not supported" >&2
-       exit 3
-       ;;
-  stop)
-       do_stop
-       ;;
-  *)
-       echo "Usage: $0 start|stop" >&2
-       exit 3
-       ;;
-esac
-
-:
-#! /bin/sh
-#
-# skeleton     example file to build /etc/init.d/ scripts.
-#              This file should be used to construct scripts for /etc/init.d.
-#
-#              Written by Miquel van Smoorenburg <miquels@cistron.nl>.
-#              Modified for Debian 
-#              by Ian Murdock <imurdock@gnu.ai.mit.edu>.
+# FIXME: this protocol is totally lame and not at all future-proof.
+# (Especially since we abort completely as soon as *anything* bad happens)
+conn = Conn(sys.stdin, sys.stdout)
+lr = linereader(conn)
+for _line in lr:
+    line = _line.strip()
+    if not line:
+        continue
+    log('bup server: command: %r\n' % line)
+    words = line.split(' ', 1)
+    cmd = words[0]
+    rest = len(words)>1 and words[1] or ''
+    if cmd == 'quit':
+        break
+    else:
+        cmd = commands.get(cmd)
+        if cmd:
+            cmd(conn, rest)
+        else:
+            raise Exception('unknown server command: %r\n' % line)
+
+log('bup server: done\n')
+#!/usr/bin/env python
+import sys, time, struct
+from bup import hashsplit, git, options, client
+from bup.helpers import *
+from subprocess import PIPE
+
+
+optspec = """
+bup join [-r host:path] [refs or hashes...]
+--
+r,remote=  remote repository path
+"""
+o = options.Options('bup join', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+git.check_repo_or_die()
+
+if not extra:
+    extra = linereader(sys.stdin)
+
+ret = 0
+
+if opt.remote:
+    cli = client.Client(opt.remote)
+    cat = cli.cat
+else:
+    cp = git.CatPipe()
+    cat = cp.join
+
+for id in extra:
+    try:
+        for blob in cat(id):
+            sys.stdout.write(blob)
+    except KeyError, e:
+        sys.stdout.flush()
+        log('error: %s\n' % e)
+        ret = 1
+
+sys.exit(ret)
+#!/usr/bin/env python
+import sys, re, errno, stat, time, math
+from bup import hashsplit, git, options, index, client
+from bup.helpers import *
+
+
+optspec = """
+bup save [-tc] [-n name] <filenames...>
+--
+r,remote=  remote repository path
+t,tree     output a tree id
+c,commit   output a commit id
+n,name=    name of backup set to update (if any)
+v,verbose  increase log output (can be used more than once)
+q,quiet    don't show progress meter
+smaller=   only back up files smaller than n bytes
+"""
+o = options.Options('bup save', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+git.check_repo_or_die()
+if not (opt.tree or opt.commit or opt.name):
+    o.fatal("use one or more of -t, -c, -n")
+if not extra:
+    o.fatal("no filenames given")
+
+opt.progress = (istty and not opt.quiet)
+opt.smaller = parse_num(opt.smaller or 0)
+
+is_reverse = os.environ.get('BUP_SERVER_REVERSE')
+if is_reverse and opt.remote:
+    o.fatal("don't use -r in reverse mode; it's automatic")
+
+refname = opt.name and 'refs/heads/%s' % opt.name or None
+if opt.remote or is_reverse:
+    cli = client.Client(opt.remote)
+    oldref = refname and cli.read_ref(refname) or None
+    w = cli.new_packwriter()
+else:
+    cli = None
+    oldref = refname and git.read_ref(refname) or None
+    w = git.PackWriter()
+
+handle_ctrl_c()
+
+
+def eatslash(dir):
+    if dir.endswith('/'):
+        return dir[:-1]
+    else:
+        return dir
+
+
+parts = ['']
+shalists = [[]]
+
+def _push(part):
+    assert(part)
+    parts.append(part)
+    shalists.append([])
+
+def _pop(force_tree):
+    assert(len(parts) >= 1)
+    part = parts.pop()
+    shalist = shalists.pop()
+    tree = force_tree or w.new_tree(shalist)
+    if shalists:
+        shalists[-1].append(('40000', part, tree))
+    else:  # this was the toplevel, so put it back for sanity
+        shalists.append(shalist)
+    return tree
+
+lastremain = None
+def progress_report(n):
+    global count, subcount, lastremain
+    subcount += n
+    cc = count + subcount
+    pct = total and (cc*100.0/total) or 0
+    now = time.time()
+    elapsed = now - tstart
+    kps = elapsed and int(cc/1024./elapsed)
+    kps_frac = 10 ** int(math.log(kps+1, 10) - 1)
+    kps = int(kps/kps_frac)*kps_frac
+    if cc:
+        remain = elapsed*1.0/cc * (total-cc)
+    else:
+        remain = 0.0
+    if (lastremain and (remain > lastremain)
+          and ((remain - lastremain)/lastremain < 0.05)):
+        remain = lastremain
+    else:
+        lastremain = remain
+    hours = int(remain/60/60)
+    mins = int(remain/60 - hours*60)
+    secs = int(remain - hours*60*60 - mins*60)
+    if elapsed < 30:
+        remainstr = ''
+        kpsstr = ''
+    else:
+        kpsstr = '%dk/s' % kps
+        if hours:
+            remainstr = '%dh%dm' % (hours, mins)
+        elif mins:
+            remainstr = '%dm%d' % (mins, secs)
+        else:
+            remainstr = '%ds' % secs
+    progress('Saving: %.2f%% (%d/%dk, %d/%d files) %s %s\r'
+             % (pct, cc/1024, total/1024, fcount, ftotal,
+                remainstr, kpsstr))
+
+
+r = index.Reader(git.repo('bupindex'))
+
+def already_saved(ent):
+    return ent.is_valid() and w.exists(ent.sha) and ent.sha
+
+def wantrecurse_pre(ent):
+    return not already_saved(ent)
+
+def wantrecurse_during(ent):
+    return not already_saved(ent) or ent.sha_missing()
+
+total = ftotal = 0
+if opt.progress:
+    for (transname,ent) in r.filter(extra, wantrecurse=wantrecurse_pre):
+        if not (ftotal % 10024):
+            progress('Reading index: %d\r' % ftotal)
+        exists = ent.exists()
+        hashvalid = already_saved(ent)
+        ent.set_sha_missing(not hashvalid)
+        if not opt.smaller or ent.size < opt.smaller:
+            if exists and not hashvalid:
+                total += ent.size
+        ftotal += 1
+    progress('Reading index: %d, done.\n' % ftotal)
+    hashsplit.progress_callback = progress_report
+
+tstart = time.time()
+count = subcount = fcount = 0
+lastskip_name = None
+lastdir = ''
+for (transname,ent) in r.filter(extra, wantrecurse=wantrecurse_during):
+    (dir, file) = os.path.split(ent.name)
+    exists = (ent.flags & index.IX_EXISTS)
+    hashvalid = already_saved(ent)
+    wasmissing = ent.sha_missing()
+    oldsize = ent.size
+    if opt.verbose:
+        if not exists:
+            status = 'D'
+        elif not hashvalid:
+            if ent.sha == index.EMPTY_SHA:
+                status = 'A'
+            else:
+                status = 'M'
+        else:
+            status = ' '
+        if opt.verbose >= 2:
+            log('%s %-70s\n' % (status, ent.name))
+        elif not stat.S_ISDIR(ent.mode) and lastdir != dir:
+            if not lastdir.startswith(dir):
+                log('%s %-70s\n' % (status, os.path.join(dir, '')))
+            lastdir = dir
+
+    if opt.progress:
+        progress_report(0)
+    fcount += 1
+    
+    if not exists:
+        continue
+    if opt.smaller and ent.size >= opt.smaller:
+        if exists and not hashvalid:
+            add_error('skipping large file "%s"' % ent.name)
+            lastskip_name = ent.name
+        continue
+
+    assert(dir.startswith('/'))
+    dirp = dir.split('/')
+    while parts > dirp:
+        _pop(force_tree = None)
+    if dir != '/':
+        for part in dirp[len(parts):]:
+            _push(part)
+
+    if not file:
+        # no filename portion means this is a subdir.  But
+        # sub/parentdirectories already handled in the pop/push() part above.
+        oldtree = already_saved(ent) # may be None
+        newtree = _pop(force_tree = oldtree)
+        if not oldtree:
+            if lastskip_name and lastskip_name.startswith(ent.name):
+                ent.invalidate()
+            else:
+                ent.validate(040000, newtree)
+            ent.repack()
+        if exists and wasmissing:
+            count += oldsize
+        continue
+
+    # it's not a directory
+    id = None
+    if hashvalid:
+        mode = '%o' % ent.gitmode
+        id = ent.sha
+        shalists[-1].append((mode, 
+                             git.mangle_name(file, ent.mode, ent.gitmode),
+                             id))
+    else:
+        if stat.S_ISREG(ent.mode):
+            try:
+                f = hashsplit.open_noatime(ent.name)
+            except IOError, e:
+                add_error(e)
+                lastskip_name = ent.name
+            except OSError, e:
+                add_error(e)
+                lastskip_name = ent.name
+            else:
+                (mode, id) = hashsplit.split_to_blob_or_tree(w, [f])
+        else:
+            if stat.S_ISDIR(ent.mode):
+                assert(0)  # handled above
+            elif stat.S_ISLNK(ent.mode):
+                try:
+                    rl = os.readlink(ent.name)
+                except OSError, e:
+                    add_error(e)
+                    lastskip_name = ent.name
+                except IOError, e:
+                    add_error(e)
+                    lastskip_name = ent.name
+                else:
+                    (mode, id) = ('120000', w.new_blob(rl))
+            else:
+                add_error(Exception('skipping special file "%s"' % ent.name))
+                lastskip_name = ent.name
+        if id:
+            ent.validate(int(mode, 8), id)
+            ent.repack()
+            shalists[-1].append((mode,
+                                 git.mangle_name(file, ent.mode, ent.gitmode),
+                                 id))
+    if exists and wasmissing:
+        count += oldsize
+        subcount = 0
+
+
+if opt.progress:
+    pct = total and count*100.0/total or 100
+    progress('Saving: %.2f%% (%d/%dk, %d/%d files), done.    \n'
+             % (pct, count/1024, total/1024, fcount, ftotal))
+
+while len(parts) > 1:
+    _pop(force_tree = None)
+assert(len(shalists) == 1)
+tree = w.new_tree(shalists[-1])
+if opt.tree:
+    print tree.encode('hex')
+if opt.commit or opt.name:
+    msg = 'bup save\n\nGenerated by command:\n%r' % sys.argv
+    ref = opt.name and ('refs/heads/%s' % opt.name) or None
+    commit = w.new_commit(oldref, tree, msg)
+    if opt.commit:
+        print commit.encode('hex')
+
+w.close()  # must close before we can update the ref
+        
+if opt.name:
+    if cli:
+        cli.update_ref(refname, commit, oldref)
+    else:
+        git.update_ref(refname, commit, oldref)
+
+if cli:
+    cli.close()
+
+if saved_errors:
+    log('WARNING: %d errors encountered while saving.\n' % len(saved_errors))
+    sys.exit(1)
+#!/usr/bin/env python
+import sys, time
+from bup import options
+
+optspec = """
+bup tick
+"""
+o = options.Options('bup tick', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if extra:
+    o.fatal("no arguments expected")
+
+t = time.time()
+tleft = 1 - (t - int(t))
+time.sleep(tleft)
+#!/usr/bin/env python
+import os, sys, stat, time
+from bup import options, git, index, drecurse
+from bup.helpers import *
+
+
+def merge_indexes(out, r1, r2):
+    for e in index.MergeIter([r1, r2]):
+        # FIXME: shouldn't we remove deleted entries eventually?  When?
+        out.add_ixentry(e)
+
+
+class IterHelper:
+    def __init__(self, l):
+        self.i = iter(l)
+        self.cur = None
+        self.next()
+
+    def next(self):
+        try:
+            self.cur = self.i.next()
+        except StopIteration:
+            self.cur = None
+        return self.cur
+
+
+def check_index(reader):
+    try:
+        log('check: checking forward iteration...\n')
+        e = None
+        d = {}
+        for e in reader.forward_iter():
+            if e.children_n:
+                if opt.verbose:
+                    log('%08x+%-4d %r\n' % (e.children_ofs, e.children_n,
+                                            e.name))
+                assert(e.children_ofs)
+                assert(e.name.endswith('/'))
+                assert(not d.get(e.children_ofs))
+                d[e.children_ofs] = 1
+            if e.flags & index.IX_HASHVALID:
+                assert(e.sha != index.EMPTY_SHA)
+                assert(e.gitmode)
+        assert(not e or e.name == '/')  # last entry is *always* /
+        log('check: checking normal iteration...\n')
+        last = None
+        for e in reader:
+            if last:
+                assert(last > e.name)
+            last = e.name
+    except:
+        log('index error! at %r\n' % e)
+        raise
+    log('check: passed.\n')
+
+
+def update_index(top):
+    ri = index.Reader(indexfile)
+    wi = index.Writer(indexfile)
+    rig = IterHelper(ri.iter(name=top))
+    tstart = int(time.time())
+
+    hashgen = None
+    if opt.fake_valid:
+        def hashgen(name):
+            return (0100644, index.FAKE_SHA)
+
+    total = 0
+    for (path,pst) in drecurse.recursive_dirlist([top], xdev=opt.xdev):
+        if opt.verbose>=2 or (opt.verbose==1 and stat.S_ISDIR(pst.st_mode)):
+            sys.stdout.write('%s\n' % path)
+            sys.stdout.flush()
+            progress('Indexing: %d\r' % total)
+        elif not (total % 128):
+            progress('Indexing: %d\r' % total)
+        total += 1
+        while rig.cur and rig.cur.name > path:  # deleted paths
+            if rig.cur.exists():
+                rig.cur.set_deleted()
+                rig.cur.repack()
+            rig.next()
+        if rig.cur and rig.cur.name == path:    # paths that already existed
+            if pst:
+                rig.cur.from_stat(pst, tstart)
+            if not (rig.cur.flags & index.IX_HASHVALID):
+                if hashgen:
+                    (rig.cur.gitmode, rig.cur.sha) = hashgen(path)
+                    rig.cur.flags |= index.IX_HASHVALID
+            if opt.fake_invalid:
+                rig.cur.invalidate()
+            rig.cur.repack()
+            rig.next()
+        else:  # new paths
+            wi.add(path, pst, hashgen = hashgen)
+    progress('Indexing: %d, done.\n' % total)
+    
+    if ri.exists():
+        ri.save()
+        wi.flush()
+        if wi.count:
+            wr = wi.new_reader()
+            if opt.check:
+                log('check: before merging: oldfile\n')
+                check_index(ri)
+                log('check: before merging: newfile\n')
+                check_index(wr)
+            mi = index.Writer(indexfile)
+            merge_indexes(mi, ri, wr)
+            ri.close()
+            mi.close()
+            wr.close()
+        wi.abort()
+    else:
+        wi.close()
+
+
+optspec = """
+bup index <-p|m|u> [options...] <filenames...>
+--
+p,print    print the index entries for the given names (also works with -u)
+m,modified print only added/deleted/modified files (implies -p)
+s,status   print each filename with a status char (A/M/D) (implies -p)
+H,hash     print the hash for each object next to its name (implies -p)
+l,long     print more information about each file
+u,update   (recursively) update the index entries for the given filenames
+x,xdev,one-file-system  don't cross filesystem boundaries
+fake-valid mark all index entries as up-to-date even if they aren't
+fake-invalid mark all index entries as invalid
+check      carefully check index file integrity
+f,indexfile=  the name of the index file (default 'index')
+v,verbose  increase log output (can be used more than once)
+"""
+o = options.Options('bup index', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if not (opt.modified or opt['print'] or opt.status or opt.update or opt.check):
+    o.fatal('supply one or more of -p, -s, -m, -u, or --check')
+if (opt.fake_valid or opt.fake_invalid) and not opt.update:
+    o.fatal('--fake-{in,}valid are meaningless without -u')
+if opt.fake_valid and opt.fake_invalid:
+    o.fatal('--fake-valid is incompatible with --fake-invalid')
+
+git.check_repo_or_die()
+indexfile = opt.indexfile or git.repo('bupindex')
+
+handle_ctrl_c()
+
+if opt.check:
+    log('check: starting initial check.\n')
+    check_index(index.Reader(indexfile))
+
+paths = index.reduce_paths(extra)
+
+if opt.update:
+    if not paths:
+        o.fatal('update (-u) requested but no paths given')
+    for (rp,path) in paths:
+        update_index(rp)
+
+if opt['print'] or opt.status or opt.modified:
+    for (name, ent) in index.Reader(indexfile).filter(extra or ['']):
+        if (opt.modified 
+            and (ent.is_valid() or ent.is_deleted() or not ent.mode)):
+            continue
+        line = ''
+        if opt.status:
+            if ent.is_deleted():
+                line += 'D '
+            elif not ent.is_valid():
+                if ent.sha == index.EMPTY_SHA:
+                    line += 'A '
+                else:
+                    line += 'M '
+            else:
+                line += '  '
+        if opt.hash:
+            line += ent.sha.encode('hex') + ' '
+        if opt.long:
+            line += "%7s %7s " % (oct(ent.mode), oct(ent.gitmode))
+        print line + (name or './')
+
+if opt.check and (opt['print'] or opt.status or opt.modified or opt.update):
+    log('check: starting final check.\n')
+    check_index(index.Reader(indexfile))
+
+if saved_errors:
+    log('WARNING: %d errors encountered.\n' % len(saved_errors))
+    sys.exit(1)
+#!/usr/bin/env python
+import sys, os, struct
+from bup import options, helpers
+
+optspec = """
+bup rbackup-server
+--
+    This command is not intended to be run manually.
+"""
+o = options.Options('bup rbackup-server', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+if extra:
+    o.fatal('no arguments expected')
+
+# get the subcommand's argv.
+# Normally we could just pass this on the command line, but since we'll often
+# be getting called on the other end of an ssh pipe, which tends to mangle
+# argv (by sending it via the shell), this way is much safer.
+buf = sys.stdin.read(4)
+sz = struct.unpack('!I', buf)[0]
+assert(sz > 0)
+assert(sz < 1000000)
+buf = sys.stdin.read(sz)
+assert(len(buf) == sz)
+argv = buf.split('\0')
+
+# stdin/stdout are supposedly connected to 'bup server' that the caller
+# started for us (often on the other end of an ssh tunnel), so we don't want
+# to misuse them.  Move them out of the way, then replace stdout with
+# a pointer to stderr in case our subcommand wants to do something with it.
 #
-# Version:     @(#)skeleton  1.9  26-Feb-2001  miquels@cistron.nl
+# It might be nice to do the same with stdin, but my experiments showed that
+# ssh seems to make its child's stderr a readable-but-never-reads-anything
+# socket.  They really should have used shutdown(SHUT_WR) on the other end
+# of it, but probably didn't.  Anyway, it's too messy, so let's just make sure
+# anyone reading from stdin is disappointed.
 #
+# (You can't just leave stdin/stdout "not open" by closing the file
+# descriptors.  Then the next file that opens is automatically assigned 0 or 1,
+# and people *trying* to read/write stdin/stdout get screwed.)
+os.dup2(0, 3)
+os.dup2(1, 4)
+os.dup2(2, 1)
+fd = os.open('/dev/null', os.O_RDONLY)
+os.dup2(fd, 0)
+os.close(fd)
+
+os.environ['BUP_SERVER_REVERSE'] = helpers.hostname()
+os.execvp(argv[0], argv)
+sys.exit(99)
+#!/usr/bin/env python
+import sys, os, glob, subprocess, time
+from bup import options, git
+from bup.helpers import *
+
+par2_ok = 0
+nullf = open('/dev/null')
+
+def debug(s):
+    if opt.verbose:
+        log(s)
+
+def run(argv):
+    # at least in python 2.5, using "stdout=2" or "stdout=sys.stderr" below
+    # doesn't actually work, because subprocess closes fd #2 right before
+    # execing for some reason.  So we work around it by duplicating the fd
+    # first.
+    fd = os.dup(2)  # copy stderr
+    try:
+        p = subprocess.Popen(argv, stdout=fd, close_fds=False)
+        return p.wait()
+    finally:
+        os.close(fd)
+
+def par2_setup():
+    global par2_ok
+    rv = 1
+    try:
+        p = subprocess.Popen(['par2', '--help'],
+                             stdout=nullf, stderr=nullf, stdin=nullf)
+        rv = p.wait()
+    except OSError:
+        log('fsck: warning: par2 not found; disabling recovery features.\n')
+    else:
+        par2_ok = 1
+
+def parv(lvl):
+    if opt.verbose >= lvl:
+        if istty:
+            return []
+        else:
+            return ['-q']
+    else:
+        return ['-qq']
+
+def par2_generate(base):
+    return run(['par2', 'create', '-n1', '-c200'] + parv(2)
+               + ['--', base, base+'.pack', base+'.idx'])
+
+def par2_verify(base):
+    return run(['par2', 'verify'] + parv(3) + ['--', base])
+
+def par2_repair(base):
+    return run(['par2', 'repair'] + parv(2) + ['--', base])
+
+def quick_verify(base):
+    f = open(base + '.pack', 'rb')
+    f.seek(-20, 2)
+    wantsum = f.read(20)
+    assert(len(wantsum) == 20)
+    f.seek(0)
+    sum = Sha1()
+    for b in chunkyreader(f, os.fstat(f.fileno()).st_size - 20):
+        sum.update(b)
+    if sum.digest() != wantsum:
+        raise ValueError('expected %r, got %r' % (wantsum.encode('hex'),
+                                                  sum.hexdigest()))
+        
 
-PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
-DAEMON=/usr/sbin/uniconfd
-NAME=uniconfd
-DESC="UniConf daemon"
-
-test -x $DAEMON || exit 0
-
-# Include uniconf defaults if available
-if [ -f /etc/default/uniconfd ] ; then
-       . /etc/default/uniconfd
-fi
-
-DAEMON_OPTS="$UNICONFD_OPTS $UNICONFD_MOUNTS"
-
-case "$1" in
-  start)
-       echo -n "Starting $DESC: "
-       start-stop-daemon --start --quiet --pidfile /var/run/$NAME.pid \
-               --make-pidfile --background \
-               --exec $DAEMON -- -f $DAEMON_OPTS
-       if [ "$?" != "0" ]; then ERR=$?; echo; exit $ERR; fi
-       echo "$NAME."
-       ;;
-  stop)
-       echo -n "Stopping $DESC: "
-       start-stop-daemon --stop --quiet --pidfile /var/run/$NAME.pid \
-               --exec $DAEMON
-       if [ "$?" != "0" ]; then ERR=$?; echo; exit $ERR; fi
-       echo "$NAME."
-       ;;
-  #reload)
-       #
-       #       If the daemon can reload its config files on the fly
-       #       for example by sending it SIGHUP, do it here.
-       #
-       #       If the daemon responds to changes in its config file
-       #       directly anyway, make this a do-nothing entry.
-       #
-       # echo "Reloading $DESC configuration files."
-       # start-stop-daemon --stop --signal 1 --quiet --pidfile \
-       #       /var/run/$NAME.pid --exec $DAEMON
-  #;;
-  restart|force-reload)
-       #
-       #       If the "reload" option is implemented, move the "force-reload"
-       #       option to the "reload" entry above. If not, "force-reload" is
-       #       just the same as "restart".
-       #
-       echo -n "Restarting $DESC: "
-       start-stop-daemon --stop --quiet --pidfile \
-               /var/run/$NAME.pid --exec $DAEMON || exit $?
-       sleep 1
-       start-stop-daemon --start --quiet --pidfile \
-               /var/run/$NAME.pid --exec $DAEMON -- $DAEMON_OPTS
-       if [ "$?" != "0" ]; then ERR=$?; echo; exit $ERR; fi
-       echo "$NAME."
-       ;;
-  *)
-       N=/etc/init.d/$NAME
-       # echo "Usage: $N {start|stop|restart|reload|force-reload}" >&2
-       echo "Usage: $N {start|stop|restart|force-reload}" >&2
-       exit 1
-       ;;
-esac
-
-exit 0
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          urandom
-# Required-Start:    $local_fs
-# Required-Stop:     $local_fs
-# Default-Start:     S
-# Default-Stop:      0 6
-# Short-Description: Save and restore random seed between restarts.
-# Description        This script saves the random seed between restarts.
-#                    It is called from the boot, halt and reboot scripts.
-### END INIT INFO
-
-[ -c /dev/urandom ] || exit 0
-
-PATH=/usr/sbin:/usr/bin:/sbin:/bin
-SAVEDFILE=/var/lib/urandom/random-seed
-POOLSIZE=512
-[ -f /proc/sys/kernel/random/poolsize ] && POOLSIZE="$(cat /proc/sys/kernel/random/poolsize)"
-. /lib/init/vars.sh
-
-. /lib/lsb/init-functions
-
-case "$1" in
-  start|"")
-       [ "$VERBOSE" = no ] || log_action_begin_msg "Initializing random number generator"
-       # Load and then save $POOLSIZE bytes,
-       # which is the size of the entropy pool
-       if [ -f "$SAVEDFILE" ]
-       then
-               # Handle locally increased pool size
-               SAVEDSIZE="$(find "$SAVEDFILE" -printf "%s")"
-               if [ "$SAVEDSIZE" -gt "$POOLSIZE" ]
-               then
-                       [ -w /proc/sys/kernel/random/poolsize ] && echo $POOLSIZE > /proc/sys/kernel/random/poolsize
-                       POOLSIZE=$SAVEDSIZE
-               fi
-               cat "$SAVEDFILE" >/dev/urandom
-       fi
-       rm -f $SAVEDFILE
-       umask 077
-       dd if=/dev/urandom of=$SAVEDFILE bs=$POOLSIZE count=1 >/dev/null 2>&1
-       ES=$?
-       umask 022
-       [ "$VERBOSE" = no ] || log_action_end_msg $ES
-       ;;
-  stop)
-       # Carry a random seed from shut-down to start-up;
-       # see documentation in linux/drivers/char/random.c
-       [ "$VERBOSE" = no ] || log_action_begin_msg "Saving random seed"
-       umask 077
-       dd if=/dev/urandom of=$SAVEDFILE bs=$POOLSIZE count=1 >/dev/null 2>&1
-       ES=$?
-       [ "$VERBOSE" = no ] || log_action_end_msg $ES
-       ;;
-  restart|reload|force-reload)
-       echo "Error: argument '$1' not supported" >&2
-       exit 3
-       ;;
-  *)
-       echo "Usage: urandom start|stop" >&2
-       exit 3
-       ;;
-esac
-
-:
-#!/bin/sh
-
-test -x /usr/sbin/vbetool || exit 0
-set -e
-
-. /lib/lsb/init-functions
-
-test -f /etc/default/rcS && . /etc/default/rcS
-test -f /etc/default/acpi-support && . /etc/default/acpi-support
-test -f /usr/share/acpi-support/device-funcs && . /usr/share/acpi-support/device-funcs
-
-case "$1" in
- start)
-       if laptop-detect > /dev/null; then
-               LAPTOP=true;
-       fi
-
-       if [ x$LAPTOP != xtrue ]; then
-               exit 0;
-       fi
-
-        DeviceConfig
-       log_begin_msg "Saving VESA state..."
-       if [ "$SAVE_VBE_STATE" = "true" ]; then
-           if [ "$VERBOSE" = no ]; then 
-               if ! vbetool vbestate save > $VBESTATE 2>/dev/null; then
-                   log_end_msg $?
-                   exit 1
-               fi
-           else
-               if ! vbetool vbestate save > $VBESTATE ; then
-                   log_end_msg $?
-                   exit 1
-               fi
-           fi
-           log_end_msg 0
-        fi
-        ;;
- *)
-        exit 0
-        ;;
-esac
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          waitnfs
-# Required-Start:    $network $local_fs
-# Required-Stop:
-# Default-Start:     S
-# Default-Stop:
-# Short-Description: Wait for critical network file systems to be mounted
-# Description:       Network file systems are mounted in the background when
-#                    interfaces are brought up; this script waits for
-#                    those among them which are critical for booting to be
-#                    mounted before carrying on.
-#                    Specifically, it will wait for file systems mounted
-#                    on /usr, /usr/*, /var, /var/* 
-#                    This script WILL NOT wait on other network file which are
-#                    mounted elsewhere!
-### END INIT INFO
-
-[ -f /etc/default/rcS ] && . /etc/default/rcS
-. /lib/lsb/init-functions
-
-do_start() {
-       [ -f /etc/fstab ] || return
-       #
-       # Read through fstab line by line, building a list of networked
-       # file systems mounted on /usr* or /var*
-       # Wait up to a fixed period of time for these file systems to mount
-       #
-
-       exec 9<&0 </etc/fstab
-
-       waitnfs=
-       while read DEV MTPT FSTYPE OPTS REST
-       do
-               case "$DEV" in
-                 ""|\#*)
-                       continue
-                       ;;
-               esac
-               case "$OPTS" in
-                 noauto|*,noauto|noauto,*|*,noauto,*)
-                       continue
-                       ;;
-               esac
-               case "$FSTYPE" in
-                 nfs|nfs4|smbfs|cifs|coda|ncp|ncpfs|ocfs2|gfs)
-                       ;;
-                 *)
-                       continue
-                       ;;
-               esac
-               case "$MTPT" in
-                 /usr/local|/usr/local/*)
-                       ;;
-                 /usr|/usr/*)
-                       waitnfs="$waitnfs $MTPT"
-                       ;;
-                 /var|/var/*)
-                       waitnfs="$waitnfs $MTPT"
-                       ;;
-               esac
-       done
-
-       exec 0<&9 9<&-
-
-       # Try mounting all networked filesystems here, just before waiting for
-       # them; background this call so as not to block startup sequence
-       /lib/init/mountall-net-fs &
-
-       # Wait for each path, the timeout is for all of them as that's
-       # really the maximum time we have to wait anyway
-       TIMEOUT=900
-       for mountpt in $waitnfs; do
-               log_action_begin_msg "Waiting for $mountpt"
-
-               while ! mountpoint -q $mountpt; do
-                       sleep 0.1
-
-                       TIMEOUT=$(( $TIMEOUT - 1 ))
-                       if [ $TIMEOUT -le 0 ]; then
-                               log_action_end_msg 1
-                               break
-                       fi
-               done
-
-               if [ $TIMEOUT -gt 0 ]; then
-                       log_action_end_msg 0
-               fi
-       done
-}
-
-case "$1" in
-    start)
-        do_start
-        ;;
-    restart|reload|force-reload)
-        echo "Error: argument '$1' not supported" >&2
-        exit 3
-        ;;
-    stop)
-        ;;
-    *)
-        echo "Usage: $0 start|stop" >&2
-        exit 3
-        ;;
-esac
-
-: exit 0
-#!/bin/sh
-
-### BEGIN INIT INFO
-# Provides:          winbind
-# Required-Start:    $network $local_fs $remote_fs
-# Required-Stop:     $network $local_fs $remote_fs
-# Default-Start:     2 3 4 5
-# Default-Stop:      0 1 6
-# Short-Description: start Winbind daemon
-### END INIT INFO
-
-
-PATH=/sbin:/bin:/usr/sbin:/usr/bin
-
-[ -r /etc/default/winbind ] && . /etc/default/winbind
-
-DAEMON=/usr/sbin/winbindd
-PIDDIR=/var/run/samba
-
-# clear conflicting settings from the environment
-unset TMPDIR
-
-# See if the daemon is there
-test -x $DAEMON || exit 0
-
-. /lib/lsb/init-functions
-
-case "$1" in
-       start)
-               log_daemon_msg "Starting the Winbind daemon" "winbind"
-
-               mkdir -p /var/run/samba/winbindd_privileged || return 1
-               chgrp winbindd_priv $PIDDIR/winbindd_privileged/ || return 1
-               chmod 0750 $PIDDIR/winbindd_privileged/ || return 1
-               start-stop-daemon --start --quiet --oknodo --exec $DAEMON -- $WINBINDD_OPTS
-
-               log_end_msg $?
-               ;;
-
-       stop)
-               log_daemon_msg "Stopping the Winbind daemon" "winbind"
-               start-stop-daemon --stop --quiet --oknodo --exec $DAEMON
-               log_end_msg $?
-               ;;
-
-       restart|force-reload)
-               $0 stop && sleep 2 && $0 start
-               ;;
-
-       *)
-               echo "Usage: /etc/init.d/winbind {start|stop|restart|force-reload}"
-               exit 1
-               ;;
-esac
-#!/bin/sh
-
-### BEGIN INIT INFO
-# Provides:            wpa-ifupdown
-# Required-Start:      $network
-# Required-Stop:       $network
-# Should-Start:
-# Should-Stop:
-# Default-Start:
-# Default-Stop:                0 6
-# Short-Description:   Stop wpa_supplicant processes started via ifupdown
-# Description:         Run ifdown on interfaces authenticated via
-#                      wpa_supplicant. Sendsigs terminates wpa_supplicant
-#                      processes before networking is stopped causing each
-#                      network interface authenticated via a wpa_supplicant
-#                      daemon to be terminated abrubtly.
-### END INIT INFO
-
-PATH=/usr/sbin:/usr/bin:/sbin:/bin
-
-test -d /var/run || exit 0
-
-test -x /sbin/ifdown || exit 0
-
-. /lib/lsb/init-functions
-
-stop_wpa_action () {
-       test -x /sbin/wpa_action || return
-       unset IFACES
-       IFACES=$(find /var/run -maxdepth 1 -type f -name 'wpa_action.*.pid' -printf '%P\n' | cut -d'.' -f2)
-       if test -n "$IFACES"; then
-               log_daemon_msg "Stopping wpa_action roaming interfaces"
-               for iface in $IFACES; do
-                       log_progress_msg "$iface"
-                       # wpa_action executes /sbin/ifdown
-                       wpa_action "$iface" stop >/dev/null 2>&1
-               done
-               log_end_msg 0
-       fi
-}
-
-stop_wpa_supplicant () {
-       unset IFACES
-       IFACES=$(find /var/run -maxdepth 1 -type f -name 'wpa_supplicant.*.pid' -printf '%P\n' | cut -d'.' -f2)
-       if test -n "$IFACES"; then
-               log_daemon_msg "Stopping wpa_supplicant interfaces"
-               for iface in $IFACES; do
-                       log_progress_msg "$iface"
-                       ifdown $iface >/dev/null 2>&1
-               done
-               log_end_msg 0
-       fi
-}
-
-case "$1" in
-       start|restart|force-reload)
-               # No-op
-               ;;
-       stop)
-               stop_wpa_action
-               stop_wpa_supplicant
-               ;;
-       *)
-               echo "Usage: $0 {start|stop|restart|force-reload}" >&2
-               exit 3
-               ;;
-esac
-
-exit 0
-#!/bin/sh
-# /etc/init.d/x11-common: set up the X server and ICE socket directories
-### BEGIN INIT INFO
-# Provides:          x11-common
-# Required-Start:    $local_fs $remote_fs
-# Required-Stop:     $local_fs $remote_fs
-# Should-Start:      $named
-# Should-Stop:       $named
-# Default-Start:     S
-# Default-Stop:
-### END INIT INFO
-
-set -e
-
-PATH=/bin:/usr/bin:/sbin:/usr/sbin
-SOCKET_DIR=/tmp/.X11-unix
-ICE_DIR=/tmp/.ICE-unix
-
-. /lib/lsb/init-functions
-if [ -f /etc/default/rcS ]; then
-  . /etc/default/rcS
-fi
-
-do_restorecon () {
-  # Restore file security context (SELinux).
-  if which restorecon >/dev/null 2>&1; then
-    restorecon "$1"
-  fi
-}
-
-set_up_socket_dir () {
-  if [ "$VERBOSE" != no ]; then
-    log_begin_msg "Setting up X server socket directory $SOCKET_DIR..."
-  fi
-  if [ -e $SOCKET_DIR ] && [ ! -d $SOCKET_DIR ]; then
-    mv $SOCKET_DIR $SOCKET_DIR.$$
-  fi
-  mkdir -p $SOCKET_DIR
-  chown 0:0 $SOCKET_DIR
-  chmod 1777 $SOCKET_DIR
-  do_restorecon $SOCKET_DIR
-  [ "$VERBOSE" != no ] && log_end_msg 0 || return 0
-}
-
-set_up_ice_dir () {
-  if [ "$VERBOSE" != no ]; then
-    log_begin_msg "Setting up ICE socket directory $ICE_DIR..."
-  fi
-  if [ -e $ICE_DIR ] && [ ! -d $ICE_DIR ]; then
-    mv $ICE_DIR $ICE_DIR.$$
-  fi
-  mkdir -p $ICE_DIR
-  chown 0:0 $ICE_DIR
-  chmod 1777 $ICE_DIR
-  do_restorecon $ICE_DIR
-  [ "$VERBOSE" != no ] && log_end_msg 0 || return 0
-}
-
-do_status () {
-    if [ -d $ICE_DIR ] && [ -d $SOCKET_DIR ]; then
-      return 0
-    else
-      return 4
-    fi
-}
-
-case "$1" in
-  start)
-    set_up_socket_dir
-    set_up_ice_dir
-  ;;
-
-  restart|reload|force-reload)
-    /etc/init.d/x11-common start
-  ;;
-
-  stop)
-   :
-  ;;
-
-  status)
-    do_status
-  ;;
-  *)
-    log_success_msg "Usage: /etc/init.d/x11-common {start|stop|status|restart|reload|force-reload}"
-    exit 1
-    ;;
-esac
-
-exit 0
-
-# vim:set ai et sts=2 sw=2 tw=0:
+def git_verify(base):
+    if opt.quick:
+        try:
+            quick_verify(base)
+        except Exception, e:
+            debug('error: %s\n' % e)
+            return 1
+        return 0
+    else:
+        return run(['git', 'verify-pack', '--', base])
+    
+    
+def do_pack(base, last):
+    code = 0
+    if par2_ok and par2_exists and (opt.repair or not opt.generate):
+        vresult = par2_verify(base)
+        if vresult != 0:
+            if opt.repair:
+                rresult = par2_repair(base)
+                if rresult != 0:
+                    print '%s par2 repair: failed (%d)' % (last, rresult)
+                    code = rresult
+                else:
+                    print '%s par2 repair: succeeded (0)' % last
+                    code = 100
+            else:
+                print '%s par2 verify: failed (%d)' % (last, vresult)
+                code = vresult
+        else:
+            print '%s ok' % last
+    elif not opt.generate or (par2_ok and not par2_exists):
+        gresult = git_verify(base)
+        if gresult != 0:
+            print '%s git verify: failed (%d)' % (last, gresult)
+            code = gresult
+        else:
+            if par2_ok and opt.generate:
+                presult = par2_generate(base)
+                if presult != 0:
+                    print '%s par2 create: failed (%d)' % (last, presult)
+                    code = presult
+                else:
+                    print '%s ok' % last
+            else:
+                print '%s ok' % last
+    else:
+        assert(opt.generate and (not par2_ok or par2_exists))
+        debug('    skipped: par2 file already generated.\n')
+    return code
+
+
+optspec = """
+bup fsck [options...] [filenames...]
+--
+r,repair    attempt to repair errors using par2 (dangerous!)
+g,generate  generate auto-repair information using par2
+v,verbose   increase verbosity (can be used more than once)
+quick       just check pack sha1sum, don't use git verify-pack
+j,jobs=     run 'n' jobs in parallel
+par2-ok     immediately return 0 if par2 is ok, 1 if not
+disable-par2  ignore par2 even if it is available
+"""
+o = options.Options('bup fsck', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+par2_setup()
+if opt.par2_ok:
+    if par2_ok:
+        sys.exit(0)  # 'true' in sh
+    else:
+        sys.exit(1)
+if opt.disable_par2:
+    par2_ok = 0
+
+git.check_repo_or_die()
+
+if not extra:
+    debug('fsck: No filenames given: checking all packs.\n')
+    extra = glob.glob(git.repo('objects/pack/*.pack'))
+
+code = 0
+count = 0
+outstanding = {}
+for name in extra:
+    if name.endswith('.pack'):
+        base = name[:-5]
+    elif name.endswith('.idx'):
+        base = name[:-4]
+    elif name.endswith('.par2'):
+        base = name[:-5]
+    elif os.path.exists(name + '.pack'):
+        base = name
+    else:
+        raise Exception('%s is not a pack file!' % name)
+    (dir,last) = os.path.split(base)
+    par2_exists = os.path.exists(base + '.par2')
+    if par2_exists and os.stat(base + '.par2').st_size == 0:
+        par2_exists = 0
+    sys.stdout.flush()
+    debug('fsck: checking %s (%s)\n' 
+          % (last, par2_ok and par2_exists and 'par2' or 'git'))
+    if not opt.verbose:
+        progress('fsck (%d/%d)\r' % (count, len(extra)))
+    
+    if not opt.jobs:
+        nc = do_pack(base, last)
+        code = code or nc
+        count += 1
+    else:
+        while len(outstanding) >= opt.jobs:
+            (pid,nc) = os.wait()
+            nc >>= 8
+            if pid in outstanding:
+                del outstanding[pid]
+                code = code or nc
+                count += 1
+        pid = os.fork()
+        if pid:  # parent
+            outstanding[pid] = 1
+        else: # child
+            try:
+                sys.exit(do_pack(base, last))
+            except Exception, e:
+                log('exception: %r\n' % e)
+                sys.exit(99)
+                
+while len(outstanding):
+    (pid,nc) = os.wait()
+    nc >>= 8
+    if pid in outstanding:
+        del outstanding[pid]
+        code = code or nc
+        count += 1
+    if not opt.verbose:
+        progress('fsck (%d/%d)\r' % (count, len(extra)))
+
+if not opt.verbose and istty:
+    log('fsck done.           \n')
+sys.exit(code)
+#!/usr/bin/env python
+import sys, os, struct, getopt, subprocess, signal
+from bup import options, ssh
+from bup.helpers import *
+
+optspec = """
+bup rbackup <hostname> index ...
+bup rbackup <hostname> save ...
+bup rbackup <hostname> split ...
+"""
+o = options.Options('bup rbackup', optspec, optfunc=getopt.getopt)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+if len(extra) < 2:
+    o.fatal('arguments expected')
+
+class SigException(Exception):
+    def __init__(self, signum):
+        self.signum = signum
+        Exception.__init__(self, 'signal %d received' % signum)
+def handler(signum, frame):
+    raise SigException(signum)
+
+signal.signal(signal.SIGTERM, handler)
+signal.signal(signal.SIGINT, handler)
+
+sp = None
+p = None
+ret = 99
+
+try:
+    hostname = extra[0]
+    argv = extra[1:]
+    p = ssh.connect(hostname, 'rbackup-server')
+
+    argvs = '\0'.join(['bup'] + argv)
+    p.stdin.write(struct.pack('!I', len(argvs)) + argvs)
+    p.stdin.flush()
+
+    main_exe = os.environ.get('BUP_MAIN_EXE') or sys.argv[0]
+    sp = subprocess.Popen([main_exe, 'server'], stdin=p.stdout, stdout=p.stdin)
+
+    p.stdin.close()
+    p.stdout.close()
+
+finally:
+    while 1:
+        # if we get a signal while waiting, we have to keep waiting, just
+        # in case our child doesn't die.
+        try:
+            ret = p.wait()
+            sp.wait()
+            break
+        except SigException, e:
+            log('\nbup rbackup: %s\n' % e)
+            os.kill(p.pid, e.signum)
+            ret = 84
+sys.exit(ret)
+#!/usr/bin/env python
+import sys, os, re
+from bup import options
+
+optspec = """
+bup newliner
+"""
+o = options.Options('bup newliner', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if extra:
+    o.fatal("no arguments expected")
+
+r = re.compile(r'([\r\n])')
+lastlen = 0
+all = ''
+while 1:
+    l = r.split(all, 1)
+    if len(l) <= 1:
+        try:
+            b = os.read(sys.stdin.fileno(), 4096)
+        except KeyboardInterrupt:
+            break
+        if not b:
+            break
+        all += b
+    else:
+        assert(len(l) == 3)
+        (line, splitchar, all) = l
+        #splitchar = '\n'
+        sys.stdout.write('%-*s%s' % (lastlen, line, splitchar))
+        if splitchar == '\r':
+            lastlen = len(line)
+        else:
+            lastlen = 0
+        sys.stdout.flush()
+
+if lastlen or all:
+    sys.stdout.write('%-*s\n' % (lastlen, all))
+#!/usr/bin/env python
+import sys
+from bup import options, git, _hashsplit
+from bup.helpers import *
+
+
+optspec = """
+bup margin
+"""
+o = options.Options('bup margin', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if extra:
+    o.fatal("no arguments expected")
+
+git.check_repo_or_die()
+#git.ignore_midx = 1
+
+mi = git.PackIdxList(git.repo('objects/pack'))
+last = '\0'*20
+longmatch = 0
+for i in mi:
+    if i == last:
+        continue
+    #assert(str(i) >= last)
+    pm = _hashsplit.bitmatch(last, i)
+    longmatch = max(longmatch, pm)
+    last = i
+print longmatch
index 13ae716417ed357d366cc543a2db14dea0629c54..afcd1f37ba621b8c453f61dd4e38a8cb40751ee4 100644 (file)
-#! /bin/sh -e
-
-# Check for daemon presence
-test -x /usr/sbin/acpid || exit 0
-
-# Check for ACPI support on kernel side
-[ -d /proc/acpi ] || exit 0
-
-# Include acpid defaults if available
-OPTIONS=""
-if [ -f /etc/default/acpid ] ; then
-       . /etc/default/acpid
-fi
-
-# Get lsb functions
-. /lib/lsb/init-functions
-. /etc/default/rcS
-
-if [ "x$VERBOSE" = "xno" ]; then
-        MODPROBE_OPTIONS="$MODPROBE_OPTIONS -Q"
-        export MODPROBE_OPTIONS
-fi
-
-# As the name says. If the kernel supports modules, it'll try to load
-# the ones listed in "MODULES".
-load_modules() {
-        PRINTK=`cat /proc/sys/kernel/printk`
-        [ "$VERBOSE" = no ] && echo "0 0 0 0" > /proc/sys/kernel/printk
+#!/usr/bin/env python
+from bup import options, drecurse
+from bup.helpers import *
+
+optspec = """
+bup drecurse <path>
+--
+x,xdev,one-file-system   don't cross filesystem boundaries
+q,quiet  don't actually print filenames
+profile  run under the python profiler
+"""
+o = options.Options('bup drecurse', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if len(extra) != 1:
+    o.fatal("exactly one filename expected")
+
+it = drecurse.recursive_dirlist(extra, opt.xdev)
+if opt.profile:
+    import cProfile
+    def do_it():
+        for i in it:
+            pass
+    cProfile.run('do_it()')
+else:
+    if opt.quiet:
+        for i in it:
+            pass
+    else:
+        for (name,st) in it:
+            print name
+
+if saved_errors:
+    log('WARNING: %d errors encountered.\n' % len(saved_errors))
+    sys.exit(1)
+#!/usr/bin/env python
+import sys, time, struct
+from bup import hashsplit, git, options, client
+from bup.helpers import *
+from subprocess import PIPE
+
+
+optspec = """
+bup split [-tcb] [-n name] [--bench] [filenames...]
+--
+r,remote=  remote repository path
+b,blobs    output a series of blob ids
+t,tree     output a tree id
+c,commit   output a commit id
+n,name=    name of backup set to update (if any)
+N,noop     don't actually save the data anywhere
+q,quiet    don't print progress messages
+v,verbose  increase log output (can be used more than once)
+copy       just copy input to output, hashsplitting along the way
+bench      print benchmark timings to stderr
+max-pack-size=  maximum bytes in a single pack
+max-pack-objects=  maximum number of objects in a single pack
+fanout=  maximum number of blobs in a single tree
+"""
+o = options.Options('bup split', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+git.check_repo_or_die()
+if not (opt.blobs or opt.tree or opt.commit or opt.name or
+        opt.noop or opt.copy):
+    o.fatal("use one or more of -b, -t, -c, -n, -N, --copy")
+if (opt.noop or opt.copy) and (opt.blobs or opt.tree or 
+                               opt.commit or opt.name):
+    o.fatal('-N is incompatible with -b, -t, -c, -n')
+
+if opt.verbose >= 2:
+    git.verbose = opt.verbose - 1
+    opt.bench = 1
+if opt.max_pack_size:
+    hashsplit.max_pack_size = parse_num(opt.max_pack_size)
+if opt.max_pack_objects:
+    hashsplit.max_pack_objects = parse_num(opt.max_pack_objects)
+if opt.fanout:
+    hashsplit.fanout = parse_num(opt.fanout)
+if opt.blobs:
+    hashsplit.fanout = 0
+
+is_reverse = os.environ.get('BUP_SERVER_REVERSE')
+if is_reverse and opt.remote:
+    o.fatal("don't use -r in reverse mode; it's automatic")
+start_time = time.time()
+
+refname = opt.name and 'refs/heads/%s' % opt.name or None
+if opt.noop or opt.copy:
+    cli = w = oldref = None
+elif opt.remote or is_reverse:
+    cli = client.Client(opt.remote)
+    oldref = refname and cli.read_ref(refname) or None
+    w = cli.new_packwriter()
+else:
+    cli = None
+    oldref = refname and git.read_ref(refname) or None
+    w = git.PackWriter()
+
+files = extra and (open(fn) for fn in extra) or [sys.stdin]
+if w:
+    shalist = hashsplit.split_to_shalist(w, files)
+    tree = w.new_tree(shalist)
+else:
+    last = 0
+    for (blob, bits) in hashsplit.hashsplit_iter(files):
+        hashsplit.total_split += len(blob)
+        if opt.copy:
+            sys.stdout.write(str(blob))
+        megs = hashsplit.total_split/1024/1024
+        if not opt.quiet and last != megs:
+            progress('%d Mbytes read\r' % megs)
+            last = megs
+    progress('%d Mbytes read, done.\n' % megs)
+
+if opt.verbose:
+    log('\n')
+if opt.blobs:
+    for (mode,name,bin) in shalist:
+        print bin.encode('hex')
+if opt.tree:
+    print tree.encode('hex')
+if opt.commit or opt.name:
+    msg = 'bup split\n\nGenerated by command:\n%r' % sys.argv
+    ref = opt.name and ('refs/heads/%s' % opt.name) or None
+    commit = w.new_commit(oldref, tree, msg)
+    if opt.commit:
+        print commit.encode('hex')
+
+if w:
+    w.close()  # must close before we can update the ref
         
-        LIST=`/sbin/lsmod|awk '!/Module/ {print $1}'`
-
-       # Get list of available modules
-        LOC="/lib/modules/`uname -r`/kernel/drivers/acpi"
-        LOC2="/lib/modules/`uname -r`/kernel/ubuntu/acpi"
-        if [ -d $LOC ]; then
-         MODAVAIL=`( find $LOC -type f -name "*.o" -printf "basename %f .o\n"; \
-               find $LOC -type f -name "*.ko" -printf "basename %f .ko\n" ) | /bin/sh`
-       else
-         MODAVAIL=""
-       fi
-
-        if [ -d $LOC2 ]; then
-         MODAVAIL="$MODAVAIL `( find $LOC2 -type f -name "*.o" -printf "basename %f .o\n"; \
-               find $LOC2 -type f -name "*.ko" -printf "basename %f .ko\n" ) | /bin/sh`"
-       fi
-
-        if [ "$MODULES" = "all" ]; then
-               MODULES="$MODAVAIL"
-        fi
-
-       if [ -n "$MODULES" ]; then
-               log_begin_msg "Loading ACPI modules..."
-               STATUS=0
-               for mod in $MODULES; do
-                       echo $MODAVAIL | grep -q -w "$mod" || continue
-                       if echo $LIST | grep -q -w "$mod"; then
-                               [ "$VERBOSE" != no ] && log_success_msg "Module already loaded: $mod"
-                       else
-                               if modprobe -b $mod 2>/dev/null; then
-                                       [ "$VERBOSE" != no ] && log_success_msg "Loaded module: $mod"
-                               else
-                                       if [ "$VERBOSE" != no ]; then
-                                               log_warning_msg "Unable to load module: $mod"
-                                       fi
-                               fi
-                       fi              
-               done
-               log_end_msg $STATUS
-       fi
-        echo "$PRINTK" > /proc/sys/kernel/printk
-}
-
-case "$1" in
-  start)
-    [ -f /proc/modules ] && load_modules
-    log_begin_msg "Starting ACPI services..."
-    start-stop-daemon --start --quiet --oknodo --exec /usr/sbin/acpid -- -c /etc/acpi/events $OPTIONS
-    log_end_msg $?
-    ;;
-  stop)
-    log_begin_msg "Stopping ACPI services..."
-    start-stop-daemon --stop --quiet --oknodo --retry 2 --exec /usr/sbin/acpid
-    log_end_msg $?
-    ;;
-  restart)
-    $0 stop
-    sleep 1
-    $0 start
-    ;;
-  reload|force-reload) 
-    log_begin_msg "Reloading ACPI services..."
-    start-stop-daemon --stop --signal 1 --exec /usr/sbin/acpid
-    log_end_msg $?
-    ;;
-  *)
-    log_success_msg "Usage: /etc/init.d/acpid {start|stop|restart|reload|force-reload}"
-    exit 1
-esac
-
-exit 0
-#!/bin/bash
-# INIT script to check whether we're on batteries, and so start with laptop 
-# mode etc enabled.
-
-# BUGS: unless we start *really* late, we have no way of throttling 
-# xscreensaver, since it won't be there to command.
-. /usr/share/acpi-support/power-funcs
-
-test -f /lib/lsb/init-functions || exit 1
-. /lib/lsb/init-functions
-
-test -d /var/lib/acpi-support || exit 0
-
-shopt -s nullglob
-
-case "$1" in
-  start)
-    log_begin_msg "Checking battery state..."
-    /etc/acpi/power.sh
-    # Source everything in /etc/acpi/start.d/
-    for SCRIPT in /etc/acpi/start.d/*.sh; do
-       . $SCRIPT
-    done
-    log_end_msg 0
-    ;;
-  stop)
-    log_begin_msg "Disabling power management..."
-    /etc/acpi/power.sh stop
-    log_end_msg 0
-    ;;
-  *)
-  ;;
-esac
-        
-
-#!/bin/sh
-#
-# alsa-utils initscript
-#
-### BEGIN INIT INFO
-# Provides:          alsa-utils
-# Required-Start:    $remote_fs
-# Required-Stop:     $remote_fs
-# Default-Start:     S
-# Default-Stop:      0 6
-# Short-Description: Restore and store ALSA driver settings
-# Description:       This script stores and restores mixer levels on
-#                    shutdown and bootup.On sysv-rc systems: to
-#                    disable storing of mixer levels on shutdown,
-#                    remove /etc/rc[06].d/K50alsa-utils.  To disable
-#                    restoring of mixer levels on bootup, rename the
-#                    "S50alsa-utils" symbolic link in /etc/rcS.d/ to
-#                    "K50alsa-utils".
-### END INIT INFO
-
-# Don't use set -e; check exit status instead
-
-# Exit silently if package is no longer installed
-[ -x /sbin/alsactl ] || exit 0
-
-PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
-MYNAME=/etc/init.d/alsa-utils
-
-. /lib/lsb/init-functions
-
-# $1 EXITSTATUS
-# [$2 MESSAGE]
-log_action_end_msg_and_exit()
-{
-       log_action_end_msg "$1" ${2:+"$2"}
-       exit $1
-}
-
-# $1 PROGRAM
-executable()
-{
-       # If which is not available then we must be running before
-       # /usr is mounted on a system that has which in /usr/bin/.
-       # Conclude that $1 is not executable.
-       [ -x /bin/which ] || [ -x /usr/bin/which ] || return 1
-       which "$1" >/dev/null 2>&1
-}
-
-# Wait for filesystems to show up
-while [ ! -d /usr/bin -o ! -d /var/lib/alsa ]; do
-       sleep 0.2
-done
-
-executable amixer || { echo "${MYNAME}: Error: No amixer program available." >&2 ; exit 1 ; }
-
-bugout() { echo "${MYNAME}: Programming error" >&2 ; exit 123 ; }
-
-# $1 <card ID> | "all"
-restore_levels()
-{
-       [ -f /var/lib/alsa/asound.state ] || return 1
-       CARD="$1"
-       [ "$1" = all ] && CARD=""
-       # Assume that if alsactl prints a message on stderr
-       # then it failed somehow.  This works around the fact
-       # that alsactl doesn't return nonzero status when it
-       # can't restore settings for the card
-       if MSG="$(alsactl restore $CARD 2>&1 >/dev/null)" && [ ! "$MSG" ] ; then
-               return 0
-       else
-               # Retry with the "force" option.  This restores more levels
-               # but it results in much longer error messages.
-               alsactl -F restore $CARD >/dev/null 2>&1
-               [ -z "$CARD" ] && log_action_cont_msg "warning: 'alsactl restore' failed with error message '$MSG'"
-               return 1
-       fi
-}
-
-# $1 <card ID> | "all"
-store_levels()
-{
-       CARD="$1"
-       [ "$1" = all ] && CARD=""
-       if MSG="$(alsactl store $CARD 2>&1)" ; then
-               sleep 1
-               return 0
-       else
-               [ -z "$CARD" ] && log_action_cont_msg "warning: 'alsactl store' failed with error message '$MSG'"
-               return 1
-       fi
-}
-
-echo_card_indices()
-{
-       if [ -f /proc/asound/cards ] ; then
-               sed -n -e's/^[[:space:]]*\([0-7]\)[[:space:]].*/\1/p' /proc/asound/cards
-       fi
-}
-
-filter_amixer_output()
-{
-       sed \
-               -e '/Unable to find simple control/d' \
-               -e '/Unknown playback setup/d' \
-               -e '/^$/d'
-}
-
-# The following functions try to set many controls.
-# No card has all the controls and so some of the attempts are bound to fail.
-# Because of this, the functions can't return useful status values.
-
-# $1 <control>
-# $2 <level>
-# $CARDOPT
-unmute_and_set_level()
-{
-       { [ "$2" ] && [ "$CARDOPT" ] ; } || bugout
-       amixer $CARDOPT -q set "$1" "$2" unmute 2>&1 | filter_amixer_output || :
-       return 0
-}
-
-# $1 <control>
-# $CARDOPT
-mute_and_zero_level()
-{
-       { [ "$1" ] && [ "$CARDOPT" ] ; } || bugout
-       amixer $CARDOPT -q set "$1" "0%" mute 2>&1 | filter_amixer_output || :
-       return 0
-}
-
-# $1 <control>
-# $2 "on" | "off"
-# $CARDOPT
-switch_control()
-{
-       { [ "$2" ] && [ "$CARDOPT" ] ; } || bugout
-       amixer $CARDOPT -q set "$1" "$2" 2>&1 | filter_amixer_output || :
-       return 0
-}
-
-# $1 <card ID>
-sanify_levels_on_card()
-{
-       CARDOPT="-c $1"
-
-       unmute_and_set_level "Front" "80%"
-       unmute_and_set_level "Master" "80%"
-       unmute_and_set_level "Master Mono" "80%"   # See Bug#406047
-       unmute_and_set_level "Master Digital" "80%"   # E.g., cs4237B
-       unmute_and_set_level "Playback" "80%"
-       unmute_and_set_level "Headphone" "70%"
-       unmute_and_set_level "PCM" "80%"
-       unmute_and_set_level "PCM,1" "80%"   # E.g., ess1969
-       unmute_and_set_level "DAC" "80%"     # E.g., envy24, cs46xx
-       unmute_and_set_level "DAC,0" "80%"   # E.g., envy24
-       unmute_and_set_level "DAC,1" "80%"   # E.g., envy24
-       unmute_and_set_level "Synth" "80%"
-       unmute_and_set_level "CD" "80%"
-
-       mute_and_zero_level "Mic"
-       mute_and_zero_level "IEC958"         # Ubuntu #19648
-
-       # Intel P4P800-MX  (Ubuntu bug #5813)
-       switch_control "Master Playback Switch" on
-       switch_control "Master Surround" on
-
-       # Trident/YMFPCI/emu10k1:
-       unmute_and_set_level "Wave" "80%"
-       unmute_and_set_level "Music" "80%"
-       unmute_and_set_level "AC97" "80%"
-
-       # DRC:
-       unmute_and_set_level "Dynamic Range Compression" "80%"
-
-       # Required for HDA Intel (hda-intel):
-       unmute_and_set_level "Front" "80%"
-
-       # Required for SB Live 7.1/24-bit (ca0106):
-       unmute_and_set_level "Analog Front" "80%"
-
-       # Required at least for Via 823x hardware on DFI K8M800-MLVF Motherboard with kernels 2.6.10-3/4 (see ubuntu #7286):
-       switch_control "IEC958 Capture Monitor" off
-
-       # Required for hardware allowing toggles for AC97 through IEC958,
-       #  valid values are 0, 1, 2, 3. Needs to be set to 0 for PCM1.
-       unmute_and_set_level "IEC958 Playback AC97-SPSA" "0"
-
-       # Required for newer Via hardware (see Ubuntu #31784)
-       unmute_and_set_level "VIA DXS,0" "80%"
-       unmute_and_set_level "VIA DXS,1" "80%"
-       unmute_and_set_level "VIA DXS,2" "80%"
-       unmute_and_set_level "VIA DXS,3" "80%"
-
-       # Required on some notebooks with ICH4:
-       switch_control "Headphone Jack Sense" off
-       switch_control "Line Jack Sense" off
-
-       # Some machines need one or more of these to be on;
-       # others need one or more of these to be off:
-       #
-       # switch_control "External Amplifier" on
-       switch_control "Audigy Analog/Digital Output Jack" on
-       switch_control "SB Live Analog/Digital Output Jack" on
-       
-       # D1984 -- Thinkpad T61/X61
-       switch_control "Speaker" on
-       switch_control "Headphone" on
-
-       # HDA-Intel w/ "Digital" capture mixer (See Ubuntu #193823)
-       unmute_and_set_level "Digital" "80%"
-
-       return 0
-}
-
-# $1 <card ID> | "all"
-sanify_levels()
-{
-       TTSDML_RETURNSTATUS=0
-       case "$1" in
-         all)
-               for CARD in $(echo_card_indices) ; do
-                       sanify_levels_on_card "$CARD" || TTSDML_RETURNSTATUS=1
-               done
-               ;;
-         *)
-               sanify_levels_on_card "$1" || TTSDML_RETURNSTATUS=1
-               ;;
-       esac
-       return $TTSDML_RETURNSTATUS
-}
-
-# $1 <card ID>
-preinit_levels_on_card()
-{
-       CARDOPT="-c $1"
-
-       # Silly dance to activate internal speakers by default on PowerMac
-       # Snapper and Tumbler
-       id=`cat /proc/asound/card$1/id 2>/dev/null`
-       if [ "$id" = "Snapper" -o "$id" = "Tumbler" ]; then
-               switch_control "Auto Mute" off
-               switch_control "PC Speaker" off
-               switch_control "Auto Mute" on
-       fi
-}
-
-# $1 <card ID> | "all"
-preinit_levels()
-{
-       TTSDML_RETURNSTATUS=0
-       case "$1" in
-         all)
-               for CARD in $(echo_card_indices) ; do
-                       preinit_levels_on_card "$CARD" || TTSDML_RETURNSTATUS=1
-               done
-               ;;
-         *)
-               preinit_levels_on_card "$1" || TTSDML_RETURNSTATUS=1
-               ;;
-       esac
-       return $TTSDML_RETURNSTATUS
-}
-
-# $1 <card ID>
-mute_and_zero_levels_on_card()
-{
-       CARDOPT="-c $1"
-       for CTL in \
-               Master \
-               PCM \
-               Synth \
-               CD \
-               Line \
-               Mic \
-               "PCM,1" \
-               Wave \
-               Music \
-               AC97 \
-               "Master Digital" \
-               DAC \
-               "DAC,0" \
-               "DAC,1" \
-               Headphone \
-               Playback \
-               Speaker
-       do
-               mute_and_zero_level "$CTL"
-       done
-#      for CTL in \
-#              "Audigy Analog/Digital Output Jack" \
-#              "SB Live Analog/Digital Output Jack"
-#      do
-#              switch_control "$CTL" off
-#      done
-       return 0
-}
-
-# $1 <card ID> | "all"
-mute_and_zero_levels()
-{
-       TTZML_RETURNSTATUS=0
-       case "$1" in
-         all)
-               for CARD in $(echo_card_indices) ; do
-                       mute_and_zero_levels_on_card "$CARD" || TTZML_RETURNSTATUS=1
-               done
-               ;;
-         *)
-               mute_and_zero_levels_on_card "$1" || TTZML_RETURNSTATUS=1
-               ;;
-       esac
-       return $TTZML_RETURNSTATUS
-}
-
-
-# $1 <card ID> | "all"
-card_OK()
-{
-       [ "$1" ] || bugout
-       if [ "$1" = all ] ; then
-               [ -d /proc/asound ]
-               return $?
-       else
-               [ -d "/proc/asound/card$1" ] || [ -d "/proc/asound/$1" ]
-               return $?
-       fi
-}
-
-# If a card identifier is provided in $2 then regard it as an error
-# if that card is not present; otherwise don't regard it as an error.
-
-case "$1" in
-  start)
-       EXITSTATUS=0
-       TARGET_CARD="$2"
-       case "$TARGET_CARD" in
-         ""|all) TARGET_CARD=all ; log_action_begin_msg "Setting up ALSA" ;;
-       esac
-       if ! card_OK "$TARGET_CARD"; then
-               [ "$TARGET_CARD" = "all" ] && log_action_end_msg "$( [ ! "$2" ] ; echo $? ; )" "none loaded"
-               exit $?
-       fi
-       preinit_levels "$TARGET_CARD" || EXITSTATUS=1
-       if ! restore_levels "$TARGET_CARD" ; then
-               sanify_levels "$TARGET_CARD" || EXITSTATUS=1
-               restore_levels "$TARGET_CARD" >/dev/null 2>&1 || :
-       fi
-       [ "$TARGET_CARD" = "all" ] && log_action_end_msg_and_exit "$EXITSTATUS"
-       exit $EXITSTATUS
-       ;;
-  stop)
-       EXITSTATUS=0
-       TARGET_CARD="$2"
-       case "$TARGET_CARD" in
-         ""|all) TARGET_CARD=all ; log_action_begin_msg "Shutting down ALSA" ;;
-         *) log_action_begin_msg "Shutting down ALSA card ${TARGET_CARD}" ;;
-       esac
-       card_OK "$TARGET_CARD" || log_action_end_msg_and_exit "$( [ ! "$2" ] ; echo $? ; )" "none loaded"
-       store_levels "$TARGET_CARD" || EXITSTATUS=1
-       mute_and_zero_levels "$TARGET_CARD" || EXITSTATUS=1
-       log_action_end_msg_and_exit "$EXITSTATUS"
-       ;;
-  restart|force-reload)
-       EXITSTATUS=0
-       $0 stop || EXITSTATUS=1
-       $0 start || EXITSTATUS=1
-       exit $EXITSTATUS
-       ;;
-  reset)
-       TARGET_CARD="$2"
-       case "$TARGET_CARD" in
-         ""|all) TARGET_CARD=all ; log_action_begin_msg "Resetting ALSA" ;;
-         *) log_action_begin_msg "Resetting ALSA card ${TARGET_CARD}" ;;
-       esac
-       card_OK "$TARGET_CARD" || log_action_end_msg_and_exit "$( [ ! "$2" ] ; echo $? ; )" "none loaded"
-       preinit_levels "$TARGET_CARD"
-       sanify_levels "$TARGET_CARD"
-       log_action_end_msg_and_exit "$?"
-       ;;
-  *)
-       echo "Usage: $MYNAME {start [CARD]|stop [CARD]|restart [CARD]|reset [CARD]}" >&2
-       exit 3
-       ;;
-esac
-
-#!/bin/bash -e
-#
-# apache2              This init.d script is used to start apache2.
-#                      It basically just calls apache2ctl.
-
-ENV="env -i LANG=C PATH=/usr/local/bin:/usr/bin:/bin"
-
-#edit /etc/default/apache2 to change this.
-NO_START=0
-
-set -e
-if [ -x /usr/sbin/apache2 ] ; then
-       HAVE_APACHE2=1
-else
-       exit 0
-fi
-
-. /lib/lsb/init-functions
-
-test -f /etc/default/rcS && . /etc/default/rcS
-test -f /etc/default/apache2 && . /etc/default/apache2
-if [ "$NO_START" != "0" -a "$1" != "stop" ]; then 
-        [ "$VERBOSE" != "no" ] && log_warning_msg "Not starting apache2 - edit /etc/default/apache2 and change NO_START to be 0.";
-        exit 0;
-fi
-
-APACHE2="$ENV /usr/sbin/apache2"
-APACHE2CTL="$ENV /usr/sbin/apache2ctl"
-
-apache_stop() {
-       PID=""
-       PIDFILE=""
-       AP_CONF=/etc/apache2/apache2.conf
-
-       # apache2 allows more than PidFile entry in the config but only the
-       # last found in the config is used; we attempt to follow includes
-       # here, but only first-level includes are supported, not nested ones
-
-       for i in $AP_CONF `awk '$1 ~ /^\s*[Ii]nclude$/ && $2 ~ /^\// {print $2}' $AP_CONF`; do
-               PIDFILE=`grep -i ^PidFile $i | tail -n 1 | awk '{print $2}'`
-               if [ -e "$PIDFILE" ]; then
-                       PID=`cat $PIDFILE`
-               fi
-       done
-       
-       errors=`$APACHE2 -t 2>&1`
-       if [ $? = 0 ]; then
-               # if the config is ok than we just stop normaly
-
-               if [ -n "$PID" ]
-               then
-                       $APACHE2CTL stop
-
-                       CNT=0
-                       while [ 1 ]
-                       do
-                               CNT=$(expr $CNT + 1)
-               
-                               [ ! -d /proc/$PID ] && break
-
-                               if [ $CNT -gt 60 ]
-                               then
-                                       if [ "$VERBOSE" != "no" ]; then
-                                               echo " ... failed!"
-                                               echo "Apache2 failed to honor the stop command, please investigate the situation by hand."
-                                       fi
-                                       return 1
-                               fi
-
-                               sleep 1
-                       done
-               else
-                       if [ "$VERBOSE" != "no" ]; then
-                               echo -n " ... no pidfile found! not running?"
-                       fi
-               fi
-
-       else
-               [ "$VERBOSE" != "no" ] && echo "$errors"
-
-               # if we are here something is broken and we need to try
-               # to exit as nice and clean as possible
-
-               # if pidof is null for some reasons the script exits automagically
-               # classified as good/unknown feature
-               PIDS=`pidof apache2` || true
-
-               REALPID=0
-               # if there is a pid we need to verify that belongs to apache2
-               # for real
-               for i in $PIDS; do
-                       if [ "$i" = "$PID" ]; then
-                               # in this case the pid stored in the
-                               # pidfile matches one of the pidof apache
-                               # so a simple kill will make it
-                               REALPID=1
-                       fi
-               done
-
-               if [ $REALPID = 1 ]; then
-                       # in this case everything is nice and dandy
-                       # and we kill apache2
-                       kill $PID
-               else
-                       # this is the worst situation... just kill all of them
-                       #for i in $PIDS; do
-                       #       kill $i
-                       #done
-                       # Except, we can't do that, because it's very, very bad
-                       if [ "$PIDS" ] && [ "$VERBOSE" != "no" ]; then
-                                echo " ... failed!"
-                               echo "You may still have some apache2 processes running.  There are"
-                               echo "processes named 'apache2' which do not match your pid file,"
-                               echo "and in the name of safety, we've left them alone.  Please review"
-                               echo "the situation by hand."
-                        fi
-                        return 1
-               fi
-       fi
-}
-
-# Stupid hack to keep lintian happy. (Warrk! Stupidhack!).
-case $1 in
-       start)
-               [ -f /etc/apache2/httpd.conf ] || touch /etc/apache2/httpd.conf
-               # ssl_scache shouldn't be here if we're just starting up.
-               [ -f /var/run/apache2/ssl_scache ] && rm -f /var/run/apache2/*ssl_scache*
-               # /var/run and /var/lock could be on a tmpfs
-               [ ! -d /var/run/apache2 ] && mkdir /var/run/apache2
-               [ ! -d /var/lock/apache2 ] && mkdir /var/lock/apache2
-               # Make sure /var/lock/apache2 has the correct permissions
-               chown www-data /var/lock/apache2
-
-               log_begin_msg "Starting apache 2.0 web server..."
-               if $APACHE2CTL startssl; then
-                        log_end_msg 0
-                else
-                        log_end_msg 1
-                fi
-       ;;
-       stop)
-               log_begin_msg "Stopping apache 2.0 web server..."
-               if apache_stop; then
-                        log_end_msg 0
-                else
-                        log_end_msg 1
-                fi
-       ;;
-       reload)
-               log_begin_msg "Reloading apache 2.0 configuration..."
-               if $APACHE2CTL graceful $2 ; then
-                        log_end_msg 0
-                else
-                        log_end_msg 1
-                fi
-       ;;
-       restart | force-reload)
-               log_begin_msg "Forcing reload of apache 2.0 web server..."
-               if ! apache_stop; then
-                        log_end_msg 1
-                fi
-               if $APACHE2CTL startssl; then
-                        log_end_msg 0
-                else
-                        log_end_msg 1
-                fi
-       ;;
-       status)
-               exit 4
-       ;;
-       *)
-               echo "Usage: /etc/init.d/apache2 start|stop|restart|reload|force-reload" >&2
-               exit 2
-       ;;
-esac
-#! /bin/sh -e
-#### BEGIN INIT INFO
-# Provides:          atd
-# Required-Start:    $syslog $time $local_fs $remote_fs
-# Required-Stop:     $syslog $time $local_fs $remote_fs
-# Default-Start:     2 3 4 5
-# Default-Stop:      S 0 1 6
-# Short-Description: Deferred execution scheduler
-# Description:       Debian init script for the atd deferred executions
-#                    scheduler
-### END INIT INFO
-#
-# Author:      Ryan Murray <rmurray@debian.org>
-#
-set -e
-
-PATH=/bin:/usr/bin:/sbin:/usr/sbin
-DAEMON=/usr/sbin/atd
-
-test -x $DAEMON || exit 0
-
-. /lib/lsb/init-functions
-
-case "$1" in
-    start)
-       log_daemon_msg "Starting deferred execution scheduler" "atd"
-       start_daemon $DAEMON
-       log_end_msg $?
-    ;;
-  stop)
-       log_daemon_msg "Stopping deferred execution scheduler" "atd"
-       killproc $DAEMON
-       log_end_msg $?
-    ;;
-  force-reload|restart)
-    $0 stop
-    $0 start
-    ;;
-  *)
-    echo "Usage: /etc/init.d/atd {start|stop|restart|force-reload}"
-    exit 1
-    ;;
-esac
-
-exit 0
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          binfmt-support
-# Required-Start:    $local_fs $remote_fs
-# Required-Stop:     $local_fs $remote_fs
-# Default-Start:     2 3 4 5
-# Default-Stop:      0 1 6
-# Short-Description: Support for extra binary formats
-# Description:       Enable support for extra binary formats using the Linux
-#                    kernel's binfmt_misc facility.
-### END INIT INFO
-
-PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
-NAME=binfmt-support
-DESC="additional executable binary formats"
-
-test -x /usr/sbin/update-binfmts || exit 0
-
-. /lib/lsb/init-functions
-. /etc/default/rcS
-
-set -e
-CODE=0
-
-case "$1" in
-  start)
-    log_daemon_msg "Enabling $DESC" "$NAME"
-    update-binfmts --enable || CODE=$?
-    log_end_msg $CODE
-    exit $CODE
-    ;;
-
-  stop)
-    log_daemon_msg "Disabling $DESC" "$NAME"
-    update-binfmts --disable || CODE=$?
-    log_end_msg $CODE
-    exit $CODE
-    ;;
-
-  restart|force-reload)
-    $0 stop
-    $0 start
-    ;;
-
-  *)
-    N=/etc/init.d/$NAME
-    echo "Usage: $N {start|stop|restart|force-reload}" >&2
-    exit 1
-    ;;
-esac
-
-exit 0
-#!/bin/sh
-#
-# bootclean
-#
-# Clean /tmp
-#
-# DO NOT RUN AFTER S:55bootmisc.sh and do not run this script directly
-# in runlevel S. Instead write an initscript to call it.
-#
-
-. /lib/init/vars.sh
-
-. /lib/lsb/init-functions
-
-# Should be called outside verbose message block
-mkflagfile()
-{
-       # Prevent symlink attack  (See #264234.)
-       [ -L "$1" ] && log_warning_msg "bootclean: Deleting symbolic link '$1'."
-       rm -f "$1" || { log_failure_msg "bootclean: Failure deleting '$1'." ; return 1 ; }
-       # No user processes should be running, so no one should be able to introduce
-       # a symlink here.  As an extra precaution, set noclobber.
-       set -o noclobber
-       :> "$1" || { log_failure_msg "bootclean: Failure creating '$1'." ; return 1 ; }
-       return 0
-}
-
-clean_tmp() {
-       cd /tmp || { log_failure_msg "bootclean: Could not cd to /tmp." ; return 1 ; }
-
-       #
-       # Only clean out /tmp if it is world-writable. This ensures
-       # it really is a/the temp directory we're cleaning.
-       #
-       [ "$(find . -maxdepth 0 -perm -002)" = "." ] || return 0
-
-       if [ ! "$TMPTIME" ]
-       then
-               log_warning_msg "Using default TMPTIME 0."
-               TMPTIME=0
-       fi
-
-       [ "$VERBOSE" = no ] || log_action_begin_msg "Cleaning /tmp"
-
-       #
-       # Remove regardless of TMPTIME setting
-       #
-       rm -f .X*-lock
-
-       #
-       # Don't clean remaining files if TMPTIME is negative or 'infinite'
-       #
-       case "$TMPTIME" in
-         -*|infinite|infinity)
-               [ "$VERBOSE" = no ] || log_action_end_msg 0 "skipped"
-               return 0
-               ;;
-       esac
-
-       #
-       # Wipe /tmp, excluding system files, but including lost+found
-       #
-       # If TMPTIME is set to 0, we do not use any ctime expression
-       # at all, so we can also delete files with timestamps
-       # in the future!
-       #
-       if [ "$TMPTIME" = 0 ] 
-       then
-               TEXPR=""
-               DEXPR=""
-       else
-               TEXPR="-mtime +$TMPTIME -ctime +$TMPTIME -atime +$TMPTIME"
-               DEXPR="-mtime +$TMPTIME -ctime +$TMPTIME"
-       fi
-
-       EXCEPT='! -name .
-               ! ( -path ./lost+found -uid 0 )
-               ! ( -path ./quota.user -uid 0 )
-               ! ( -path ./aquota.user -uid 0 )
-               ! ( -path ./quota.group -uid 0 )
-               ! ( -path ./aquota.group -uid 0 )
-               ! ( -path ./.journal -uid 0 )
-               ! ( -path ./.clean -uid 0 )
-               ! ( -path './...security*' -uid 0 )'
-
-       mkflagfile /tmp/.clean || return 1
-
-       report_err()
-       {
-               if [ "$VERBOSE" = no ]
-               then
-                       log_failure_msg "bootclean: Failure cleaning /tmp."
-               else
-                       log_action_end_msg 1 "bootclean: Failure cleaning /tmp"
-               fi
-       }
-
-       #
-       # First remove all old files...
-       # (Use xargs here so that only one additional process gets created)
-       #
-       find . -depth -xdev $TEXPR $EXCEPT ! -type d \
-               -print0 | xargs -0r rm -f -- \
-               || { report_err ; return 1 ; }
-
-       #
-       # ...and then all empty directories
-       # (Don't use xargs here because dirs must be removed one by one from
-       # the bottom up)
-       #
-       find . -depth -xdev $DEXPR $EXCEPT -type d -empty \
-               -exec rmdir \{\} \; \
-               || { report_err ; return 1 ; }
-
-       [ "$VERBOSE" = no ] || log_action_end_msg 0
-       return 0
-}
-
-which find >/dev/null 2>&1 || exit 1
-which xargs >/dev/null 2>&1 || exit 1
-
-# If there are flag files that have not been created by root
-# then remove them
-for D in /tmp
-do
-       if [ -f $D/.clean ]
-       then
-               which stat >/dev/null 2>&1 && cleanuid="$(stat -c %u $D/.clean)"
-               # Poor's man stat %u, since stat (and /usr) might not be
-               # available in some bootup stages
-               [ "$cleanuid" ] || cleanuid="$(find $D/.clean -printf %U)"
-               [ "$cleanuid" ] || { log_failure_msg "bootclean: Could not stat '$D/.clean'." ; exit 1 ; }
-               if [ "$cleanuid" -ne 0 ]
-               then
-                       rm -f $D/.clean || { log_failure_msg "bootclean: Could not delete '$D/.clean'." ; exit 1 ; }
-               fi
-       fi
-done
-
-[ -f /tmp/.clean ] && exit 0
-
-ES=0
-[ -d /tmp ] && ! [ -f /tmp/.clean ] && { clean_tmp || ES=1 ; }
-exit $ES
-
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          bootlogd
-# Required-Start:    mountdevsubfs
-# Required-Stop:
-# Default-Start:     S
-# Default-Stop:
-# Short-Description: Start or stop bootlogd.
-# Description:       Starts or stops the bootlogd log program
-#                    which logs boot messages.
-### END INIT INFO
-
-PATH=/sbin:/bin
-DAEMON=/sbin/bootlogd
-[ -x "$DAEMON" ] || exit 0
-NAME=bootlogd
-DESC="boot logger"
-BOOTLOGD_OPTS="-r -c"
-[ -r /etc/default/bootlogd ] && . /etc/default/bootlogd
-. /lib/init/vars.sh
-
-. /lib/lsb/init-functions
-
-# Because bootlogd is broken on some systems, we take the special measure
-# of requiring it to be enabled by setting an environment variable.
-case "$BOOTLOGD_ENABLE" in
-  [Nn]*)
-       exit 0
-       ;;
-esac
-
-# Previously this script was symlinked as "stop-bootlogd" which, when run
-# with the "start" argument, should stop bootlogd.  Now stop-bootlogd is
-# a distinct script, but for backward compatibility this script continues
-# to implement the old behavior.
-SCRIPTNAME=${0##*/}
-SCRIPTNAME=${SCRIPTNAME#[SK]??}
-ACTION="$1"
-case "$0" in
-  *stop-bootlog*)
-       [ "$ACTION" = start ] && ACTION=stop
-       ;;
-esac
-
-case "$ACTION" in
-  start)
-       # PATH is set above
-       log_daemon_msg "Starting $DESC" "$NAME"
-       if [ -d /proc/1/. ]
-       then
-               umask 027
-               start-stop-daemon --start --quiet --exec $DAEMON -- \
-                       $BOOTLOGD_OPTS
-               ES=$?
-       else
-               $DAEMON $BOOTLOGD_OPTS
-               ES=$?
-       fi
-       log_end_msg $ES
-       ;;
-  stop)
-       PATH=/sbin:/bin:/usr/sbin:/usr/bin
-       log_daemon_msg "Stopping $DESC" "$NAME"
-       start-stop-daemon --stop --quiet --exec $DAEMON
-       ES=$?
-       sleep 1
-       log_end_msg $ES
-       if [ -f /var/log/boot ] && [ -f /var/log/boot~ ]
-       then
-               [ "$VERBOSE" = no ] || log_action_begin_msg "Moving boot log file"
-               # bootlogd writes to boot, making backup at boot~
-               cd /var/log && {
-                       chgrp adm boot || :
-                       savelog -q -p -c 5 boot \
-                       && mv boot.0 boot \
-                       && mv boot~ boot.0
-               }
-               ES=$?
-               [ "$VERBOSE" = no ] || log_action_end_msg $ES
-       fi
-       ;;
-  restart|force-reload)
-       /etc/init.d/bootlogd stop
-       /etc/init.d/bootlogd start
-       ;;
-  *)
-       echo "Usage: $SCRIPTNAME {start|stop|restart|force-reload}" >&2
-       exit 3
-       ;;
-esac
-
-:
-#!/bin/sh
-### BEGIN INIT INFO
-# Provides:          bootmisc
-# Required-Start:    $local_fs hostname $remote_fs
-# Required-Stop:     $local_fs
-# Default-Start:     S
-# Default-Stop:
-# Short-Description: Miscellaneous things to be done during bootup.
-# Description:
-### END INIT INFO
-
-PATH=/usr/sbin:/usr/bin:/sbin:/bin
-[ "$DELAYLOGIN" ] || DELAYLOGIN=yes
-. /lib/init/vars.sh
-
-do_start () {
-       #
-       # If login delaying is enabled then create the flag file
-       # which prevents logins before startup is complete
-       #
-       case "$DELAYLOGIN" in
-         Y*|y*)
-               echo "System bootup in progress - please wait" > /var/lib/initscripts/nologin
-               ;;
-       esac
-
-       # Create /var/run/utmp so we can login.
-       : > /var/run/utmp
-       if grep -q ^utmp: /etc/group
-       then
-               chmod 664 /var/run/utmp
-               chgrp utmp /var/run/utmp
-       fi
-
-       # Set pseudo-terminal access permissions.
-       if [ ! -e /dev/.devfsd ] && [ -c /dev/ttyp0 ]
-       then
-               chmod -f 666 /dev/tty[p-za-e][0-9a-f]
-               chown -f root:tty /dev/tty[p-za-e][0-9a-f]
-       fi
-
-       # Update motd
-       uname -snrvm > /var/run/motd
-       [ -f /etc/motd.tail ] && cat /etc/motd.tail >> /var/run/motd
-
-       # Save kernel messages in /var/log/dmesg
-       if which dmesg >/dev/null 2>&1
-       then
-               savelog -q -p -c 5 /var/log/dmesg
-               dmesg -s 524288 > /var/log/dmesg
-               chgrp adm /var/log/dmesg || :
-       elif [ -c /dev/klog ]
-       then
-               savelog -q -p -c 5 /var/log/dmesg
-               dd if=/dev/klog of=/var/log/dmesg &
-               sleep 1
-               kill $!
-               [ -f /var/log/dmesg ] && { chgrp adm /var/log/dmesg || : ; }
-       fi
-
-       # Remove bootclean's flag files.
-       # Don't run bootclean again after this!
-       rm -f /tmp/.clean
-}
-
-case "$1" in
-  start|"")
-       do_start
-       ;;
-  restart|reload|force-reload)
-       echo "Error: argument '$1' not supported" >&2
-       exit 3
-       ;;
-  stop)
-       # No-op
-       ;;
-  *)
-       echo "Usage: bootmisc.sh [start|stop]" >&2
-       exit 3
-       ;;
-esac
-
-:
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          checkfs
-# Required-Start:    modutils checkroot
-# Required-Stop:
-# Should-Start:      lvm cryptdisks
-# Should-Stop:
-# Default-Start:     S
-# Default-Stop:
-# Short-Description: Check all filesystems.
-### END INIT INFO
-
-PATH=/sbin:/bin
-FSCK_LOGFILE=/var/log/fsck/checkfs
-[ "$FSCKFIX" ] || FSCKFIX=no
-. /lib/init/vars.sh
-. /lib/init/usplash-fsck-functions.sh
-
-. /lib/lsb/init-functions
-
-# Always output fsck progress
-stdin=`readlink /proc/self/fd/0`
-if [ "${stdin#/dev/null}" != "$stdin" ]; then
-    exec </dev/console >/dev/console 2>&1
-fi
-
-do_start () {
-       # See if we're on AC Power
-       # If not, we're not gonna run our check
-       if which on_ac_power >/dev/null 2>&1
-       then
-               on_ac_power >/dev/null 2>&1
-               if [ $? -eq 1 ]
-               then
-                       [ "$VERBOSE" = no ] || log_success_msg "Running on battery power, so skipping file system check."
-                       BAT=yes
-               fi
-       fi
-
-       #
-       # Check the rest of the file systems.
-       #
-       if [ ! -f /fastboot ] && [ ! "$BAT" ] && [ "$FSCKTYPES" != "none" ]
-       then
-               if [ -f /forcefsck ]
-               then
-                       force="-f"
-               else
-                       force=""
-               fi
-               if [ "$FSCKFIX" = yes ]
-               then
-                       fix="-y"
-               else
-                       fix="-a"
-               fi
-               spinner="-C"
-               case "$TERM" in
-                 dumb|network|unknown|"")
-                       spinner=""
-                       ;;
-               esac
-               [ "$(uname -m)" = s390 ] && spinner=""  # This should go away
-               FSCKTYPES_OPT=""
-               [ "$FSCKTYPES" ] && FSCKTYPES_OPT="-t $FSCKTYPES"
-               handle_failed_fsck() {
-                       log_failure_msg "File system check failed. 
-A log is being saved in ${FSCK_LOGFILE} if that location is writable. 
-Please repair the file system manually."
-                       log_warning_msg "A maintenance shell will now be started. 
-CONTROL-D will terminate this shell and resume system boot."
-                       # Start a single user shell on the console
-                       if ! sulogin $CONSOLE
-                       then
-                               log_failure_msg "Attempt to start maintenance shell failed. 
-Continuing with system boot in 5 seconds."
-                               sleep 5
-                       fi
-               }
-               if [ "$VERBOSE" = no ]
-               then
-                       log_action_begin_msg "Checking file systems"
-                        if pidof usplash; then
-                            PROGRESS_FILE=`mktemp` || exit 1
-                            set -m
-                            logsave -s $FSCK_LOGFILE fsck -C3 -R -A $fix $force $FSCKTYPES_OPT >/dev/console 2>&1 3>$PROGRESS_FILE &
-                            set +m
-                            usplash_progress "$PROGRESS_FILE"
-                            rm -f $PROGRESS_FILE
-                        else
-                            logsave -s $FSCK_LOGFILE fsck $spinner -R -A $fix $force $FSCKTYPES_OPT
-                            FSCKCODE=$?
-                        fi
-
-                       if [ "$FSCKCODE" -gt 1 ]
-                       then
-                               log_action_end_msg 1 "code $FSCKCODE"
-                               handle_failed_fsck
-                       else
-                               log_action_end_msg 0
-                       fi
-               else
-                       if [ "$FSCKTYPES" ]
-                       then
-                               log_action_msg "Will now check all file systems of types $FSCKTYPES"
-                       else
-                               log_action_msg "Will now check all file systems"
-                       fi
-                       logsave -s $FSCK_LOGFILE fsck $spinner -V -R -A $fix $force $FSCKTYPES_OPT
-                       FSCKCODE=$?
-                       if [ "$FSCKCODE" -gt 1 ]
-                       then
-                               handle_failed_fsck
-                       else
-                               log_success_msg "Done checking file systems. 
-A log is being saved in ${FSCK_LOGFILE} if that location is writable."
-                       fi
-               fi
-       fi
-       rm -f /fastboot /forcefsck
-}
-
-case "$1" in
-  start|"")
-       do_start
-       ;;
-  restart|reload|force-reload)
-       echo "Error: argument '$1' not supported" >&2
-       exit 3
-       ;;
-  stop)
-       # No-op
-       ;;
-  *)
-       echo "Usage: checkfs.sh [start|stop]" >&2
-       exit 3
-       ;;
-esac
-
-:
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          checkroot
-# Required-Start:    mountdevsubfs
-# Required-Stop:     
-# Should-Start:      keymap hwclockfirst
-# Should-stop:
-# Default-Start:     S
-# Default-Stop:
-# Short-Description: Check to root file system.
-### END INIT INFO
-
-PATH=/lib/init:/sbin:/bin
-FSCK_LOGFILE=/var/log/fsck/checkroot
-[ "$FSCKFIX" ] || FSCKFIX=no
-[ "$SULOGIN" ] || SULOGIN=no
-. /lib/init/vars.sh
-. /lib/init/usplash-fsck-functions.sh
-
-. /lib/lsb/init-functions
-
-# Always output fsck progress
-stdin=`readlink /proc/self/fd/0`
-if [ "${stdin#/dev/null}" != "$stdin" ]; then
-    exec </dev/console >/dev/console 2>&1
-fi
-
-do_start () {
-       #
-       # Set SULOGIN in /etc/default/rcS to yes if you want a sulogin to
-       # be spawned from this script *before anything else* with a timeout,
-       # like sysv does.
-       #
-       [ "$SULOGIN" = yes ] && sulogin -t 30 $CONSOLE
-
-       KERNEL="$(uname -s)"
-       MACHINE="$(uname -m)"
-
-       #
-       # Read /etc/fstab, looking for:
-       # 1) The root filesystem, resolving LABEL=*|UUID=* entries to the
-       #       device node,
-       # 2) Swap that is on a md device or a file that may be on a md 
-       #       device,
-       # 3) The mount parameters for a devfs filesystem.
-       #
-
-       exec 9<&0 </etc/fstab
-
-       fstabroot=/dev/root
-       rootdev=none
-       roottype=none
-       rootopts=defaults
-       rootmode=rw
-       rootcheck=no
-       swap_on_lv=no
-       swap_on_file=no
-       devfs=
-
-       while read DEV MTPT FSTYPE OPTS DUMP PASS JUNK
-       do
-               case "$DEV" in
-                 ""|\#*)
-                       continue;
-                       ;;
-                 /dev/mapper/*)
-                       [ "$FSTYPE" = "swap" ] && swap_on_lv=yes
-                       ;;
-                 /dev/*)
-                       ;;
-                 LABEL=*|UUID=*)
-                       if [ "$MTPT" = "/" ] && which findfs >/dev/null 2>&1
-                       then
-                               DEV="$(findfs "$DEV")"
-                       fi
-                       ;;
-                 /*)
-                       [ "$FSTYPE" = "swap" ] && swap_on_file=yes
-                       ;;
-                 *)
-                       # Devfs definition ?
-                       if [ "$FSTYPE" = "devfs" ] && [ "$MTPT" = "/dev" ] && mountpoint -q /dev
-                       then
-                               devfs="-t $FSTYPE $DEV $MTPT"
-                       fi
-                       ;;
-               esac
-               [ "$MTPT" != "/" ] && continue
-               rootdev="$DEV"
-               fstabroot="$DEV"
-               rootopts="$OPTS"
-               roottype="$FSTYPE"
-               ( [ "$PASS" != 0 ] && [ "$PASS" != "" ]   ) && rootcheck=yes
-               ( [ "$FSTYPE" = "nfs" ] || [ "$FSTYPE" = "nfs4" ] ) && rootcheck=no
-               case "$OPTS" in
-                 ro|ro,*|*,ro|*,ro,*)
-                       rootmode=ro
-                       ;;
-               esac
-       done
-
-       exec 0<&9 9<&-
-
-       #
-       # Activate the swap device(s) in /etc/fstab. This needs to be done
-       # before fsck, since fsck can be quite memory-hungry.
-       #
-       ENABLE_SWAP=no
-       case "$KERNEL" in
-         Linux)
-               if [ "$swap_on_lv" = yes ]
-               then
-                       [ "$VERBOSE" = no ] || log_warning_msg "Not activating swap on logical volume."
-               elif [ "$swap_on_file" = yes ]
-               then
-                       [ "$VERBOSE" = no ] || log_warning_msg "Not activating swap on swapfile."
-               else
-                       ENABLE_SWAP=yes
-               fi
-               ;;
-         *)
-               ENABLE_SWAP=yes
-               ;;
-       esac
-       if [ "$ENABLE_SWAP" = yes ]
-       then
-               if [ "$VERBOSE" = no ]
-               then
-                       log_action_begin_msg "Activating swap"
-                       swapon -a -e >/dev/null 2>&1
-                       log_action_end_msg $?
-               else
-                       log_action_msg "Will now activate swap"
-                       swapon -a -v
-                       ES=$?
-                       if [ "$ES" = 0 ]
-                       then
-                               log_success_msg "Done activating swap."
-                       else
-                               log_failure_msg "Swap activation failed with error code ${ES}."
-                       fi
-               fi
-       fi
-
-       #
-       # Does the root device in /etc/fstab match with the actual device ?
-       # If not we try to use the /dev/root alias device, and if that
-       # fails we create a temporary node in /dev/shm.
-       #
-       if [ "$rootcheck" = yes ]
-       then
-               ddev="$(mountpoint -qx $rootdev)"
-               rdev="$(mountpoint -d /)"
-               if [ "$ddev" != "$rdev" ] && [ "$ddev" != "4:0" ]
-               then
-                       if [ "$(mountpoint -qx /dev/root)" = "4:0" ]
-                       then
-                               rootdev=/dev/root
-                       else
-                               if \
-                                       rm -f /dev/shm/root \
-                                       && mknod -m 600 /dev/shm/root b ${rdev%:*} ${rdev#*:} \
-                                       && [ -e /dev/shm/root ]
-                               then
-                                       rootdev=/dev/shm/root
-                               else
-                                       rootfatal=yes
-                               fi
-                       fi
-               fi
-       fi
-
-       #
-       # Bother, said Pooh.
-       #
-       if [ "$rootfatal" = yes ]
-       then
-               log_failure_msg "The device node $rootdev for the root filesystem is missing or incorrect 
-or there is no entry for the root filesystem listed in /etc/fstab. 
-The system is also unable to create a temporary node in /dev/shm. 
-This means you have to fix the problem manually."
-               log_warning_msg "A maintenance shell will now be started. 
-CONTROL-D will terminate this shell and restart the system."
-               # Start a single user shell on the console
-               if ! sulogin $CONSOLE
-               then
-                       log_failure_msg "Attempt to start maintenance shell failed. 
-Will restart in 5 seconds."
-                       sleep 5
-               fi
-               [ "$VERBOSE" = no ] || log_action_msg "Will now restart"
-               reboot -f
-       fi
-
-       # See if we're on AC Power
-       # If not, we're not gonna run our check
-       if which on_ac_power >/dev/null 2>&1 && [ "$rootcheck" = yes ]
-       then
-               if [ -d /proc/acpi ]; then
-                       modprobe ac >/dev/null 2>&1
-               fi
-               on_ac_power >/dev/null 2>&1
-               if [ "$?" -eq 1 ]
-               then
-                       log_warning_msg "On battery power, so skipping file system check."
-                       rootcheck=no
-               fi
-       fi
-
-       #
-       # See if we want to check the root file system.
-       #
-       FSCKCODE=0
-       if [ -f /fastboot ]
-       then
-               [ "$rootcheck" = yes ] && log_warning_msg "Fast boot enabled, so skipping file system check."
-               rootcheck=no
-       fi
-
-       if [ "$rootcheck" = yes ]
-       then
-               #
-               # Ensure that root is quiescent and read-only before fsck'ing.
-               #
-               # mount -n -o remount,ro / would be the correct syntax but
-               # mount can get confused when there is a "bind" mount defined
-               # in fstab that bind-mounts "/" somewhere else.
-               #
-               # So we use mount -n -o remount,ro $rootdev / but that can
-               # fail on older kernels on sparc64/alpha architectures due
-               # to a bug in sys_mount().
-               #
-               # As a compromise we try both.
-               #
-               if \
-                       ! mount    -n -o remount,ro              $rootdev /              \
-                       && ! mount -n -o remount,ro -t dummytype $rootdev /  2>/dev/null \
-                       && ! mount -n -o remount,ro                       /  2>/dev/null
-               then
-                       log_failure_msg "Cannot check root file system because it is not mounted read-only."
-                       rootcheck=no
-               fi
-       fi
-
-       #
-       # The actual checking is done here.
-       #
-       if [ "$rootcheck" = yes ]
-       then
-               if [ -f /forcefsck ]
-               then
-                       force="-f"
-               else
-                       force=""
-               fi
-
-               if [ "$FSCKFIX" = yes ]
-               then
-                       fix="-y"
-               else
-                       fix="-a"
-               fi
-
-               spinner="-C"
-               case "$TERM" in
-                 dumb|network|unknown|"")
-                       spinner="" ;;
-               esac
-               # This Linux/s390 special case should go away.
-               if [ "${KERNEL}:${MACHINE}" = Linux:s390 ]
-               then
-                       spinner=""
-               fi
-               
-               if [ "$VERBOSE" = no ]
-               then
-                       log_action_begin_msg "Checking root file system"
-                        if [ "$roottype" = "ext2" -o "$roottype" = "ext3" ] && pidof usplash; then
-                            PROGRESS_FILE=`mktemp -p /var/run` || PROGRESS_FILE=/var/run/checkroot_fsck
-                            set -m
-                            logsave -s $FSCK_LOGFILE fsck -C3 $force $fix -t $roottype $rootdev >/dev/console 2>&1 3>$PROGRESS_FILE &
-                            set +m
-                            usplash_progress "$PROGRESS_FILE"
-                            rm -f $PROGRESS_FILE
-                        else
-                            logsave -s $FSCK_LOGFILE fsck $spinner $force $fix -t $roottype $rootdev
-                            FSCKCODE=$?
-                        fi
-                       if [ "$FSCKCODE" = 0 ]
-                       then
-                               log_action_end_msg 0
-                       else
-                               log_action_end_msg 1 "code $FSCKCODE"
-                       fi
-               else
-                       log_action_msg "Will now check root file system"
-                       logsave -s $FSCK_LOGFILE fsck $spinner $force $fix -V -t $roottype $rootdev
-                       FSCKCODE=$?
-                       if [ "$FSCKCODE" = 0 ]
-                       then
-                               log_success_msg "Done checking root file system. 
-A log will be saved in ${FSCK_LOGFILE} if that location is writable."
-                       else
-                               log_failure_msg "Root file system check failed with error code ${FSCKCODE}. 
-A log is being saved in ${FSCK_LOGFILE} if that location is writable."
-                       fi
-               fi
-       fi
-
-       #
-       # If there was a failure, drop into single-user mode.
-       #
-       # NOTE: "failure" is defined as exiting with a return code of
-       # 4 or larger. A return code of 1 indicates that file system
-       # errors were corrected but that the boot may proceed. A return
-       # code of 2 or 3 indicates that the system should immediately reboot.
-       #
-       if [ "$FSCKCODE" -gt 3 ]
-       then
-               # Surprise! Re-directing from a HERE document (as in "cat << EOF")
-               # does not work because the root is currently read-only.
-               log_failure_msg "An automatic file system check (fsck) of the root filesystem failed. 
-A manual fsck must be performed, then the system restarted. 
-The fsck should be performed in maintenance mode with the 
-root filesystem mounted in read-only mode."
-               log_warning_msg "The root filesystem is currently mounted in read-only mode. 
-A maintenance shell will now be started. 
-After performing system maintenance, press CONTROL-D 
-to terminate the maintenance shell and restart the system."
-               # Start a single user shell on the console
-               if ! sulogin $CONSOLE
-               then
-                       log_failure_msg "Attempt to start maintenance shell failed. 
-Will restart in 5 seconds."
-                       sleep 5
-               fi
-               [ "$VERBOSE" = no ] || log_action_msg "Will now restart"
-               reboot -f
-       elif [ "$FSCKCODE" -gt 1 ]
-       then
-               log_failure_msg "The file system check corrected errors on the root partition 
-but requested that the system be restarted."
-               log_warning_msg "The system will be restarted in 5 seconds."
-               sleep 5
-               [ "$VERBOSE" = no ] || log_action_msg "Will now restart"
-               reboot -f
-       fi
-
-       #
-       # Remount root to final mode (rw or ro).
-       #
-       # See the comments above at the previous "mount -o remount"
-       # for an explanation why we try this twice.
-       #
-       if ! mount -n -o remount,$rootopts,$rootmode $fstabroot / 2>/dev/null
-       then
-               mount -n -o remount,$rootopts,$rootmode /
-       fi
-
-       #
-       # We only create/modify /etc/mtab if the location where it is
-       # stored is writable. If /etc/mtab is a symlink into /proc/
-       # then it is not writable.
-       #
-       INIT_MTAB_FILE=no
-       MTAB_PATH="$(readlink -f /etc/mtab || :)"
-       case "$MTAB_PATH" in
-         /proc/*)
-               ;;
-         /*)
-               if touch "$MTAB_PATH" >/dev/null 2>&1
-               then
-                       :> "$MTAB_PATH"
-                       rm -f ${MTAB_PATH}~
-                       INIT_MTAB_FILE=yes
-               fi
-               ;;
-         "")
-               [ -L /etc/mtab ] && MTAB_PATH="$(readlink /etc/mtab)"
-               if [ "$MTAB_PATH" ]
-               then
-                       log_failure_msg "Cannot initialize ${MTAB_PATH}."
-               else
-                       log_failure_msg "Cannot initialize /etc/mtab."
-               fi
-               ;;
-         *)
-               log_failure_msg "Illegal mtab location '${MTAB_PATH}'."
-               ;;
-       esac
-
-       if [ "$INIT_MTAB_FILE" = yes ]
-       then
-               [ "$roottype" != none ] &&
-                       mount -f -o $rootopts -t $roottype $fstabroot /
-               [ "$devfs" ] && mount -f $devfs
-       fi
-
-       #
-       # Remove /dev/shm/root if we created it.
-       #
-       rm -f /dev/shm/root
-}
-
-case "$1" in
-  start|"")
-       do_start
-       ;;
-  restart|reload|force-reload)
-       echo "Error: argument '$1' not supported" >&2
-       exit 3
-       ;;
-  stop)
-       # No-op
-       ;;
-  *)
-       echo "Usage: checkroot.sh [start|stop]" >&2
-       exit 3
-       ;;
-esac
-
-:
-#! /bin/sh
-#
-# This file was automatically customized by debmake on Fri,  6 Nov 1998 23:00:08 -0600
-#
-# Written by Miquel van Smoorenburg <miquels@drinkel.ow.org>.
-# Modified for Debian GNU/Linux by Ian Murdock <imurdock@gnu.ai.mit.edu>.
-# Modified for Debian by Christoph Lameter <clameter@debian.org>
-# Modified for chrony by John Hasler <jhasler@debian.org> 10 Nov 1998
-
-PATH=/bin:/usr/bin:/sbin:/usr/sbin
-DAEMON=/usr/sbin/chronyd
-FLAGS="defaults"
-NAME="chronyd"
-DESC="time daemon"
-
-test -f $DAEMON || exit 0
-
-case "$1" in
-  start)
-    start-stop-daemon --start --verbose --exec $DAEMON
-    ;;
-  stop)
-    start-stop-daemon --stop --verbose --oknodo --exec $DAEMON
-    ;;
-  restart|force-reload)
-        #
-        #       If the "reload" option is implemented, move the "force-reload"
-        #       option to the "reload" entry above. If not, "force-reload" is
-        #       just the same as "restart".
-        #                                                                                   
-        echo -n "Restarting $DESC: "
-        start-stop-daemon --stop --quiet --exec $DAEMON
-        sleep 1
-        start-stop-daemon --start --quiet --exec $DAEMON -- -r
-        echo "$NAME."
-        ;;
-  *)
-    echo "Usage: /etc/init.d/chrony {start|stop|restart|force-reload}"
-    exit 1
-    ;;
-esac
-
-exit 0
-#!/bin/sh
-### BEGIN INIT INFO
-# Provides:          console-screen
-# Required-Start:    $local_fs $remote_fs
-# Required-Stop:     $local_fs $remote_fs
-# Default-Start:     S 2 3 4 5
-# Default-Stop:      0 1 6
-# Should-Start:      $syslog
-# Should-Stop: 
-# Description: Set console screen modes and fonts
-# Short-Description:   Prepare console
-### END INIT INFO
-
-#
-# This is the boot script for the `console-tools' package.
-#
-# It loads parameters from /etc/console-tools/config, maybe loads
-# default screen-font, screen font-map, and application charset-map,
-# and maybe start "vcstime"
-#
-# (c) 1997 Yann Dirson
-
-# If setupcon is present, then we've been superseded by console-setup.
-if type setupcon >/dev/null 2>&1; then
-    exit 0
-fi
-
-# check if usplash is runing and skip this, we'll get run again later
-if pidof usplash > /dev/null; then
-    exit 0
-fi
-
-if [ -r /etc/console-tools/config ] ; then
-    . /etc/console-tools/config
-fi
-
-if [ -d /etc/console-tools/config.d ]; then
-    for i in `run-parts --list /etc/console-tools/config.d `; do
-       . $i
-    done
-fi
-
-. /lib/lsb/init-functions
-
-PATH=/sbin:/bin:/usr/sbin:/usr/bin
-SETFONT="/usr/bin/consolechars"
-SETFONT_OPT=""
-CHARSET="/usr/bin/charset"
-VCSTIME="/usr/sbin/vcstime"
-
-# Different device name for 2.6 kernels and devfs
-if [ `uname -r | cut -f 2 -d .` = 6 ] && [ -e /dev/.devfsd ]; then
-    VCSTIME_OPT="-2 /dev/vcsa0"
-else
-    VCSTIME_OPT=""
-fi
-
-
-
-# set DEVICE_PREFIX depending on devfs/udev
-if [ -d /dev/vc ]; then
-    DEVICE_PREFIX="/dev/vc/"
-else
-    DEVICE_PREFIX="/dev/tty"
-fi
-
-reset_vga_palette ()
-{
-       if [ -f /proc/fb ]; then
-           # They have a framebuffer device.
-           # That means we have work to do...
-           echo -n "\e]R"
-       fi
-}
-
-setup ()
-{
-    # be sure the main program is installed
-    [ -x "${SETFONT}" ] || return 0
-
-    VT="no"
-    # If we can't access the console, quit
-    CONSOLE_TYPE=`fgconsole 2>/dev/null` || return 0
-
-    if [ ! $CONSOLE_TYPE = "serial" ]  ; then
-       readlink /proc/self/fd/0 | grep -q -e /dev/vc -e '/dev/tty[^p]' -e /dev/console
-       if [ $? -eq 0 ] ; then
-           VT="yes"
-           reset_vga_palette
-       fi
-    fi
-
-    [ $VT = "no" ] && return 0
-
-    # start vcstime
-    if [ "${DO_VCSTIME}" = "yes" -a -x ${VCSTIME} ] ; then
-       [ "$VERBOSE" != "no" ] && log_action_begin_msg "Starting clock on text console"
-       ${VCSTIME} ${VCSTIME_OPT} &
-        [ "$VERBOSE" != "no" ] && log_action_end_msg 0
-    fi
-
-
-    # Global default font+sfm
-    if [ "${SCREEN_FONT}" ]
-       then
-       [ "$VERBOSE" != "no" ] && log_action_begin_msg "Setting up general console font"
-       SCREEN_FONT="-f ${SCREEN_FONT}"
-
-       # maybe use an external SFM
-       [ "${SCREEN_FONT_MAP}" ] && SCREEN_FONT_MAP="-u ${SCREEN_FONT_MAP}"
-
-       # Try to be cleverer and run for all consoles, but this is run
-       # _before_ getty and so only one console running. So,
-       # Set for the first 6 VCs (as they are allocated in /etc/inittab)
-       NUM_CONSOLES=`fgconsole --next-available`
-       NUM_CONSOLES=$(($NUM_CONSOLES - 1))
-       [ ${NUM_CONSOLES} -eq 1 ] && NUM_CONSOLES=6
-       i=1
-       while [ $i -le $NUM_CONSOLES ]
-           do
-           if ! ${SETFONT} --tty=${DEVICE_PREFIX}$i ${SETFONT_OPT} ${SCREEN_FONT} ${SCREEN_FONT_MAP} ; then
-             [ "$VERBOSE" != "no" ] && log_action_end_msg 1
-             break
-           elif [ "$i" -eq "$NUM_CONSOLES" ]; then
-             [ "$VERBOSE" != "no" ] && log_action_end_msg 0
-           fi
-           i=$(($i + 1))
-       done
-    fi
-
-
-    # Per-VC font+sfm
-    VCS="`set | grep '^SCREEN_FONT_vc[0-9]*=' | sed -e 's/^SCREEN_FONT_vc//' -e 's/=.*//'`"
-    if [ "${VCS}" ]
-       then
-       [ "$VERBOSE" != "no" ] && log_action_begin_msg "Setting up per-VC fonts"
-       for vc in ${VCS}
-         do
-           # extract FONTNAME info from variable setting
-         eval font=\$SCREEN_FONT_vc$vc
-         # eventually find an associated SFM
-         eval sfm=\${SCREEN_FONT_MAP_vc${vc}}
-         [ "$sfm" ] && sfm="-u $sfm"
-
-         ${SETFONT} --tty=${DEVICE_PREFIX}$vc ${SETFONT_OPT} -f $font $sfm
-       done
-       [ "$VERBOSE" != "no" ] && log_action_end_msg 0
-    fi
-
-
-    # Global ACM
-    [ "${APP_CHARSET_MAP}" ] && ${CHARSET} G0 ${APP_CHARSET_MAP}
-
-
-    # Per-VC ACMs
-    VCS="`set | grep '^APP_CHARSET_MAP_vc[0-9]*=' | sed -e 's/^APP_CHARSET_MAP_vc//' -e 's/=.*//'`"
-    if [ "${VCS}" ]
-       then
-       [ "$VERBOSE" != "no" ] && log_action_begin_msg "Setting up per-VC ACM\'s"
-       for vc in ${VCS}
-         do
-           # extract FONTNAME info from variable setting
-         eval acm=\$APP_CHARSET_MAP_vc$vc
-         ${CHARSET} --tty="${DEVICE_PREFIX}$vc" G0 "$acm"
-       done
-       [ "$VERBOSE" != "no" ] && log_action_end_msg 0
-    fi
-
-
-    # Go to UTF-8 mode as necessary
-    # 
-    ENV_FILE=''
-    [ -r /etc/environment ] && ENV_FILE="/etc/environment"
-    [ -r /etc/default/locale ] && ENV_FILE="/etc/default/locale"
-    [ "$ENV_FILE" ] && CHARMAP=$(set -a && . "$ENV_FILE" && locale charmap)
-    if test "$CHARMAP" = "UTF-8" 
-    then
-        unicode_start 2> /dev/null || true
-    else
-        unicode_stop 2> /dev/null|| true
-    fi
-
-    # screensaver stuff
-    setterm_args=""
-    if [ "$BLANK_TIME" ]; then
-        setterm_args="$setterm_args -blank $BLANK_TIME"
-    fi
-    if [ "$BLANK_DPMS" ]; then
-        setterm_args="$setterm_args -powersave $BLANK_DPMS"
-    fi
-    if [ "$POWERDOWN_TIME" ]; then
-        setterm_args="$setterm_args -powerdown $POWERDOWN_TIME"
-    fi
-    if [ "$setterm_args" ]; then
-        setterm $setterm_args 
-    fi
-
-    # Keyboard rate and delay
-    KBDRATE_ARGS=""
-    if [ -n "$KEYBOARD_RATE" ]; then
-        KBDRATE_ARGS="-r $KEYBOARD_RATE"
-    fi
-    if [ -n "$KEYBOARD_DELAY" ]; then
-        KBDRATE_ARGS="$KBDRATE_ARGS -d $KEYBOARD_DELAY"
-    fi
-    if [ -n "$KBDRATE_ARGS" ]; then
-       [ "$VERBOSE" != "no" ] && log_action_begin_msg "Setting keyboard rate and delay"
-        kbdrate -s $KBDRATE_ARGS
-       [ "$VERBOSE" != "no" ] && log_action_end_msg 0
-    fi
-
-    # Inform gpm if present, of potential changes.
-    if [ -f /var/run/gpm.pid ]; then
-       kill -WINCH `cat /var/run/gpm.pid` 2> /dev/null
-    fi
-
-    # Allow user to remap keys on the console
-    if [ -r /etc/console-tools/remap ]
-       then
-       dumpkeys < ${DEVICE_PREFIX}1 | sed -f /etc/console-tools/remap | loadkeys --quiet
-    fi
-    # Set LEDS here
-    if [ "$LEDS" != "" ]
-       then
-       i=1
-       while [ $i -le $NUM_CONSOLES ]
-         do
-          setleds -D $LEDS < $DEVICE_PREFIX$i
-         i=$(($i + 1))
-       done
-    fi
-}
-
-case "$1" in
-    start|reload|restart|force-reload)
-       log_action_msg "Setting console screen modes and fonts"
-       setup
-       ;;
-    stop)
-       ;;
-    *)
-       setup
-       ;;
-esac
-#!/bin/sh
-# Start/stop the cron daemon.
-#
-### BEGIN INIT INFO
-# Provides:          cron
-# Required-Start:    $syslog $time
-# Required-Stop:     $syslog $time
-# Default-Start:     2 3 4 5
-# Default-Stop:      0 1 6
-# Short-Description: Regular background program processing daemon
-# Description:       cron is a standard UNIX program that runs user-specified 
-#                    programs at periodic scheduled times. vixie cron adds a 
-#                    number of features to the basic UNIX cron, including better
-#                    security and more powerful configuration options.
-### END INIT INFO
-
-
-test -f /usr/sbin/cron || exit 0
-
-#LSBNAMES='-l'  # Uncomment for LSB name support in /etc/cron.d/
-
-. /lib/lsb/init-functions
-
-case "$1" in
-start) log_daemon_msg "Starting periodic command scheduler" "crond"
-        start-stop-daemon --start --quiet --pidfile /var/run/crond.pid --name cron --startas /usr/sbin/cron -- $LSBNAMES
-        log_end_msg $?
-       ;;
-stop)  log_daemon_msg "Stopping periodic command scheduler" "crond"
-        start-stop-daemon --stop --quiet --pidfile /var/run/crond.pid --name cron
-        log_end_msg $?
-        ;;
-restart) log_daemon_msg "Restarting periodic command scheduler" "crond" 
-        start-stop-daemon --stop --retry 5 --quiet --pidfile /var/run/crond.pid --name cron
-        start-stop-daemon --start --quiet --pidfile /var/run/crond.pid --name cron --startas /usr/sbin/cron -- $LSBNAMES
-        log_end_msg $?
-        ;;
-reload|force-reload) log_daemon_msg "Reloading configuration files for periodic command scheduler" "crond"
-       # cron reloads automatically
-        log_end_msg 0
-        ;;
-*)     log_action_msg "Usage: /etc/init.d/cron {start|stop|restart|reload|force-reload}"
-        exit 2
-        ;;
-esac
-exit 0
-#!/bin/sh
-### BEGIN INIT INFO
-# Provides:          dbus
-# Required-Start:    $remote_fs $syslog
-# Required-Stop:     $remote_fs $syslog
-# Default-Start:     2 3 4 5
-# Default-Stop:      1
-# Short-Description: D-Bus systemwide message bus
-# Description:       D-Bus is a simple interprocess messaging system, used
-#                    for sending messages between applications.
-### END INIT INFO
-# -*- coding: utf-8 -*-
-# Debian init.d script for D-BUS
-# Copyright Â© 2003 Colin Walters <walters@debian.org>
-# Copyright Â© 2005 Sjoerd Simons <sjoerd@debian.org>
-
-set -e
-
-DAEMON=/usr/bin/dbus-daemon
-UUIDGEN=/usr/bin/dbus-uuidgen
-UUIDGEN_OPTS=--ensure
-NAME=dbus
-DAEMONUSER=messagebus
-PIDDIR=/var/run/dbus
-PIDFILE=$PIDDIR/pid
-DESC="system message bus"
-EVENTDIR=/etc/dbus-1/event.d
-
-test -x $DAEMON || exit 0
-
-. /lib/lsb/init-functions
-
-# Source defaults file; edit that file to configure this script.
-PARAMS=""
-if [ -e /etc/default/dbus ]; then
-  . /etc/default/dbus
-fi
-
-if [ -n "$ENABLED" ]; then
-    log_warning_msg "The ENABLED option in /etc/default/$NAME has been deprecated."
-    log_warning_msg "Please remove this setting from the configuration file."
-    log_warning_msg "To disable the service use a runlevel editor like sysv-rc-conf or bum instead."
-fi
-
-create_machineid() {
-  # Create machine-id file
-  if [ -x $UUIDGEN ]; then
-    $UUIDGEN $UUIDGEN_OPTS
-  fi
-}
-
-dependent_services()
-{
-  # Do nothing if we are called by init
-  [ ! -z $runlevel ] && return 
-
-  # Determine current runlevel
-  r=$(/sbin/runlevel) || true
-  r=${r#*\ }
-
-  # Do nothing if we can't determine the runlevel (e.g. inside chroots)
-  [ "$r" = "unknown" ] && return
-
-  if [ "$1" = "stop" ] ; then
-    param="--reverse"
-    action="stop"
-  else
-    param=""
-    action="start"
-  fi
-
-  # Get the list of services active in this runlevel
-  if [ -d /etc/rc${r}.d/ ] ; then # sysv-rc
-    services=$(grep -s -l "^# Required-Start:.*dbus" /etc/rc${r}.d/S??* | sort $param)
-  elif [ -f /etc/runlevel.conf ] ; then # file-rc
-    list=$(grep -s -l "^# Required-Start:.*dbus" /etc/init.d/* || true)
-    services=$( for i in $list ; do
-      grep -E "^[[:digit:]]{2}[[:space:]]+([0-9,S]+|[-])[[:space:]]+.*$r.*[[:space:]]+$i$" /etc/runlevel.conf
-    done  | sort $param | awk '{print $4}' )
-  else
-    services=""
-    log_warning_msg "Unable to determine dependent services: unknown init system"
-  fi
-
-  # Start the services in the correct order
-  for i in $services ; do
-    service=$(basename $i)
-    service=${service#S??}
-    invoke-rc.d $service $action || true
-  done
-
-}
-
-
-start_it_up()
-{
-  if [ ! -d $PIDDIR ]; then
-    mkdir -p $PIDDIR
-    chown $DAEMONUSER $PIDDIR
-    chgrp $DAEMONUSER $PIDDIR
-  fi
-
-  if ! mountpoint -q /proc/ ; then
-    log_failure_msg "Can't start $DESC - /proc is not mounted"
-    return
-  fi
-
-  if [ -e $PIDFILE ]; then
-    PIDDIR=/proc/$(cat $PIDFILE)
-    if [ -d ${PIDDIR} -a  "$(readlink -f ${PIDDIR}/exe)" = "${DAEMON}" ]; then 
-      log_success_msg "$DESC already started; not starting."
-      return
-    else
-      log_success_msg "Removing stale PID file $PIDFILE."
-      rm -f $PIDFILE
-    fi
-  fi
-
-  create_machineid
-
-  log_daemon_msg "Starting $DESC" "$NAME"
-  start-stop-daemon --start --quiet --pidfile $PIDFILE \
-    --user $DAEMONUSER --exec $DAEMON -- --system $PARAMS
-  log_end_msg $?
-  if [ -d $EVENTDIR ]; then
-      run-parts --arg=start $EVENTDIR || true
-  fi
-  dependent_services start
-}
-
-shut_it_down()
-{
-  dependent_services stop
-  if [ -d $EVENTDIR ]; then
-      run-parts --reverse --arg=stop $EVENTDIR || true
-  fi
-  log_daemon_msg "Stopping $DESC" "$NAME"
-  start-stop-daemon --stop --retry 5 --quiet --oknodo --pidfile $PIDFILE \
-    --user $DAEMONUSER
-  # We no longer include these arguments so that start-stop-daemon
-  # can do its job even given that we may have been upgraded.
-  # We rely on the pidfile being sanely managed
-  # --exec $DAEMON -- --system $PARAMS
-  log_end_msg $?
-  rm -f $PIDFILE
-}
-
-reload_it()
-{
-  create_machineid
-  log_action_begin_msg "Reloading $DESC config"
-  dbus-send --print-reply --system --type=method_call \
-            --dest=org.freedesktop.DBus \
-            / org.freedesktop.DBus.ReloadConfig > /dev/null
-  # hopefully this is enough time for dbus to reload it's config file.
-  log_action_end_msg $?
-}
-
-case "$1" in
-  start)
-    start_it_up
-  ;;
-  stop)
-    shut_it_down
-  ;;
-  reload|force-reload)
-    reload_it
-  ;;
-  restart)
-    shut_it_down
-    start_it_up
-  ;;
-  *)
-    echo "Usage: /etc/init.d/$NAME {start|stop|reload|restart|force-reload}" >&2
-    exit 2
-  ;;
-esac
-
-#! /bin/sh
-
-# $Id: dns-clean,v 1.1.1.1 2004/05/07 03:12:59 john Exp $
-
-# dns-clean by John Hasler 1999-2003
-# Any possessor of a copy of this program may treat it as if it
-# were in the public domain.  I waive all rights.
-
-# This script should be run at bootup to clean up any mess left by 0dns-up.
-# It should be run before ppp is started.
-# It should never be run while ppp is up.
-
-### BEGIN INIT INFO
-# Provides:          dns-clean
-# Required-Start:    $local_fs
-# Required-Stop:     $local_fs
-# Default-Start:     S
-# Default-Stop:
-# Short-Description: Cleans up any mess left by 0dns-up
-# Description: 0dns-up often leaves behind some cruft. This Script is meant
-#              to clean up any such mess.
-### END INIT INFO
-
-PATH=/sbin:/bin:/usr/sbin:/usr/bin
-
-test -f /usr/sbin/pppconfig || exit 0
-# We might have a tmpfs /var/run.
-mkdir /var/run/pppconfig >/dev/null 2>&1 || true
-test -f /etc/ppp/ip-down.d/0dns-down || exit 0
-
-. /lib/lsb/init-functions
-. /etc/default/rcS
-
-case "$1" in
-  start)
-       [ "$VERBOSE" != no ] && log_begin_msg "Restoring resolver state..."
-       /etc/ppp/ip-down.d/0dns-down "0dns-clean"
-       [ "$VERBOSE" != no ] && log_end_msg $?
-       ;;
-  stop|restart|force-reload)
-       ;;
-  *)
-        ;;
-esac
-
-exit 0
-
-
-
-#! /bin/sh
-#
-# evms          Enterprise Volume Management System
-#
-#              Written by Miquel van Smoorenburg <miquels@cistron.nl>.
-#              Modified for Debian GNU/Linux
-#              by Ian Murdock <imurdock@gnu.ai.mit.edu>.
-#               Modified for evms package
-#               by Matt Zimmerman <mdz@debian.org>
-#
-
-### BEGIN INIT INFO
-# Provides:          evms
-# Default-Start:     2 3 4 5
-# Default-Stop:      0 1 6
-# Required-Start:    
-# Required-Stop:     
-# Short-Description: Activates EVMS volumes
-# Description:       Activates any EVMS volumes that are left unactivated
-#                    by the initramfs for some reason (or if the user does
-#                    not use initramfs). This possibly includes setting up
-#                    RAID, LVM, snapshots, BBR etc., but does not start a
-#                    service.
-### END INIT INFO
-
-PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
-NAME=evms
-DESC="Enterprise Volume Management System"
-
-test -x /sbin/evms_activate || exit 0
-
-. /lib/lsb/init-functions
-. /etc/default/rcS
-
-set -e
-
-case "$1" in
-  start|reload|restart|force-reload)
-       log_begin_msg "Starting $DESC..."
-       status=0
-       if [ "$VERBOSE" != no ]; then
-               evms_activate || status=$?
-       else
-               # Messages are still written to the log
-               evms_activate >/dev/null 2>&1 || status=$?
-       fi
-       log_end_msg $status
-       ;;
-  stop)
-       ;;
-  status)
-       echo "no daemons started by this script"
-        log_end_msg 0
-       ;;
-  *)
-       N=/etc/init.d/$NAME
-       log_success_msg "Usage: $N {start|stop|restart|reload|force-reload|status}"
-       exit 1
-       ;;
-esac
-
-exit 0
-#! /bin/sh
-#
-# Originally based on:
-# Version:     @(#)skeleton  1.8  03-Mar-1998  miquels@cistron.nl
-#
-# Modified for gdm, Steve Haslam <steve@arise.dmeon.co.uk> 14mar99
-# modified to remove --exec, as it does not work on upgrades. 18jan2000
-# modified to use --name, to detect stale PID files 18mar2000
-# sleep until gdm dies, then restart it 16jul2000
-# get along with other display managers (Branden Robinson, Ryan Murray) 05sep2001
-
-set -e
-
-# To start gdm even if it is not the default display manager, change
-# HEED_DEFAULT_DISPLAY_MANAGER to "false."
-HEED_DEFAULT_DISPLAY_MANAGER=true
-DEFAULT_DISPLAY_MANAGER_FILE=/etc/X11/default-display-manager
-PATH=/sbin:/bin:/usr/sbin:/usr/bin
-DAEMON=/usr/sbin/gdm
-PIDFILE=/var/run/gdm.pid
-UPGRADEFILE=/var/run/gdm.upgrade
-
-if [ -e $UPGRADEFILE -a "$1" != "restart" -a "$1" != "force-reload" ]; then
-       SSD_ARG="--startas $DAEMON"
-       rm -f $UPGRADEFILE
-else
-       SSD_ARG="--exec $DAEMON"
-fi
-
-# Allow cdd to override the config
-if [ -f /etc/gdm/gdm-cdd.conf ]; then
-       CONFIG_FILE="--config=/etc/gdm/gdm-cdd.conf"
-fi
-
-test -x $DAEMON || exit 0
-
-if [ -r /etc/environment ]; then
-  if LANG=$(pam_getenv -l LANG); then
-    export LANG
-  fi
-  if LANGUAGE=$(pam_getenv -l LANGUAGE); then
-    export LANGUAGE
-  fi
-
-fi
-
-. /lib/lsb/init-functions
-
-case "$1" in
-  start)
-       if [ -e "$DEFAULT_DISPLAY_MANAGER_FILE" -a "$HEED_DEFAULT_DISPLAY_MANAGER" = "true" -a "$(cat $DEFAULT_DISPLAY_MANAGER_FILE 2>/dev/null)" != "$DAEMON" ]; then
-               log_warning_msg "Not starting GNOME Display Manager (gdm); it is not the default display manager."
-       else
-               # if usplash is runing, make sure to stop it now, yes "start" kills it.
-               if pidof usplash > /dev/null; then
-                       /etc/init.d/usplash start
-               fi
-               log_begin_msg "Starting GNOME Display Manager..."
-               start-stop-daemon --start --quiet --oknodo --pidfile $PIDFILE --name gdm $SSD_ARG -- $CONFIG_FILE >/dev/null 2>&1 || log_end_msg 1
-               log_end_msg 0
-       fi
-  ;;
-  stop)
-       log_begin_msg "Stopping GNOME Display Manager..."
-       start-stop-daemon --stop  --quiet --oknodo --pidfile $PIDFILE --name gdm $SSD_ARG --retry 30 >/dev/null 2>&1
-       log_end_msg 0
-  ;;
-  reload)
-       log_begin_msg "Reloading GNOME Display Manager configuration..."
-       log_warning_msg "Changes will take effect when all current X sessions have ended."
-       start-stop-daemon --stop --signal USR1 --quiet --pidfile \
-               $PIDFILE --name gdm $SSD_ARG >/dev/null 2>&1
-       log_end_msg 0
-  ;;
-  restart|force-reload)
-       $0 stop || true
-       $0 start
-  ;;
-  *)
-       log_success_msg "Usage: /etc/init.d/gdm {start|stop|restart|reload|force-reload}"
-       exit 1
-  ;;
-esac
-
-exit 0
-#! /bin/sh -e
-#
-### BEGIN INIT INFO
-# Provides:          glibc
-# Required-Start:
-# Required-Stop:
-# Default-Start:     S
-# Default-Stop:
-### END INIT INFO
-#
-# 
-# This script detects deprecated kernel versions incompatible with
-# the current version of the glibc
-
-# glibc kernel version check: KERNEL_VERSION_CHECK
-linux_compare_versions () {
-    verA=$(($(echo "$1" | sed 's/\([0-9]*\)\.\([0-9]*\)\.\([0-9]*\).*/\1 \* 10000 + \2 \* 100 + \3/')))
-    verB=$(($(echo "$3" | sed 's/\([0-9]*\)\.\([0-9]*\)\.\([0-9]*\).*/\1 \* 10000 + \2 \* 100 + \3/')))
-
-    test $verA -$2 $verB
-}
-
-kfreebsd_compare_versions () {
-    verA=$(($(echo "$1" | sed 's/\([0-9]*\)\.\([0-9]*\).*/\1 \* 100 + \2/')))
-    verB=$(($(echo "$3" | sed 's/\([0-9]*\)\.\([0-9]*\).*/\1 \* 100 + \2/')))
-
-    test $verA -$2 $verB
-}
-
-kernel26_help() {
-    echo ""
-    echo "The installation of a 2.6 kernel _could_ ask you to install a new libc"
-    echo "first, this is NOT a bug, and should *NOT* be reported. In that case,"
-    echo "please add etch sources to your /etc/apt/sources.list and run:"
-    echo "  apt-get install -t etch linux-image-2.6"
-    echo "Then reboot into this new kernel, and proceed with your upgrade"
-}
-
-exit_check () {
-    sleep 5
-    exit 1
-}
-
-    system=`uname -s`
-    if [ "$system" = "Linux" ]
-    then
-        # Test to make sure z < 255, in x.y.z-n form of kernel version
-        # Also make sure we don't trip on x.y.zFOO-n form
-        #kernel_rev=$(uname -r | tr -- - . | cut -d. -f3 | tr -d '[:alpha:]')
-        kernel_rev=$(uname -r | sed 's/\([0-9]*\.[0-9]*\.\)\([0-9]*\)\(.*\)/\2/')
-        if [ "$kernel_rev" -ge 255 ]
-        then
-            echo "WARNING: Your kernel version indicates a revision number"
-            echo "of 255 or greater.  Glibc has a number of built in"
-            echo "assumptions that this revision number is less than 255."
-            echo "If you\'ve built your own kernel, please make sure that any"
-            echo "custom version numbers are appended to the upstream"
-            echo "kernel number with a dash or some other delimiter."
-
-            exit_check
-        fi
-
-        # sanity checking for the appropriate kernel on each architecture.
-        realarch=`uname -m`
-        kernel_ver=`uname -r`
-
-        # convert "armv4l" and similar to just "arm", and "mips64" and similar
-        # to just "mips"
-        case $realarch in
-          arm*) realarch="arm";;
-          mips*) realarch="mips";;
-        esac
-
-
-        # From glibc 2.3.5-7 real-i386 is dropped.
-        if [ "$realarch" = i386 ]
-        then
-            echo "WARNING: This machine has real i386 class processor."
-            echo "Debian etch and later does not support such old hardware"
-            echo "any longer."
-            echo "The reason is that \"bswap\" instruction is not supported"
-            echo "on i386 class processors, and some core libraries have"
-            echo "such instruction.  You\'ll see illegal instruction error"
-            echo "when you upgrade your Debian system."
-            exit_check
-        fi
-
-        # arm boxes require __ARM_NR_set_tls in the kernel to function properly.
-        if [ "$realarch" = arm ]
-        then
-            if linux_compare_versions "$kernel_ver" lt 2.6.12
-            then
-                echo WARNING: This version of glibc requires that you be running
-                echo kernel version 2.6.12 or later.  Earlier kernels contained
-                echo bugs that may render the system unusable if a modern version
-                echo of glibc is installed.
-                kernel26_help
-                exit_check
-            fi 
-        fi
-
-        # Alpha and HPPA boxes require latest fixes in the kernel to function properly.
-        if [ "$realarch" = parisc -o "$realarch" = alpha ]
-        then
-            if linux_compare_versions "$kernel_ver" lt 2.6.9
-            then
-                echo WARNING: This version of glibc requires that you be running
-                echo kernel version 2.6.9 or later.  Earlier kernels contained
-                echo bugs that may render the system unusable if a modern version
-                echo of glibc is installed.
-                kernel26_help
-                exit_check
-            fi
-        fi
-
-        # sh4 boxes require kernel version 2.6.11 minimum
-        if [ "$realarch" = sh4 ]
-        then
-            if linux_compare_versions "$kernel_ver" lt 2.6.11
-            then
-                echo WARNING: This version of glibc requires that you be running
-                echo kernel version 2.6.11 or later.  Earlier kernels contained
-                echo bugs that may render the system unusable if a modern version
-                echo of glibc is installed.
-                kernel26_help
-                exit_check
-            fi 
-        fi
-
-        # The GNU libc requires 2.6 kernel (except on m68k) because we drop to
-        # support linuxthreads
-        if [ "$realarch" != m68k ]
-        then
-            if linux_compare_versions "$kernel_ver" lt 2.6.8
-            then
-                echo WARNING: POSIX threads library NPTL requires kernel version
-                echo 2.6.8 or later.  If you use a kernel 2.4, please upgrade it
-                echo before installing glibc.
-                kernel26_help
-                exit_check
-            fi
-        fi
-
-        # The GNU libc is now built with --with-kernel= >= 2.4.1 on m68k
-        if [ "$realarch" = m68k ]
-        then
-            if linux_compare_versions "$kernel_ver" lt 2.4.1
-            then
-                echo WARNING: This version of glibc requires that you be running
-                echo kernel version 2.4.1 or later.  Earlier kernels contained
-                echo bugs that may render the system unusable if a modern version
-                echo of glibc is installed.
-                kernel26_help
-                exit_check
-            fi
-        fi
-
-        # From glibc 2.6-3 SPARC V8 support is dropped.
-        if [ "$realarch" = sparc ]
-        then
-            # The process could be run using linux32, check for /proc.
-            if [ -f /proc/cpuinfo ]
-            then
-               case "$(sed '/^type/!d;s/^type.*: //g' /proc/cpuinfo)" in
-                   sun4u)
-                      # UltraSPARC CPU
-                      ;;
-                   sun4v)
-                      # Niagara CPU
-                      ;;
-                   *)
-                      echo "WARNING: This machine has a SPARC V8 or earlier class processor."
-                      echo "Debian lenny and later does not support such old hardware"
-                      echo "any longer."
-                      exit_check
-                      ;;
-               esac
-            fi
-        fi
-    elif [ $system = "GNU/kFreeBSD" ] ; then
-        kernel_ver=`uname -r`
-        if kfreebsd_compare_versions "$kernel_ver" lt 6.0
-        then
-            echo WARNING: This version of glibc uses UMTX_OP_WAIT and UMTX_OP_WAKE
-           echo syscalls that are not present in the current running kernel. They
-           echo have been added in kFreeBSD 6.0.  Your system should still work,
-           echo but it is recommended to upgrade to a more recent version.
-        fi
-    fi
-
-: exit 0
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          halt
-# Required-Start:    umountroot
-# Required-Stop:
-# Should-Start:      lvm raid2
-# Should-Stop:
-# Default-Start:     0
-# Default-Stop:
-# Short-Description: Execute the halt command.
-# Description:
-### END INIT INFO
-
-PATH=/usr/sbin:/usr/bin:/sbin:/bin
-[ -f /etc/default/halt ] && . /etc/default/halt
-
-. /lib/lsb/init-functions
-
-do_stop () {
-       if [ "$INIT_HALT" = "" ]
-       then
-               case "$HALT" in
-                 [Pp]*)
-                       INIT_HALT=POWEROFF
-                       ;;
-                 [Hh]*)
-                       INIT_HALT=HALT
-                       ;;
-                 *)
-                       INIT_HALT=POWEROFF
-                       ;;
-               esac
-       fi
-
-       # See if we need to cut the power.
-       if [ "$INIT_HALT" = "POWEROFF" ] && [ -x /etc/init.d/ups-monitor ]
-       then
-               /etc/init.d/ups-monitor poweroff
-       fi
-
-       # Don't shut down drives if we're using RAID.
-       hddown="-h"
-       if grep -qs '^md.*active' /proc/mdstat
-       then
-               hddown=""
-       fi
-
-       # If INIT_HALT=HALT don't poweroff.
-       poweroff="-p"
-       if [ "$INIT_HALT" = "HALT" ]
-       then
-               poweroff=""
-       fi
-
-       log_action_msg "Will now halt"
-       sleep 1
-       halt -d -f -i $poweroff $hddown
-}
-
-case "$1" in
-  start)
-       # No-op
-       ;;
-  restart|reload|force-reload)
-       echo "Error: argument '$1' not supported" >&2
-       exit 3
-       ;;
-  stop)
-       do_stop
-       ;;
-  *)
-       echo "Usage: $0 start|stop" >&2
-       exit 3
-       ;;
-esac
-
-:
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          hostname
-# Required-Start:
-# Required-Stop:
-# Default-Start:     S
-# Default-Stop:
-# Short-Description: Set hostname.
-# Description:
-### END INIT INFO
-
-PATH=/sbin:/bin
-
-. /lib/init/vars.sh
-. /lib/lsb/init-functions
-
-do_start () {
-       [ -f /etc/hostname ] && HOSTNAME="$(cat /etc/hostname)"
-
-       # Keep current name if /etc/hostname is missing.
-       [ -z "$HOSTNAME" ] && HOSTNAME="$(hostname)"
-
-       # And set it to 'localhost' if no setting was found
-       [ -z "$HOSTNAME" ] && HOSTNAME=localhost
-
-       [ "$VERBOSE" != no ] && log_action_begin_msg "Setting hostname to '$HOSTNAME'"
-       hostname "$HOSTNAME"
-       ES=$?
-       [ "$VERBOSE" != no ] && log_action_end_msg $ES
-}
-
-case "$1" in
-  start|"")
-       do_start
-       ;;
-  restart|reload|force-reload)
-       echo "Error: argument '$1' not supported" >&2
-       exit 3
-       ;;
-  stop)
-       # No-op
-       ;;
-  *)
-       echo "Usage: hostname.sh [start|stop]" >&2
-       exit 3
-       ;;
-esac
-#!/bin/sh
-# hwclock.sh   Set and adjust the CMOS clock, according to the UTC
-#              setting in /etc/default/rcS (see also rcS(5)).
-#
-# Version:     @(#)hwclock.sh  2.00  14-Dec-1998  miquels@cistron.nl
-#
-# Patches:
-#              2000-01-30 Henrique M. Holschuh <hmh@rcm.org.br>
-#               - Minor cosmetic changes in an attempt to help new
-#                 users notice something IS changing their clocks
-#                 during startup/shutdown.
-#               - Added comments to alert users of hwclock issues
-#                 and discourage tampering without proper doc reading.
-
-# WARNING:     Please read /usr/share/doc/util-linux/README.Debian.hwclock
-#              before changing this file. You risk serious clock
-#              misbehaviour otherwise.
-
-### BEGIN INIT INFO
-# Provides:          hwclockfirst
-# Required-Start:    mountdevsubfs
-# Required-Stop:     umountroot
-# Default-Start:     S
-# Default-Stop:      0 6
-### END INIT INFO
-
-FIRST=yes      # debian/rules sets this to 'yes' when creating hwclockfirst.sh
-
-# Set this to any options you might need to give to hwclock, such
-# as machine hardware clock type for Alphas.
-HWCLOCKPARS=
-
-hwclocksh()
-{
-    [ ! -x /sbin/hwclock ] && return 0
-    . /etc/default/rcS
-
-    . /lib/lsb/init-functions
-    verbose_log_action_msg() { [ "$VERBOSE" = no ] || log_action_msg "$@"; }
-
-    [ "$GMT" = "-u" ] && UTC="yes"
-    case "$UTC" in
-       no|"")  GMT="--localtime"
-               UTC=""
-               if [ "X$FIRST" = "Xyes" ] && [ ! -r /etc/localtime ]; then
-                   if [ -z "$TZ" ]; then
-                       log_action_msg "System clock was not updated at this time"
-                       return 1
-                   fi
-               fi
-               ;;
-       yes)    GMT="--utc"
-               UTC="--utc"
-               ;;
-       *)      log_action_msg "Unknown UTC setting: \"$UTC\""; return 1 ;;
-    esac
-
-    case "$BADYEAR" in
-       no|"")  BADYEAR="" ;;
-       yes)    BADYEAR="--badyear" ;;
-       *)      log_action_msg "unknown BADYEAR setting: \"$BADYEAR\""; return 1 ;;
-    esac
-
-    case "$1" in
-       start)
-           if [ -w /etc ] && [ ! -f /etc/adjtime ] && [ ! -e /etc/adjtime ]; then
-               echo "0.0 0 0.0" > /etc/adjtime
-           fi
-
-           if [ ! -w /etc/adjtime ]; then
-               NOADJ="--noadjfile"
-           else
-               NOADJ=""
-           fi
-
-           if [ "$FIRST" != yes ]; then
-               # Uncomment the hwclock --adjust line below if you want
-               # hwclock to try to correct systematic drift errors in the
-               # Hardware Clock.
-               #
-               # WARNING: If you uncomment this option, you must either make
-               # sure *nothing* changes the Hardware Clock other than
-               # hwclock --systohc, or you must delete /etc/adjtime
-               # every time someone else modifies the Hardware Clock.
-               #
-               # Common "vilains" are: ntp, MS Windows, the BIOS Setup
-               # program.
-               #
-               # WARNING: You must remember to invalidate (delete)
-               # /etc/adjtime if you ever need to set the system clock
-               # to a very different value and hwclock --adjust is being
-               # used.
-               #
-               # Please read /usr/share/doc/util-linux/README.Debian.hwclock
-               # before enabling hwclock --adjust.
-
-               #/sbin/hwclock --adjust $GMT $BADYEAR
-               :
-           fi
-
-           if [ "$HWCLOCKACCESS" != no ]; then
-               log_action_msg "Setting the system clock"
-
-               # Copies Hardware Clock time to System Clock using the correct
-               # timezone for hardware clocks in local time, and sets kernel
-               # timezone. DO NOT REMOVE.
-               if /sbin/hwclock --hctosys $GMT $HWCLOCKPARS $BADYEAR $NOADJ; then
-                   #   Announce the local time.
-                   verbose_log_action_msg "System Clock set to: `date $UTC`"
-               else
-                   log_warning_msg "Unable to set System Clock to: `date $UTC`"
-               fi
-           else
-               verbose_log_action_msg "Not setting System Clock"
-           fi
-           ;;
-       stop|restart|reload|force-reload)
-           #
-           # Updates the Hardware Clock with the System Clock time.
-           # This will *override* any changes made to the Hardware Clock.
-           #
-           # WARNING: If you disable this, any changes to the system
-           #          clock will not be carried across reboots.
-           #
-           if [ "$HWCLOCKACCESS" != no ]; then
-               log_action_msg "Saving the system clock"
-               if [ "$GMT" = "-u" ]; then
-                   GMT="--utc"
-               fi
-               if /sbin/hwclock --systohc $GMT $HWCLOCKPARS $BADYEAR; then
-                   verbose_log_action_msg "Hardware Clock updated to `date`"
-               fi
-           else
-               verbose_log_action_msg "Not saving System Clock"
-           fi
-           ;;
-       show)
-           if [ "$HWCLOCKACCESS" != no ]; then
-               /sbin/hwclock --show $GMT $HWCLOCKPARS $BADYEAR
-           fi
-           ;;
-       *)
-           log_success_msg "Usage: hwclock.sh {start|stop|reload|force-reload|show}"
-           log_success_msg "       start sets kernel (system) clock from hardware (RTC) clock"
-           log_success_msg "       stop and reload set hardware (RTC) clock from kernel (system) clock"
-           return 1
-           ;;
-    esac
-}
-
-hwclocksh "$@"
-#!/bin/sh
-# hwclock.sh   Set and adjust the CMOS clock, according to the UTC
-#              setting in /etc/default/rcS (see also rcS(5)).
-#
-# Version:     @(#)hwclock.sh  2.00  14-Dec-1998  miquels@cistron.nl
-#
-# Patches:
-#              2000-01-30 Henrique M. Holschuh <hmh@rcm.org.br>
-#               - Minor cosmetic changes in an attempt to help new
-#                 users notice something IS changing their clocks
-#                 during startup/shutdown.
-#               - Added comments to alert users of hwclock issues
-#                 and discourage tampering without proper doc reading.
-
-# WARNING:     Please read /usr/share/doc/util-linux/README.Debian.hwclock
-#              before changing this file. You risk serious clock
-#              misbehaviour otherwise.
-
-### BEGIN INIT INFO
-# Provides:          hwclock
-# Required-Start:    mountdevsubfs
-# Required-Stop:     $local_fs
-# Default-Start:     S
-# Default-Stop:      0 6
-### END INIT INFO
-
-FIRST=no       # debian/rules sets this to 'yes' when creating hwclockfirst.sh
-
-# Set this to any options you might need to give to hwclock, such
-# as machine hardware clock type for Alphas.
-HWCLOCKPARS=
-
-hwclocksh()
-{
-    [ ! -x /sbin/hwclock ] && return 0
-    . /etc/default/rcS
-
-    . /lib/lsb/init-functions
-    verbose_log_action_msg() { [ "$VERBOSE" = no ] || log_action_msg "$@"; }
-
-    [ "$GMT" = "-u" ] && UTC="yes"
-    case "$UTC" in
-       no|"")  GMT="--localtime"
-               UTC=""
-               if [ "X$FIRST" = "Xyes" ] && [ ! -r /etc/localtime ]; then
-                   if [ -z "$TZ" ]; then
-                       log_action_msg "System clock was not updated at this time"
-                       return 1
-                   fi
-               fi
-               ;;
-       yes)    GMT="--utc"
-               UTC="--utc"
-               ;;
-       *)      log_action_msg "Unknown UTC setting: \"$UTC\""; return 1 ;;
-    esac
-
-    case "$BADYEAR" in
-       no|"")  BADYEAR="" ;;
-       yes)    BADYEAR="--badyear" ;;
-       *)      log_action_msg "unknown BADYEAR setting: \"$BADYEAR\""; return 1 ;;
-    esac
-
-    case "$1" in
-       start)
-           if [ -w /etc ] && [ ! -f /etc/adjtime ] && [ ! -e /etc/adjtime ]; then
-               echo "0.0 0 0.0" > /etc/adjtime
-           fi
-
-           if [ ! -w /etc/adjtime ]; then
-               NOADJ="--noadjfile"
-           else
-               NOADJ=""
-           fi
-
-           if [ "$FIRST" != yes ]; then
-               # Uncomment the hwclock --adjust line below if you want
-               # hwclock to try to correct systematic drift errors in the
-               # Hardware Clock.
-               #
-               # WARNING: If you uncomment this option, you must either make
-               # sure *nothing* changes the Hardware Clock other than
-               # hwclock --systohc, or you must delete /etc/adjtime
-               # every time someone else modifies the Hardware Clock.
-               #
-               # Common "vilains" are: ntp, MS Windows, the BIOS Setup
-               # program.
-               #
-               # WARNING: You must remember to invalidate (delete)
-               # /etc/adjtime if you ever need to set the system clock
-               # to a very different value and hwclock --adjust is being
-               # used.
-               #
-               # Please read /usr/share/doc/util-linux/README.Debian.hwclock
-               # before enabling hwclock --adjust.
-
-               #/sbin/hwclock --adjust $GMT $BADYEAR
-               :
-           fi
-
-           if [ "$HWCLOCKACCESS" != no ]; then
-               log_action_msg "Setting the system clock"
-
-               # Copies Hardware Clock time to System Clock using the correct
-               # timezone for hardware clocks in local time, and sets kernel
-               # timezone. DO NOT REMOVE.
-               if /sbin/hwclock --hctosys $GMT $HWCLOCKPARS $BADYEAR $NOADJ; then
-                   #   Announce the local time.
-                   verbose_log_action_msg "System Clock set to: `date $UTC`"
-               else
-                   log_warning_msg "Unable to set System Clock to: `date $UTC`"
-               fi
-           else
-               verbose_log_action_msg "Not setting System Clock"
-           fi
-           ;;
-       stop|restart|reload|force-reload)
-           #
-           # Updates the Hardware Clock with the System Clock time.
-           # This will *override* any changes made to the Hardware Clock.
-           #
-           # WARNING: If you disable this, any changes to the system
-           #          clock will not be carried across reboots.
-           #
-           if [ "$HWCLOCKACCESS" != no ]; then
-               log_action_msg "Saving the system clock"
-               if [ "$GMT" = "-u" ]; then
-                   GMT="--utc"
-               fi
-               if /sbin/hwclock --systohc $GMT $HWCLOCKPARS $BADYEAR; then
-                   verbose_log_action_msg "Hardware Clock updated to `date`"
-               fi
-           else
-               verbose_log_action_msg "Not saving System Clock"
-           fi
-           ;;
-       show)
-           if [ "$HWCLOCKACCESS" != no ]; then
-               /sbin/hwclock --show $GMT $HWCLOCKPARS $BADYEAR
-           fi
-           ;;
-       *)
-           log_success_msg "Usage: hwclock.sh {start|stop|reload|force-reload|show}"
-           log_success_msg "       start sets kernel (system) clock from hardware (RTC) clock"
-           log_success_msg "       stop and reload set hardware (RTC) clock from kernel (system) clock"
-           return 1
-           ;;
-    esac
-}
-
-hwclocksh "$@"
-#!/bin/sh
-### BEGIN INIT INFO
-# Provides:             keymap
-# Required-Start:       mountdevsubfs
-# Required-Stop:     
-# Default-Start:        S
-# Default-Stop:
-# Short-Description:   Set keymap
-# Description:         Set the Console keymap
-### END INIT INFO
-
-# If setupcon is present, then we've been superseded by console-setup.
-if type setupcon >/dev/null 2>&1; then
-       exit 0
-fi
-
-. /lib/lsb/init-functions
-
-#
-# Load the keymaps *as soon as possible*
-#
-
-# Don't fail on error
-CONSOLE_TYPE=`fgconsole 2>/dev/null` || CONSOLE_TYPE="unknown"
-
-# Don't fail on serial consoles
-
-QUIT=0
-# fail silently if loadkeys not present (yet).
-command -v loadkeys >/dev/null 2>&1 || QUIT=1
-
-CONFDIR=/etc/console
-CONFFILEROOT=boottime
-EXT=kmap
-CONFFILE=${CONFDIR}/${CONFFILEROOT}.${EXT}.gz
-
-reset_kernel()
-{
-       # On Mac PPC machines, we may need to set kernel vars first
-        # We need to mount /proc to do that; not optimal, as its going to 
-        # be mounted in S10checkroot, but we need it set up before sulogin
-        # may be run in checkroot, which will need the keyboard to log in...
-       [ -x /sbin/sysctl ] || return
-       [ -r /etc/sysctl.conf ] || return
-       grep -v '^\#' /etc/sysctl.conf | grep -q keycodes 
-       if [ "$?" = "0" ] ; then
-           grep keycodes /etc/sysctl.conf | grep -v "^#" | while read d ; do
-               /sbin/sysctl -w $d 2> /dev/null || true
-            done
-        fi
-}
-
-unicode_start_stop()
-{
-       # Switch unicode mode by checking the locale.
-       # This will be needed before loading the keymap.
-       [ -x /usr/bin/unicode_start ] || [ -x /bin/unicode_start ] ||  return
-       [ -x /usr/bin/unicode_stop ] || [ -x /bin/unicode_stop ] || return
-
-       ENV_FILE="none"
-       [ -r /etc/environment ] && ENV_FILE="/etc/environment"
-       [ -r /etc/default/locale ] && ENV_FILE="/etc/default/locale" 
-       [ $ENV_FILE = none ] && return
-       
-       for var in LANG LC_ALL LC_CTYPE; do
-               value=$(egrep "^[^#]*${var}=" $ENV_FILE | tail -n1 | cut -d= -f2)
-               eval $var=$value
-       done
-
-       CHARMAP=`LANG=$LANG LC_ALL=$LC_ALL LC_CTYPE=$LC_CTYPE locale charmap`
-       if [ "$CHARMAP" = "UTF-8" ]; then
-               unicode_start 2> /dev/null || true
-       else
-               unicode_stop 2> /dev/null || true
-       fi
-}
-
-if [ ! $QUIT = '1' ] ; then
-
-  case "$1" in
-      start | restart | force-reload | reload)
-  
-       # Set kernel variables if required
-       reset_kernel
-
-        # First mount /proc if necessary...and if it is there (#392798)
-        unmount_proc="no"
-       if [ -d /proc ]; then
-               if [ ! -x /proc/$$ ]; then
-                       unmount_proc="yes"      
-                       mount -n /proc
-               fi
-  
-
-               if [ -f /proc/sys/dev/mac_hid/keyboard_sends_linux_keycodes ] ; then
-                       linux_keycodes=`cat /proc/sys/dev/mac_hid/keyboard_sends_linux_keycodes`
-               else
-                       linux_keycodes=1;
-               fi
-       else
-                       linux_keycodes=1;
-       fi
-
-       # load new map
-       if [ $linux_keycodes -gt 0 ] ; then 
-         if [ -r ${CONFFILE} ] ; then
-
-           # Switch console mode to UTF-8 or ASCII as necessary
-           unicode_start_stop
-
-           if [ $CONSOLE_TYPE = "serial" ] ; then 
-                   loadkeys -q ${CONFFILE} 2>&1 > /dev/null
-           else
-                   loadkeys -q ${CONFFILE}
-           fi
-           if [ $? -gt 0 ]
-               then
-               # if we've a serial console, we may not have a keyboard, so don't
-               # complain if we fail. 
-                  if [ ! $CONSOLE_TYPE = "serial" ]; then 
-                       log_warning_msg "Problem when loading ${CONFDIR}/${CONFFILEROOT}.${EXT}.gz, use install-keymap"
-                       sleep 10
-                  fi 
-               fi
-           fi
-       fi
-
-       # unmount /proc if we mounted it
-        [ "$unmount_proc" = "no" ] || umount -n /proc
-
-       ;;
-
-    stop)
-       ;;
-
-    *)
-       log_warning_msg "Usage: $0 {start|stop|restart|reload|force-reload}"
-       ;;
-  esac
-
-fi
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          killprocs
-# Required-Start:    $local_fs
-# Required-Stop:
-# Default-Start:     1
-# Default-Stop:
-# Short-Description: executed by init(8) upon entering runlevel 1 (single).
-### END INIT INFO
-
-PATH=/usr/sbin:/usr/bin:/sbin:/bin
-
-. /lib/lsb/init-functions
-
-do_start () {
-       # Kill all processes.
-       log_action_begin_msg "Sending all processes the TERM signal"
-       killall5 -15
-       log_action_end_msg 0
-       sleep 5
-       log_action_begin_msg "Sending all processes the KILL signal"
-       killall5 -9
-       log_action_end_msg 0
-
-       # We start update here, since we just killed it.
-       if [ -x /sbin/update ] && [ "$(uname -s)" = Linux ]
-       then
-               case "$(uname -r)" in
-                 0.*|1.*|2.[0123].*)
-                       /sbin/update
-                       ;;
-               esac
-       fi
-}
-
-case "$1" in
-  start)
-       do_start
-       ;;
-  restart|reload|force-reload)
-       echo "Error: argument '$1' not supported" >&2
-       exit 3
-       ;;
-  stop)
-       # No-op
-       ;;
-  *)
-       echo "Usage: $0 start|stop" >&2
-       exit 3
-       ;;
-esac
-#! /bin/sh
-# /etc/init.d/klogd: start the kernel log daemon.
-
-### BEGIN INIT INFO
-# Provides:             klogd
-# Required-Start:       syslog
-# Required-Stop:        syslog
-# Default-Start:        S 1 2 3 4 5
-# Default-Stop:         0 6
-# Short-Description:    Kernel logger
-### END INIT INFO
-
-PATH=/bin:/usr/bin:/sbin:/usr/sbin
-
-pidfile=/var/run/klogd/klogd.pid
-kmsgpipe=/var/run/klogd/kmsg
-kmsgpidfile=/var/run/klogd/kmsgpipe.pid
-binpath=/sbin/klogd
-
-test -f $binpath || exit 0
-. /lib/lsb/init-functions
-
-#  Use KLOGD="-k /boot/System.map-$(uname -r)" to specify System.map
-#
-KLOGD="-P $kmsgpipe"
-
-test ! -r /etc/default/klogd || . /etc/default/klogd
-
-. /lib/lsb/init-functions
-
-case "$1" in
-  start)
-    log_begin_msg "Starting kernel log daemon..."
-    # create klog-writeable pid and fifo directory
-    mkdir -p /var/run/klogd
-    chown klog:klog /var/run/klogd
-    mkfifo -m 700 $kmsgpipe
-    chown klog:klog $kmsgpipe
-    # shovel /proc/kmsg to pipe readable by klogd user
-    start-stop-daemon --start --pidfile $kmsgpidfile --exec /bin/dd -b -m -- bs=1 if=/proc/kmsg of=$kmsgpipe
-    # start klogd as non-root with reading from kmsgpipe
-    start-stop-daemon --start --quiet --chuid klog --exec $binpath -- $KLOGD
-    log_end_msg $?
-    ;;
-  stop)
-    log_begin_msg "Stopping kernel log daemon..."
-    start-stop-daemon --stop --quiet --retry 3 --oknodo --exec $binpath --pidfile $pidfile
-    # stop kmsgpipe
-    start-stop-daemon --stop --quiet --oknodo --pidfile $kmsgpidfile
-    rm -f $kmsgpidfile $kmsgpipe
-    log_end_msg $?
-    ;;
-  restart|force-reload)
-    $0 stop
-    sleep 1
-    $0 start
-    ;;
-  *)
-    log_success_msg "Usage: /etc/init.d/klogd {start|stop|restart|force-reload}"
-    exit 1
-esac
-
-exit 0
-#!/bin/sh
-#
-# chkconfig: - 20 90
-# description: Starts and stops "laptop-mode" - tweaks system behavior
-#              to extend battery life.
-#
-# config:  /etc/laptop-mode/laptop-mode.conf
-
-### BEGIN INIT INFO
-# Provides:          laptop-mode
-# Should-Start:      $all
-# Required-Start:    $local_fs
-# Required-Stop:     $local_fs
-# Default-Start:     2 3 4 5
-# Default-Stop:      0 1 6
-# Short-Description: Enable laptop-mode-tools power management functions
-# Description:       Enable laptop-mode-tools power management functions
-### END INIT INFO
-
-
-test -f /usr/sbin/laptop_mode || exit 0
-
-. /lib/lsb/init-functions
-TEMPFILE=`mktemp`
-
-if [ -f /etc/default/laptop-mode ]; then
-       . /etc/default/laptop-mode;
-fi
-if [ -f /etc/default/acpi-support ]; then
-       . /etc/default/acpi-support;
-fi
-
-if [ x$ENABLE_LAPTOP_MODE = xfalse ]; then
-       exit 0;
-fi
-
-# Enable laptop mode when the system is booted when running on battery.
-
-case $1 in
-  start)
-    log_action_begin_msg "Enabling laptop mode"
-    mkdir -p /var/run/laptop-mode-tools
-    touch /var/run/laptop-mode-tools/enabled
-    /usr/sbin/laptop_mode init auto > $TEMPFILE
-    log_action_end_msg $? "$( cat $TEMPFILE )"
-    ;;
-
-  restart|reload|force-reload)
-    # Full restart: first stop laptop mode completely (to restore default mount options etc.)
-    log_action_begin_msg "Disabling laptop mode"
-    mkdir -p /var/run/laptop-mode-tools
-    rm -f /var/run/laptop-mode-tools/enabled
-    /usr/sbin/laptop_mode init stop > $TEMPFILE
-    log_action_end_msg $? "$( cat $TEMPFILE )"
-
-    # Now remove files containing stored status, re-enable, and start it up again.
-    log_action_begin_msg "Enabling laptop mode"
-    rm -f /var/run/laptop-mode-tools/*\r
-    touch /var/run/laptop-mode-tools/enabled
-    /usr/sbin/laptop_mode init auto force > $TEMPFILE
-    log_action_end_msg $? "$( cat $TEMPFILE )"
-    ;;
-
-  stop)
-    log_action_begin_msg "Disabling laptop mode"
-    rm -f /var/run/laptop-mode-tools/enabled
-    /usr/sbin/laptop_mode init stop > $TEMPFILE
-    log_action_end_msg $? "$( cat $TEMPFILE )"
-    ;;
-
-  status)
-    echo "Laptop mode status:"
-    echo
-    /usr/sbin/laptop_mode status
-    ;;
+if opt.name:
+    if cli:
+        cli.update_ref(refname, commit, oldref)
+    else:
+        git.update_ref(refname, commit, oldref)
+
+if cli:
+    cli.close()
+
+secs = time.time() - start_time
+size = hashsplit.total_split
+if opt.bench:
+    log('\nbup: %.2fkbytes in %.2f secs = %.2f kbytes/sec\n'
+        % (size/1024., secs, size/1024./secs))
+#!/usr/bin/env python
+import sys, re, struct, mmap
+from bup import git, options
+from bup.helpers import *
+
+
+def s_from_bytes(bytes):
+    clist = [chr(b) for b in bytes]
+    return ''.join(clist)
+
+
+def report(count):
+    fields = ['VmSize', 'VmRSS', 'VmData', 'VmStk']
+    d = {}
+    for line in open('/proc/self/status').readlines():
+        l = re.split(r':\s*', line.strip(), 1)
+        d[l[0]] = l[1]
+    if count >= 0:
+        e1 = count
+        fields = [d[k] for k in fields]
+    else:
+        e1 = ''
+    print ('%9s  ' + ('%10s ' * len(fields))) % tuple([e1] + fields)
+    sys.stdout.flush()
+
+
+optspec = """
+bup memtest [-n elements] [-c cycles]
+--
+n,number=  number of objects per cycle
+c,cycles=  number of cycles to run
+ignore-midx  ignore .midx files, use only .idx files
+"""
+o = options.Options('bup memtest', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if extra:
+    o.fatal('no arguments expected')
+
+git.ignore_midx = opt.ignore_midx
+
+git.check_repo_or_die()
+m = git.PackIdxList(git.repo('objects/pack'))
+
+cycles = opt.cycles or 100
+number = opt.number or 10000
+
+report(-1)
+f = open('/dev/urandom')
+a = mmap.mmap(-1, 20)
+report(0)
+for c in xrange(cycles):
+    for n in xrange(number):
+        b = f.read(3)
+        if 0:
+            bytes = list(struct.unpack('!BBB', b)) + [0]*17
+            bytes[2] &= 0xf0
+            bin = struct.pack('!20s', s_from_bytes(bytes))
+        else:
+            a[0:2] = b[0:2]
+            a[2] = chr(ord(b[2]) & 0xf0)
+            bin = str(a[0:20])
+        #print bin.encode('hex')
+        m.exists(bin)
+    report((c+1)*number)
+#!/usr/bin/env python
+import sys, os, stat
+from bup import options, git, vfs
+from bup.helpers import *
+
+def print_node(text, n):
+    prefix = ''
+    if opt.hash:
+        prefix += "%s " % n.hash.encode('hex')
+    if stat.S_ISDIR(n.mode):
+        print '%s%s/' % (prefix, text)
+    elif stat.S_ISLNK(n.mode):
+        print '%s%s@' % (prefix, text)
+    else:
+        print '%s%s' % (prefix, text)
+
+
+optspec = """
+bup ls <dirs...>
+--
+s,hash   show hash for each file
+"""
+o = options.Options('bup ls', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+git.check_repo_or_die()
+top = vfs.RefList(None)
+
+if not extra:
+    extra = ['/']
+
+ret = 0
+for d in extra:
+    try:
+        n = top.lresolve(d)
+        if stat.S_ISDIR(n.mode):
+            for sub in n:
+                print_node(sub.name, sub)
+        else:
+            print_node(d, n)
+    except vfs.NodeError, e:
+        log('error: %s\n' % e)
+        ret = 1
+
+sys.exit(ret)
+#!/usr/bin/env python
+import sys, os, re, stat, readline, fnmatch
+from bup import options, git, shquote, vfs
+from bup.helpers import *
+
+def node_name(text, n):
+    if stat.S_ISDIR(n.mode):
+        return '%s/' % text
+    elif stat.S_ISLNK(n.mode):
+        return '%s@' % text
+    else:
+        return '%s' % text
+
+
+def do_ls(path, n):
+    l = []
+    if stat.S_ISDIR(n.mode):
+        for sub in n:
+            l.append(node_name(sub.name, sub))
+    else:
+        l.append(node_name(path, n))
+    print columnate(l, '')
     
-  *)
-    echo "Usage: $0 {stop|start|restart|reload|force-reload|status}" >&2
-    exit 2
-    ;;
-esac
-
-if [ -f $TEMPFILE ] ; then
-       rm $TEMPFILE
-fi
-
-exit 0
-#!/bin/sh
-### BEGIN INIT INFO
-# Provides:          libpam-foreground-clean
-# Required-Start:    $local_fs $remote_fs
-# Required-Stop:
-# Default-Start:     S
-# Default-Stop:
-# Short-Description: Clean old status files during boot.
-### END INIT INFO
-
-set -e
-
-. /lib/lsb/init-functions
-PATH=/sbin:/bin
-
-STATEDIR=/var/run/console
-
-case "$1" in
-  start)
-    if [ -d $STATEDIR ]; then
-      log_begin_msg "Cleaning up $STATEDIR/..."
-      rm -f $STATEDIR/*
-      log_end_msg 0
-    fi
-    exit 0
-    ;;
-
-  stop|restart|force-reload)
-    exit 0
-    ;;
-
-  *)
-    echo "Usage: $0 {start|stop|restart|force-reload}" >&2
-    exit 3
-    ;;
-esac
-#!/bin/sh -e
-#
-# loopback - brings up the loopback (127.0.0.1) network device so that
-#            DHCP and other such things will work
-#
 
-# Check the package is still installed
-[ -x /sbin/ifup ] || exit 0
-
-# Get LSB functions
-. /lib/lsb/init-functions
-. /etc/default/rcS
-
-case "$1" in
-    start)
-       [ -d /var/run/network ] || mkdir /var/run/network
-
-       log_begin_msg "Starting basic networking..."
-       if ifup --allow auto lo; then
-           log_end_msg 0
-       else
-           log_end_msg $?
-       fi
-       ;;
-    stop)
-       log_begin_msg "Stopping basic networking..."
-       if ifdown lo; then
-           log_end_msg 0
-       else
-           log_end_msg $?
-       fi
-       ;;
-    restart|force-reload)
-       exit 0
-       ;;
-    *)
-       echo "Usage: /etc/init.d/loopback {start|stop|restart|force-reload}"
-       exit 1
-       ;;
-esac
-
-exit 0
-#! /bin/sh
-
-N=/etc/init.d/makedev
-PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
-
-set -e
-
-case "$1" in
-  start)
-       test -L /dev/MAKEDEV || ln -fs /sbin/MAKEDEV /dev/MAKEDEV
-
-       # create dvb-devices, if the dvb-directory allready exists, and 
-       # no devfs or udev is in use (workaround for the changed major-number
-       # of the dvb-devices, introduced in kernel 2.6.8, to be able to 
-       # switch between kernels <= 2.6.7 and >= 2.6.8, without manual 
-       # recreation of the devices (MAKEDEV dvb checks the kernel-version 
-       # and uses the correct major-number))
-       
-       if [ ! -e /dev/.devfsd -a ! -e /dev/.udevdb ]; then
-               if [ -d /dev/dvb ]; then
-                       cd /dev && ./MAKEDEV dvb
-               fi
-       fi
-       
-       ;;
-  stop|reload|restart|force-reload)
-       ;;
-  *)
-       echo "Usage: $N {start|stop|restart|force-reload}" >&2
-       exit 1
-       ;;
-esac
-
-exit 0
-#!/bin/sh
-#
-# Start the RAID monitor daemon for all active md arrays if desired.
-#
-# Copyright (c) 2001-2004 Mario Jou/3en <joussen@debian.org>
-# Distributable under the terms of the GNU GPL version 2.
-
-MDADM=/sbin/mdadm
-DEBIANCONFIG=/etc/default/mdadm
-PIDFILE=/var/run/mdadm.pid
-
-test -x $MDADM || exit 0
-
-. /lib/lsb/init-functions
-
-MAIL_TO=root
-START_DAEMON=true
-test -f $DEBIANCONFIG && . $DEBIANCONFIG
-
-case "$1" in
-    start)
-        if [ "x$START_DAEMON" = "xtrue" ] ; then
-            log_begin_msg "Starting RAID monitoring services..."
-            start-stop-daemon -S -q -p $PIDFILE -x $MDADM -- -F -i $PIDFILE -m $MAIL_TO -f -s
-            log_end_msg $?
-        fi
-        ;;
-    stop)
-        if [ -f $PIDFILE ] ; then
-            log_begin_msg "Stopping RAID monitoring services..."
-            start-stop-daemon -K -q -p $PIDFILE -x $MDADM
-           log_end_msg $?
-            rm -f $PIDFILE
-        fi
-        ;;
-    restart|reload|force-reload)
-        $0 stop
-        $0 start
-        ;;
-    *)
-        log_success_msg "Usage: $0 {start|stop|restart|reload|force-reload}"
-        exit 1
-        ;;
-esac
-
-exit 0
-#!/bin/sh
-#
-# Start any arrays which are described in /etc/mdadm/mdadm.conf and which are
-# not running already.
-#
-# Copyright (c) 2001-2004 Mario Jou/3en <joussen@debian.org>
-# Distributable under the terms of the GNU GPL version 2.
-
-MDADM=/sbin/mdadm
-MDRUN=/sbin/mdrun
-CONFIG=/etc/mdadm/mdadm.conf
-DEBIANCONFIG=/etc/default/mdadm
-
-. /lib/lsb/init-functions
-
-test -x $MDADM || exit 0
-
-AUTOSTART=true
-test -f $DEBIANCONFIG && . $DEBIANCONFIG
-
-case "$1" in
-    start)
-       if [ "x$AUTOSTART" = "xtrue" ] ; then
-            if [ ! -f /proc/mdstat ] && [ -x /sbin/modprobe ] ; then
-                /sbin/modprobe -k md > /dev/null 2>&1  
-            fi
-            test -f /proc/mdstat || exit 0
-           log_begin_msg "Starting RAID devices..."
-           if [ -f $CONFIG ] && [ -x $MDADM ] ; then
-               $MDADM -A -s
-           elif [ -x $MDRUN ] ; then
-               $MDRUN
-           fi
-           log_end_msg $?
-       fi
-        ;;
-    stop|restart|reload|force-reload)
-        ;;
-    *)
-       log_success_msg "Usage: $0 {start|stop|restart|reload|force-reload}"
-        exit 1
-        ;;
-esac
-
-exit 0
-#!/bin/sh -e
-### BEGIN INIT INFO
-# Provides:          module-init-tools
-# Required-Start:    
-# Required-Stop:     
-# Should-Start:      checkroot
-# Should-stop:
-# Default-Start:     S
-# Default-Stop:
-# Short-Description: Process /etc/modules.
-# Description:       Load the modules listed in /etc/modules.
-### END INIT INFO
-
-# Silently exit if the kernel does not support modules or needs modutils.
-[ -f /proc/modules ] || exit 0
-[ ! -f /proc/ksyms ] || exit 0
-[ -x /sbin/modprobe  ] || exit 0
-
-. /etc/default/rcS
-. /lib/lsb/init-functions
-
-PATH="/sbin:/bin"
-
-KVER=$(uname -r)
-KMAJ=${KVER%${KVER#*.*[^.]}}
-KMAJ=${KMAJ%.}
-
-if [ -e /etc/modules-$KVER ]; then
-  MODULES_FILE=/etc/modules-$KVER
-elif [ -e /etc/modules-$KMAJ ]; then
-  MODULES_FILE=/etc/modules-$KMAJ
-else
-  MODULES_FILE=/etc/modules
-fi
-
-load_module() {
-  local module args
-  module="$1"
-  args="$2"
-
-  if [ "$VERBOSE" != no ]; then
-    log_action_msg "Loading kernel module $module"
-    modprobe $module $args || true
-  else
-    modprobe $module $args > /dev/null 2>&1 || true
-  fi   
-}
-
-if [ "$VERBOSE" = no ]; then
-  log_action_begin_msg 'Loading kernel modules'
-fi
-
-# Loop over every line in /etc/modules.
-log_begin_msg 'Loading manual drivers...'
-grep '^[^#]' $MODULES_FILE | \
-while read module args; do
-  [ "$module" ] || continue
-  load_module "$module" "$args"
-done
-
-if [ "$VERBOSE" = no ]; then 
-  log_action_end_msg 0
-fi
-
-exit 0
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          mountall-bootclean
-# Required-Start:    mountall
-# Required-Stop:
-# Default-Start:     S
-# Default-Stop:
-# Short-Description: bootclean after mountall.
-# Description:       Clean temporary filesystems after
-#                    all local filesystems have been mounted.
-### END INIT INFO
-
-case "$1" in
-  start|"")
-       # Clean /tmp
-       /etc/init.d/bootclean
-       ;;
-  restart|reload|force-reload)
-       echo "Error: argument '$1' not supported" >&2
-       exit 3
-       ;;
-  stop)
-       # No-op
-       ;;
-  *)
-       echo "Usage: mountall-bootclean.sh [start|stop]" >&2
-       exit 3
-       ;;
-esac
-
-:
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          mountall
-# Required-Start:    checkfs
-# Required-Stop: 
-# Should-Start:      lvm
-# Should-Stop:
-# Default-Start:     S
-# Default-Stop:
-# Short-Description: Mount all filesystems.
-# Description:
-### END INIT INFO
-
-PATH=/sbin:/bin
-. /lib/init/vars.sh
-
-. /lib/lsb/init-functions
-. /lib/init/mount-functions.sh
-
-if [ -r /etc/default/locale ]; then
-       . /etc/default/locale
-       export LANG
-fi
-
-do_start() {
-       #
-       # Mount local file systems in /etc/fstab.
-       #
-       pre_mountall
-       if [ "$VERBOSE" = no ]
-       then
-               log_action_begin_msg "Mounting local filesystems"
-               mount -a -t proc >/dev/null 2>&1  # Ignore error message due to /proc already being mounted
-               ES_TO_REPORT=$?
-               mount -a -t noproc,nfs,nfs4,smbfs,cifs,ncp,ncpfs,coda,ocfs2,gfs
-               ES=$?
-               ES_TO_REPORT=$(($ES_TO_REPORT | $ES))
-               if [ 0 = "$ES_TO_REPORT" ]
-               then
-                       log_action_end_msg 0
-               else
-                       log_action_end_msg 1 "code $ES_TO_REPORT"
-               fi
-       else
-               log_action_msg "Will now mount local filesystems"
-               mount -a -t proc >/dev/null 2>&1  # Ignore error message due to /proc already being mounted
-               ES=$?
-               [ 0 = "$ES" ] || log_failure_msg "Mounting proc filesystems failed with error code ${ES}."
-               mount -a -v -t noproc,nfs,nfs4,smbfs,cifs,ncp,ncpfs,coda,ocfs2,gfs
-               ES=$?
-               if [ 0 = "$ES" ]
-               then
-                       log_success_msg "Done mounting local filesystems."
-               else
-                       log_failure_msg "Mounting local filesystems failed with error code ${ES}."
-               fi
-       fi
-
-       post_mountall
-
-       case "$(uname -s)" in
-         *FreeBSD)
-               INITCTL=/etc/.initctl
-               ;;
-         *)
-               INITCTL=/dev/initctl
-               ;;
-       esac
-
-       #
-       # We might have mounted something over /dev, see if
-       # /dev/initctl is there.
-       #
-       if [ ! -p $INITCTL ]
-       then
-               rm -f $INITCTL
-               mknod -m 600 $INITCTL p
-       fi
-       kill -USR1 1
-
-       #
-       # Execute swapon command again, in case we want to swap to
-       # a file on a now mounted filesystem.
-       #
-       # Ignore 255 status due to swap already being enabled
-       #
-       if [ "$VERBOSE" = no ]
-       then
-               log_action_begin_msg "Activating swapfile swap"
-               swapon -a -e 2>/dev/null || :  # Stifle "Device or resource busy"
-               log_action_end_msg 0
-       else
-               log_action_msg "Will now activate swapfile swap"
-               swapon -a -e -v || :
-               log_success_msg "Done activating swapfile swap."
-       fi
-}
-
-case "$1" in
-  start|"")
-       do_start
-       ;;
-  restart|reload|force-reload)
-       echo "Error: argument '$1' not supported" >&2
-       exit 3
-       ;;
-  stop)
-       # No-op
-       ;;
-  *)
-       echo "Usage: mountall.sh [start|stop]" >&2
-       exit 3
-       ;;
-esac
-
-:
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          mountdevsubfs mountvirtfs
-# Required-Start:    mountkernfs
-# Required-Stop:
-# Default-Start:     S
-# Default-Stop:
-# Short-Description: Mount special file systems under /dev.
-# Description:       Mount the virtual filesystems the kernel provides
-#                    that ordinarily live under the /dev filesystem.
-### END INIT INFO
-
-PATH=/lib/init:/sbin:/bin
-TTYGRP=5
-TTYMODE=620
-[ -f /etc/default/devpts ] && . /etc/default/devpts
-
-TMPFS_SIZE=
-[ -f /etc/default/tmpfs ] && . /etc/default/tmpfs
-
-KERNEL="$(uname -s)"
-
-. /lib/lsb/init-functions
-. /lib/init/mount-functions.sh
-
-do_start () {
-       #
-       # Mount a tmpfs on /dev/shm
-       #
-       SHM_OPT=
-       [ "${SHM_SIZE:=$TMPFS_SIZE}" ] && SHM_OPT="-osize=$SHM_SIZE"
-       domount tmpfs shmfs /dev/shm $SHM_OPT
-
-       #
-       # Mount /dev/pts. Create master ptmx node if needed.
-       #
-       domount devpts "" /dev/pts -ogid=$TTYGRP,mode=$TTYMODE
-
-       #
-       # Magic to make /proc/bus/usb work
-       #
-       #mkdir -p /dev/bus/usb/.usbfs
-       #domount usbfs "" /dev/bus/usb/.usbfs -obusmode=0700,devmode=0600,listmode=0644
-       #ln -s .usbfs/devices /dev/bus/usb/devices
-       #mount --rbind /dev/bus/usb /proc/bus/usb
-}
-
-case "$1" in
-  "")
-       echo "Warning: mountdevsubfs should be called with the 'start' argument." >&2
-       do_start
-       ;;
-  start)
-       do_start
-       ;;
-  restart|reload|force-reload)
-       echo "Error: argument '$1' not supported" >&2
-       exit 3
-       ;;
-  stop)
-       # No-op
-       ;;
-  *)
-       echo "Usage: mountdevsubfs [start|stop]" >&2
-       exit 3
-       ;;
-esac
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          mountkernfs
-# Required-Start:
-# Required-Stop:
-# Default-Start:     S
-# Default-Stop:
-# Short-Description: Mount kernel virtual file systems.
-# Description:       Mount initial set of virtual filesystems the kernel
-#                    provides and that are required by everything.
-### END INIT INFO
-
-PATH=/lib/init:/sbin:/bin
-
-. /lib/lsb/init-functions
-. /lib/init/mount-functions.sh
-
-do_start () {
-       #
-       # Mount proc filesystem on /proc
-       #
-       domount proc "" /proc -onodev,noexec,nosuid
-
-       #
-       # Mount sysfs on /sys
-       #
-       domount sysfs "" /sys -onodev,noexec,nosuid
-
-       # Mount /var/run and /var/lock as tmpfs.
-       domount tmpfs "" /var/run -omode=0755,nodev,noexec,nosuid
-       domount tmpfs "" /var/lock -omode=1777,nodev,noexec,nosuid
-
-       # Mount spufs, if Cell Broadband processor is detected
-       if mountpoint -q /proc && grep -qs '^cpu.*Cell' /proc/cpuinfo; then
-               mkdir -p /spu
-               domount spufs "" /spu -ogid=spu
-       fi
-
-       # Propagate files from the initramfs to our new /var/run.
-       for file in /dev/.initramfs/varrun/*; do
-               [ -e "$file" ] || continue
-               cp -a "$file" "/var/run/${x#/dev/.initramfs/varrun/}"
-       done
-
-       if [ ! -d /var/run/sendsigs.omit.d/ ]; then
-               mkdir /var/run/sendsigs.omit.d/
-       fi
-}
-
-case "$1" in
-  "")
-       echo "Warning: mountvirtfs should be called with the 'start' argument." >&2
-       do_start
-       ;;
-  start)
-       do_start
-       ;;
-  restart|reload|force-reload)
-       echo "Error: argument '$1' not supported" >&2
-       exit 3
-       ;;
-  stop)
-       # No-op
-       ;;
-  *)
-       echo "Usage: mountvirtfs [start|stop]" >&2
-       exit 3
-       ;;
-esac
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          mountnfs-bootclean
-# Required-Start:    mountnfs
-# Required-Stop:
-# Default-Start:     S
-# Default-Stop:
-# Short-Description: bootclean after mountnfs.
-# Description:       Clean temporary filesystems after
-#                    network filesystems have been mounted.
-### END INIT INFO
-
-case "$1" in
-  start|"")
-       # Clean /tmp
-       /etc/init.d/bootclean
-       ;;
-  restart|reload|force-reload)
-       echo "Error: argument '$1' not supported" >&2
-       exit 3
-       ;;
-  stop)
-       # No-op
-       ;;
-  *)
-       echo "Usage: mountnfs-bootclean.sh [start|stop]" >&2
-       exit 3
-       ;;
-esac
-
-:
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          mountoverflowtmp
-# Required-Start:    mountall-bootclean
-# Required-Stop:
-# Default-Start:     S
-# Default-Stop:
-# Short-Description: mount emergency /tmp.
-# Description:       Mount a tmpfs on /tmp if there would
-#                    otherwise be too little space to log in.
-### END INIT INFO
-
-. /lib/lsb/init-functions
-
-set -e
-
-defs=/etc/default/mountoverflowtmp
-test ! -f "$defs" || . "$defs"
-
-: ${MINTMPKB:=1024}
-if test "$MINTMPKB" = "0"; then exit 0; fi
-
-case "$1" in
-  start|"")
-       log_action_begin_msg "Checking minimum space in /tmp"
-       df="`df -kP /tmp`"
-       avail="`printf "%s" "$df" | awk 'NR==2 { print $4 }'`"
-       log_action_end_msg 0
-       if test $avail -lt "$MINTMPKB"; then
-               log_action_begin_msg "Mounting emergency tmpfs on /tmp"
-               mount -t tmpfs -o size=1048576,mode=1777 overflow /tmp
-               log_action_end_msg 0
-       fi
-       ;;
-  restart|reload|force-reload)
-       echo "Error: argument '$1' not supported" >&2
-       exit 3
-       ;;
-  stop)
-       log_action_begin_msg "Unmounting any overflow tmpfs from /tmp"
-       if LANG=C LC_ALL=C mount | \
-               grep '^overflow on /tmp type tmpfs' >/dev/null; then
-               umount overflow
-       fi
-       log_action_end_msg 0
-       ;;
-  *)
-       echo "Usage: mountoverflowtmp [start|stop]" >&2
-       exit 3
-       ;;
-esac
-
-:
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          mtab
-# Required-Start:    mountall
-# Required-Stop:
-# Default-Start:     S
-# Default-Stop:
-# Short-Description: Update mtab file.
-# Description:       Update the mount program's mtab file after
-#                    all local filesystems have been mounted.
-### END INIT INFO
-
-PATH=/lib/init:/sbin:/bin
-TTYGRP=5
-TTYMODE=620
-[ -f /etc/default/devpts ] && . /etc/default/devpts
-
-TMPFS_SIZE=
-[ -f /etc/default/tmpfs ] && . /etc/default/tmpfs
-
-KERNEL="$(uname -s)"
-
-. /lib/lsb/init-functions
-. /lib/init/mount-functions.sh
-
-domtab ()
-{
-       # Directory present?
-       if [ ! -d $2 ]
-       then
-               return
-       fi
-
-       # Not mounted?
-       if ! mountpoint -q $2
-       then
-               return
-       fi
-
-       if [ -n "$3" ]
-       then
-               NAME="$3"
-       else
-               NAME="$1"
-       fi
-
-       # Already recorded?
-       if ! grep -E -sq "^([^ ]+) +$2 +" /etc/mtab
-       then
-               mount -f -t $1 $OPTS $4 $NAME $2
-       fi
-}
-
-do_start () {
-       DO_MTAB=""
-       MTAB_PATH="$(readlink -f /etc/mtab || :)"
-       case "$MTAB_PATH" in
-         /proc/*)
-               # Assume that /proc/ is not writable
-               ;;
-         /*)
-               # Only update mtab if it is known to be writable
-               # Note that the touch program is in /usr/bin
-               #if ! touch "$MTAB_PATH" >/dev/null 2>&1
-               #then
-               #       return
-               #fi
-               ;;
-         "")
-               [ -L /etc/mtab ] && MTAB_PATH="$(readlink /etc/mtab)"
-               if [ "$MTAB_PATH" ]
-               then
-                       log_failure_msg "Cannot initialize ${MTAB_PATH}."
-               else
-                       log_failure_msg "Cannot initialize /etc/mtab."
-               fi
-               ;;
-         *)
-               log_failure_msg "Illegal mtab location '${MTAB_PATH}'."
-               ;;
-       esac
-
-       #
-       # Initialize mtab file if necessary
-       #
-       if [ ! -f /etc/mtab ]
-       then
-               :> /etc/mtab
-               chmod 644 /etc/mtab
-       fi
-       if selinux_enabled && which restorecon >/dev/null 2>&1 && [ -r /etc/mtab ]
-       then
-               restorecon /etc/mtab
-       fi
-
-       # S01mountkernfs.sh
-       domtab proc /proc "proc" -onodev,noexec,nosuid
-       domtab sysfs /sys "sys" -onodev,noexec,nosuid
-       domtab tmpfs /var/run "varrun" -omode=0755,nodev,noexec,nosuid
-       domtab tmpfs /var/lock "varlock" -omode=1777,nodev,noexec,nosuid
-       domtab usbfs /proc/bus/usb "procbususb"
-
-       # S10udev
-       domtab tmpfs /dev "udev" -omode=0755
-
-       # S02mountdevsubfs
-       SHM_OPT=
-       [ "${SHM_SIZE:=$TMPFS_SIZE}" ] && SHM_OPT="-osize=$SHM_SIZE"
-       domtab tmpfs /dev/shm "devshm" $SHM_OPT
-       domtab devpts /dev/pts "devpts" -ogid=$TTYGRP,mode=$TTYMODE
-
-       # S07linux-restricted-modules-common
-       exec 9<&0 0</proc/mounts
-       while read FDEV FDIR FTYPE FOPTS REST
-       do
-               case "$FDIR" in
-                       /lib/modules/*/volatile)
-                               domtab "$FTYPE" "$FDIR" "lrm"
-                               ;;
-               esac
-       done
-       exec 0<&9 9<&-
-
-       # /etc/network/if-up.d/mountnfs
-       exec 9<&0 </etc/fstab
-       while read FDEV FDIR FTYPE FOPTS REST
-       do
-               case "$FDEV" in
-                 ""|\#*)
-                       continue
-                       ;;
-               esac
-               case "$FOPTS" in
-                 noauto|*,noauto|noauto,*|*,noauto,*)
-                       continue
-                       ;;
-               esac
-               case "$FTYPE" in
-                 nfs|nfs4|smbfs|cifs|coda|ncp|ncpfs|ocfs2|gfs)
-                       domtab "$FTYPE" "$FDIR" "$FDEV" "-o$FOPTS"
-                       ;;
-                 *)
-                       continue
-                       ;;
-               esac
-        done
-        exec 0<&9 9<&-
-
-       
-}
-
-case "$1" in
-  start|"")
-       do_start
-       ;;
-  restart|reload|force-reload)
-       echo "Error: argument '$1' not supported" >&2
-       exit 3
-       ;;
-  stop)
-       # No-op
-       ;;
-  *)
-       echo "Usage: mountall-mtab.sh [start|stop]" >&2
-       exit 3
-       ;;
-esac
-
-:
-#!/bin/bash
-#
-# MySQL daemon start/stop script.
-#
-# Debian version. Based on the original by TcX.
-#
-set -e
-set -u
-${DEBIAN_SCRIPT_DEBUG:+ set -v -x}
-
-test -x /usr/sbin/mysqld || exit 0
-
-SELF=$(cd $(dirname $0); pwd -P)/$(basename $0)
-CONF=/etc/mysql/my.cnf
-MYADMIN="/usr/bin/mysqladmin --defaults-file=/etc/mysql/debian.cnf"
-
-# priority can be overriden and "-s" adds output to stderr
-ERR_LOGGER="logger -p daemon.err -t /etc/init.d/mysql -i"
-
-# Safeguard (relative paths, core dumps..)
-cd /
-umask 077
-
-# mysqladmin likes to read /root/.my.cnf. This is usually not what I want
-# as many admins e.g. only store a password without a username there and
-# so break my scripts.
-export HOME=/etc/mysql/
-
-## fetch a particular option from mysql's invocation
-#
-# usage: void mysqld_get_param option
-mysqld_get_param() {
-       /usr/sbin/mysqld --print-defaults \
-               | tr " " "\n" \
-               | grep -- "--$1" \
-               | tail -n 1 \
-               | cut -d= -f2
-}
-
-## Checks if there is a server running and if so if it is accessible.
-#
-# check_alive insists on a pingable server
-# check_dead also fails if there is a lost mysqld in the process list
-#
-# Usage: boolean mysqld_status [check_alive|check_dead] [warn|nowarn]
-mysqld_status () {
-    ping_output=`$MYADMIN ping 2>&1`; ping_alive=$(( ! $? ))
-
-    ps_alive=0
-    pidfile=`mysqld_get_param pid-file`
-    if [ -f "$pidfile" ] && ps `cat $pidfile` >/dev/null 2>&1; then ps_alive=1; fi
+def write_to_file(inf, outf):
+    for blob in chunkyreader(inf):
+        outf.write(blob)
     
-    if [ "$1" = "check_alive"  -a  $ping_alive = 1 ] ||
-       [ "$1" = "check_dead"   -a  $ping_alive = 0  -a  $ps_alive = 0 ]; then
-       return 0 # EXIT_SUCCESS
-    else
-       if [ "$2" = "warn" ]; then
-           /bin/echo -e "$ps_alive processes alive and '$MYADMIN ping' resulted in\n$ping_output\n" | $ERR_LOGGER -p daemon.debug
-       fi
-       return 1 # EXIT_FAILURE
-    fi
-}
-
-#
-# main()
-#
-
-case "${1:-''}" in
-  'start')
-       # check for config file
-       if [ ! -r /etc/mysql/my.cnf ]; then
-         /bin/echo -e "\nWARNING: /etc/mysql/my.cnf cannot be read. See README.Debian.gz"
-        fi 
-       # Start daemon
-       echo -n "Starting MySQL database server: mysqld"
-       if mysqld_status check_alive nowarn; then
-          echo "...already running."
-       else
-           /usr/bin/mysqld_safe > /dev/null 2>&1 &
-           for i in 1 2 3 4 5 6; do
-                sleep 1
-               if mysqld_status check_alive nowarn ; then break; fi
-            done
-           if mysqld_status check_alive warn; then
-                echo "."
-               # Now start mysqlcheck or whatever the admin wants.
-               /etc/mysql/debian-start
-           else
-               echo "...failed."
-               /bin/echo -e "\tPlease take a look at the syslog."
-           fi
-       fi
-
-        if $MYADMIN variables | egrep -q have_bdb.*YES; then
-            /bin/echo "BerkeleyDB is obsolete, see /usr/share/doc/mysql-server-4.1/README.Debian.gz" | $ERR_LOGGER -p daemon.info
-        fi
-       ;;
-
-  'stop')
-       # * As a passwordless mysqladmin (e.g. via ~/.my.cnf) must be possible
-       # at least for cron, we can rely on it here, too. (although we have 
-       # to specify it explicit as e.g. sudo environments points to the normal
-       # users home and not /root)
-       echo -n "Stopping MySQL database server: mysqld"        
-       if ! mysqld_status check_dead nowarn; then
-         set +e
-         shutdown_out=`$MYADMIN shutdown 2>&1`; r=$?
-         set -e
-         if [ "$r" -ne 0 ]; then
-           /bin/echo -e -n "...failed.\n$shutdown_out\nKilling MySQL database server by signal: mysqld"
-           killall -15 mysqld
-            server_down=
-           for i in 1 2 3 4 5 6 7 8 9 10; do
-              sleep 1
-              if mysqld_status check_dead nowarn; then server_down=1; break; fi
-            done
-          if test -z "$server_down"; then killall -9 mysqld; fi
-         fi
-        fi
-
-        if ! mysqld_status check_dead warn; then
-         echo "...failed."
-         echo "Please stop MySQL manually and read /usr/share/doc/mysql-server-4.1/README.Debian.gz!"
-         exit -1
-       else
-         echo "."
-        fi
-       ;;
-
-  'restart')
-       set +e; $SELF stop; set -e
-       $SELF start 
-       ;;
-
-  'reload'|'force-reload')
-       echo -n "Reloading MySQL database server: mysqld"
-       $MYADMIN reload
-       echo "."
-       ;;
-
-  'status')
-       if mysqld_status check_alive nowarn; then
-         $MYADMIN version
-       else
-         echo "MySQL is stopped."
-         exit 3
-       fi
-       ;;
-
-  *)
-       echo "Usage: $SELF start|stop|restart|reload|force-reload|status"
-       exit 1
-       ;;
-esac
-
-#!/bin/bash
-#
-# MySQL NDB management daemon start/stop script.
-#
-set -e
-set -u
-${DEBIAN_SCRIPT_DEBUG:+ set -v -x}
-
-# Variables
-SELF=$(cd $(dirname $0); pwd -P)/$(basename $0)
-DAEMON=/usr/sbin/ndbd
-CONF=/etc/mysql/my.cnf
-export HOME=/etc/mysql/
-
-# Safeguard (relative paths, core dumps..)
-cd /
-umask 077
-
-# Exit *silently* if we're not supposed to be started.
-#
-# The Debian scripts should execute these scripts to stop and start
-# the daemon when upgrading if it is started. On the other hand it should
-# remain silently if the server has not even been configured.
-# See /usr/share/doc/mysql-server-*/README.Debian for more information.
-test -x $DAEMON || exit 0
-if $DAEMON --help | grep -q '^ndb-connectstring.*No default value'; then exit 0; fi
-
-#
-# main()
-#
-case "${1:-''}" in
-  'start')
-       # Start daemon
-        # Creatign a PID file does not work as the master process forks
-        # a child with different PID and then terminates itself.
-       echo -n "Starting MySQL NDB cluster server: ndbd"
-       if start-stop-daemon \
-               --start \
-               --exec $DAEMON \
-               --user mysql
-       then
-         echo "."
-       else
-         echo "...failed."
-         /bin/echo -e "\tPlease take a look at the syslog."
-         exit 1
-       fi                        
-       ;;
-
-  'stop')
-       echo -n "Stopping MySQL NDB cluster management server: ndbd"    
-       if start-stop-daemon \
-               --stop \
-               --oknodo \
-               --exec $DAEMON
-       then
-         echo "."
-       else
-         echo "...failed."
-         exit 1
-        fi
-       ;;
-
-  'restart'|'force-reload')
-       set +e; $SELF stop; set -e
-       $SELF start 
-       ;;
-
-  *)
-       echo "Usage: $SELF start|stop|restart|force-reload"
-       exit 1
-       ;;
-esac
-
-#!/bin/bash
-#
-# MySQL NDB management daemon start/stop script.
-#
-set -e
-set -u
-${DEBIAN_SCRIPT_DEBUG:+ set -v -x}
-
-# Variables
-SELF=$(cd $(dirname $0); pwd -P)/$(basename $0)
-DAEMON=/usr/sbin/ndb_mgmd
-CONF=/etc/mysql/ndb_mgmd.cnf
-export HOME=/etc/mysql/
-
-# Safeguard (relative paths, core dumps..)
-cd /
-umask 077
-
-# Exit *silently* if we're not supposed to be started.
-#
-# The Debian scripts should execute these scripts to stop and start
-# the daemon when upgrading if it is started. On the other hand it should
-# remain silently if the server has not even been configured.
-# See /usr/share/doc/mysql-server-*/README.Debian for more information.
-test -x $DAEMON || exit 0
-test -r $CONF || exit 0
-
-#
-# main()
-#
-case "${1:-''}" in
-  'start')
-       # Start daemon
-       echo -n "Starting MySQL NDB cluster management server: ndb_mgmd"
-       # --pid-file does not work as the daemon forks itself with $PID=$PID+1
-       if start-stop-daemon \
-               --start \
-               --exec $DAEMON \
-               --user mysql \
-               -- \
-               -f $CONF
-       then
-         echo "."
-       else
-         echo "...failed."
-         /bin/echo -e "\tPlease take a look at the syslog."
-         exit 1
-       fi                        
-       ;;
-
-  'stop')
-       echo -n "Stopping MySQL NDB cluster management server: ndb_mgmd"        
-       if start-stop-daemon \
-               --stop \
-               --oknodo \
-               --exec $DAEMON
-       then
-         echo "."
-       else
-         echo "...failed."
-         exit 1
-        fi
-       ;;
-
-  'restart'|'force-reload')
-       set +e; $SELF stop; set -e
-       $SELF start 
-       ;;
-
-  *)
-       echo "Usage: $SELF start|stop|restart|force-reload"
-       exit 1
-       ;;
-esac
-
-#!/bin/sh -e
-### BEGIN INIT INFO
-# Provides:          networking
-# Required-Start:    mountkernfs ifupdown $local_fs
-# Required-Stop:     ifupdown $local_fs
-# Default-Start:     S
-# Default-Stop:      0 6
-# Short-Description: Raise network interfaces.
-### END INIT INFO
-
-PATH="/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin"
-
-[ -x /sbin/ifup ] || exit 0
-
-. /lib/lsb/init-functions
-
-
-case "$1" in
-start)
-       log_action_begin_msg "Configuring network interfaces"
-        type usplash_write >/dev/null 2>/dev/null && usplash_write "TIMEOUT 120" || true
-       if [ "$VERBOSE" != no ]; then
-           if ifup -a; then
-               log_action_end_msg $?
-           else
-               log_action_end_msg $?
-           fi
-       else
-           if ifup -a >/dev/null 2>&1; then
-               log_action_end_msg $?
-           else
-               log_action_end_msg $?
-           fi
-       fi
-        type usplash_write >/dev/null 2>/dev/null && usplash_write "TIMEOUT 15" || true
-       ;;
-
-stop)
-       if sed -n 's/^[^ ]* \([^ ]*\) \([^ ]*\) .*$/\2/p' /proc/mounts | 
-               grep -qE '^(nfs[1234]?|smbfs|ncp|ncpfs|coda|cifs)$'; then
-           log_warning_msg "not deconfiguring network interfaces: network shares still mounted."
-           exit 0
-       fi
-
-       log_action_begin_msg "Deconfiguring network interfaces"
-       if [ "$VERBOSE" != no ]; then
-           if ifdown -a --exclude=lo; then
-               log_action_end_msg $?
-           else
-               log_action_end_msg $?
-           fi
-       else
-           if ifdown -a --exclude=lo >/dev/null 2>/dev/null; then
-               log_action_end_msg $?
-           else
-               log_action_end_msg $?
-           fi
-       fi
-       ;;
-
-force-reload|restart)
-       log_action_begin_msg "Reconfiguring network interfaces"
-       ifdown -a --exclude=lo || true
-       if ifup -a --exclude=lo; then
-           log_action_end_msg $?
-       else
-           log_action_end_msg $?
-       fi
-       ;;
-
-*)
-       echo "Usage: /etc/init.d/networking {start|stop|restart|force-reload}"
-       exit 1
-       ;;
-esac
-
-exit 0
-
-#!/bin/sh
-#
-# nfs-common    This shell script takes care of starting and stopping
-#               common daemons required for NFS clients and servers.
-#
-# chkconfig: 345 20 80
-# description: NFS is a popular protocol for file sharing across \
-#             TCP/IP networks. This service provides NFS file \
-#             locking functionality.
-#
-
-set -e
-
-# What is this?
-DESC="NFS common utilities"
-
-# Read config
-DEFAULTFILE=/etc/default/nfs-common
-PREFIX=
-NEED_LOCKD=
-NEED_IDMAPD=yes
-IDMAPD_PIDFILE=/var/run/rpc.idmapd.pid
-NEED_GSSD=yes
-GSSD_PIDFILE=/var/run/rpc.gssd.pid
-PIPEFS_MOUNTPOINT=/var/lib/nfs/rpc_pipefs
-RPCGSSDOPTS=
-if [ -f $DEFAULTFILE ]; then
-    . $DEFAULTFILE
-fi
-
-. /lib/lsb/init-functions
-
-# Determine whether lockd daemon is required.
-case "$NEED_LOCKD" in
-yes|no)        ;;
-*)  case `uname -r` in
-    '' | [01].* | 2.[0123].* )
-       # Older kernels may or may not need a lockd daemon.
-       # We must assume they do, unless we can prove otherwise.
-       # (A false positive here results only in a harmless message.)
-       NEED_LOCKD=yes
-       if test -f /proc/ksyms
-       then
-           grep -q lockdctl /proc/ksyms || NEED_LOCKD=no
-       fi
-       ;;
-
-    *)  # Modern kernels (>= 2.4) start a lockd thread automatically.
-       NEED_LOCKD=no
-       ;;
-    esac
-    ;;
-esac
-
-# Exit if required binaries are missing.
-[ -x $PREFIX/sbin/rpc.statd ] || exit 0
-[ -x $PREFIX/sbin/rpc.lockd ] || [ "$NEED_LOCKD"  = no ] || exit 0
-[ -x /usr/sbin/rpc.idmapd   ] || [ "$NEED_IDMAPD" = no ] || exit 0
-[ -x /usr/sbin/rpc.gssd     ] || [ "$NEED_GSSD"   = no ] || exit 0
-
-do_modprobe() {
-    modprobe -q "$1" || true
-}
 
-do_mount() {
-    if ! grep -E -qs "$1\$" /proc/filesystems
-    then
-       return 1
-    fi
-    if ! mountpoint -q "$2"
-    then
-       mount -t "$1" "$1" "$2"
-       return
-    fi
-    return 0
-}
-
-# See how we were called.
-case "$1" in
-  start)
-       cd /    # daemons should have root dir as cwd
-       log_begin_msg "Starting nfs statd..."
-       ERROR=0
-       start-stop-daemon --start --quiet \
-           --exec $PREFIX/sbin/rpc.statd -- $STATDOPTS || ERROR=1
-       log_end_msg $ERROR
-       if [ "$NEED_LOCKD" = yes ]
-       then
-           log_begin_msg "Starting nfs lockd..."
-           ERROR=0
-           start-stop-daemon --start --quiet \
-               --exec $PREFIX/sbin/rpc.lockd || ERROR=1
-           log_end_msg $ERROR
-       fi
-       if [ "$NEED_IDMAPD" = yes ] || [ "$NEED_GSSD" = yes ]
-       then
-           do_modprobe nfs
-           if do_mount rpc_pipefs $PIPEFS_MOUNTPOINT
-           then
-               if [ "$NEED_IDMAPD" = yes ]
-               then
-                   log_begin_msg "Starting rpc idmapd..."
-                   ERROR=0
-                   start-stop-daemon --start --quiet \
-                           --make-pidfile --pidfile $IDMAPD_PIDFILE \
-                           --exec /usr/sbin/rpc.idmapd || ERROR=1
-                   log_end_msg $ERROR
-               fi
-               if [ "$NEED_GSSD" = yes ]
-               then
-                   log_begin_msg "Starting rpc gssd..."
-                   ERROR=0
-                   start-stop-daemon --start --quiet \
-                           --make-pidfile --pidfile $GSSD_PIDFILE \
-                           --exec /usr/sbin/rpc.gssd -- $RPCGSSDOPTS || ERROR=1
-                   log_end_msg $ERROR
-               fi
-           fi
-       fi
-       ;;
-
-  stop)
-       if [ "$NEED_GSSD" = yes ]
-       then
-           log_begin_msg "Stopping rpc gssd..."
-           ERROR=0
-           start-stop-daemon --stop --oknodo --quiet \
-                   --name rpc.gssd --user 0 || ERROR=1
-           log_end_msg $ERROR
-           rm -f $GSSD_PIDFILE
-       fi
-       if [ "$NEED_IDMAPD" = yes ]
-       then
-           log_begin_msg "Stopping rpc idmapd..."
-           ERROR=0
-           start-stop-daemon --stop --oknodo --quiet \
-               --name rpc.idmapd --user 0 || ERROR=1
-           log_end_msg $ERROR
-           rm -f $IDMAPD_PIDFILE
-       fi
-       if [ "$NEED_LOCKD" = yes ]
-       then
-           log_begin_msg "Stopping nfs lockd..."
-           ERROR=0
-           start-stop-daemon --stop --oknodo --quiet \
-               --name rpc.lockd --user 0  || ERROR=1
-           log_end_msg $ERROR
-       fi
-       log_begin_msg "Stopping nfs statd..."
-       ERROR=0
-       start-stop-daemon --stop --oknodo --quiet \
-           --name rpc.statd --user 0 || ERROR=1
-       log_end_msg $ERROR
-       ;;
-
-  restart | force-reload)
-       $0 stop
-       sleep 1
-       $0 start
-       ;;
-
-  *)
-       log_success_msg "Usage: nfs-common {start|stop|restart}"
-       exit 1
-       ;;
-esac
-
-exit 0
-#!/bin/sh
-#
-# nfs-kernel-server
-#              This shell script takes care of starting and stopping
-#               the kernel-mode NFS server.
-#
-# chkconfig: 345 60 20
-# description: NFS is a popular protocol for file sharing across TCP/IP \
-#              networks. This service provides NFS server functionality, \
-#              which is configured via the /etc/exports file.
-#
-
-set -e
-
-# What is this?
-DESC="NFS kernel daemon"
-PREFIX=/usr
-
-# Exit if required binaries are missing.
-[ -x $PREFIX/sbin/rpc.nfsd    ] || exit 0
-[ -x $PREFIX/sbin/rpc.mountd  ] || exit 0
-[ -x $PREFIX/sbin/exportfs    ] || exit 0
-[ -x $PREFIX/sbin/rpc.svcgssd ] || exit 0
-
-# Read config
-DEFAULTFILE=/etc/default/nfs-kernel-server
-RPCNFSDCOUNT=8
-RPCMOUNTDOPTS=
-NEED_SVCGSSD=yes
-RPCGSSDOPTS=
-RPCSVCGSSDOPTS=
-PROCNFSD_MOUNTPOINT=/proc/fs/nfsd
-if [ -f $DEFAULTFILE ]; then
-    . $DEFAULTFILE
-fi
-
-. /lib/lsb/init-functions
-
-do_modprobe() {
-    modprobe -q "$1" || true
-}
-
-do_mount() {
-    if ! grep -E -qs "$1\$" /proc/filesystems
-    then
-       return 1
-    fi
-    if ! mountpoint -q "$2"
-    then
-       mount -t "$1" "$1" "$2"
-       return
-    fi
-    return 0
-}
-
-# See how we were called.
-case "$1" in
-  start)
-       cd /    # daemons should have root dir as cwd
-       if grep -q '^/' /etc/exports
-       then
-               do_modprobe nfsd
-               do_mount nfsd $PROCNFSD_MOUNTPOINT || NEED_SVCGSSD=no
-               log_begin_msg "Exporting directories for $DESC..."
-               ERROR=0
-               $PREFIX/sbin/exportfs -r || ERROR=1
-               log_end_msg $ERROR
-
-               if [ "$NEED_SVCGSSD" = yes ]
-               then
-                   log_begin_msg "Starting rpc svcgssd..."
-                   ERROR=0
-                   start-stop-daemon --start --quiet \
-                           --make-pidfile --pidfile /var/run/rpc.svcgssd.pid \
-                           --exec $PREFIX/sbin/rpc.svcgssd -- $RPCSVCGSSDOPTS || ERROR=1
-                   log_end_msg $ERROR
-               fi
-
-               log_begin_msg "Starting rpc nfsd..."
-               ERROR=0
-               start-stop-daemon --start --quiet \
-                   --exec $PREFIX/sbin/rpc.nfsd -- $RPCNFSDCOUNT || ERROR=1
-               log_end_msg $ERROR
-
-               # make sure 127.0.0.1 is a valid source for requests
-               ClearAddr=
-               if [ -f /proc/net/rpc/auth.unix.ip/channel ]
-               then
-                   fgrep -qs 127.0.0.1 /proc/net/rpc/auth.unix.ip/content || {
-                       echo "nfsd 127.0.0.1 2147483647 localhost" >/proc/net/rpc/auth.unix.ip/channel
-                       ClearAddr=yes
-                   }
-               fi
-
-               $PREFIX/bin/rpcinfo -u localhost nfs 3 >/dev/null 2>&1 ||
-                   RPCMOUNTDOPTS="$RPCMOUNTDOPTS --no-nfs-version 3"
-
-               [ -z "$ClearAddr" ] || echo "nfsd 127.0.0.1 1" >/proc/net/rpc/auth.unix.ip/channel
-
-               log_begin_msg "Starting rpc mountd..."
-               ERROR=0
-               start-stop-daemon --start --quiet \
-                   --exec $PREFIX/sbin/rpc.mountd -- $RPCMOUNTDOPTS || ERROR=1
-               log_end_msg $ERROR
-       else
-               log_warning_msg "Not starting $DESC: No exports."
-       fi
-       ;;
-
-  stop)
-       log_begin_msg "Stopping rpc mountd..."
-       ERROR=0
-       start-stop-daemon --stop --oknodo --quiet \
-           --name rpc.mountd --user 0 || ERROR=1
-       log_end_msg $ERROR
-       if [ "$NEED_SVCGSSD" = yes ]
-       then
-           log_begin_msg "Stopping rpc svcgssd..."
-           ERROR=0
-           start-stop-daemon --stop --oknodo --quiet \
-                   --name rpc.svcgssd --user 0 || ERROR=1
-           log_end_msg $ERROR
-           rm -f /var/run/rpc.svcgssd.pid
-       fi
-       log_begin_msg "Stopping rpc nfsd..."
-       ERROR=0
-       start-stop-daemon --stop --oknodo --quiet \
-           --name nfsd --user 0 --signal 2 || ERROR=1
-       log_end_msg $ERROR
-
-       log_begin_msg "Unexporting directories for $DESC..."
-       ERROR=0
-       $PREFIX/sbin/exportfs -au || ERROR=1
-       log_end_msg $ERROR
-       ;;
-
-  reload | force-reload)
-       log_begin_msg "Re-exporting directories for $DESC..."
-       ERROR=0
-       $PREFIX/sbin/exportfs -r || ERROR=1
-       log_end_msg $ERROR
-       ;;
-
-  restart)
-       $0 stop
-       sleep 1
-       $0 start
-       ;;
-
-  *)
-       log_success_msg "Usage: nfs-kernel-server {start|stop|reload|force-reload|restart}"
-       exit 1
-       ;;
-esac
-
-exit 0
-#! /bin/sh
-#
-### BEGIN INIT INFO
-# Provides:          pcmcia
-# Required-Start:    udev
-# Required-Stop:
-# Default-Start:     S
-# Default-Stop:
-# Short-Description: PCMCIA support
-# Description:       This service provides PCMCIA hardware support for
-#                    systems running Linux >= 2.6.13-rc1.
-### END INIT INFO
-
-set -e
-
-[ -f /sbin/pccardctl ] || exit 0
-
-# If /lib/lsb/init-functions doesn't exist
-# define them here, otherwise installer breaks
-if [ -f /lib/lsb/init-functions ]; then
-    . /lib/lsb/init-functions
-else
-    log_daemon_msg()
-    {
-       echo "$1: $2"
-    }
-    log_end_msg()
-    {
-       if [ "$1" = 0 ]; then
-           echo "done"
-       else
-           echo "failed!"
-       fi
-       return $1
-    }
-    log_success_msg()
-    {
-       echo "$@"
-    }
-    log_failure_msg()
-    {
-       echo "$@"
-    }
-fi
-
-[ -f /etc/default/pcmciautils ] && . /etc/default/pcmciautils
-
-case $PCMCIA in
-    no|false)
-       exit 0
-       ;;
-esac
-
-[ -f /etc/default/rcS ] && . /etc/default/rcS
-
-# Are we running from init?
-run_by_init()
-{
-    ([ "$previous" ] && [ "$runlevel" ]) || [ "$runlevel" = S ]
-}
-
-if ls /sys/class/pcmcia_socket/* >/dev/null 2>&1; then
-    if ! run_by_init; then
-       log_success_msg "PCMCIA bridge driver already present in kernel"
-    fi
-    exit 0
-fi
-
-KERNEL_VERSION="$(uname -r | sed 's/-.*//')"
-
-supported_kernel()
-{
-    case $KERNEL_VERSION in
-       2.[012345].*|2.6.[0-9]|2.6.[0-9][!0-9]*) return 1 ;;
-       2.6.1[012]|2.6.1[012][!0-9]*) return 1 ;;
-    esac
-    return 0
-}
-
-if ! supported_kernel; then
-    if ! run_by_init; then
-       log_failure_msg "pcmciautils requires Linux >= 2.6.13-rc1; use pcmcia-cs instead"
-    fi
-    exit 1
-fi
-
-if [ -z "$PCIC" ]; then
-    if ! run_by_init; then
-       log_failure_msg "No PCMCIA bridge module specified"
-    fi
-    exit 1
-fi
-
-if ! [ -e /dev/.udev ]; then
-    if ! run_by_init; then
-       log_failure_msg "pcmciautils requires udev to be enabled"
-    fi
-    exit 1
-fi
-
-if [ "$VERBOSE" = "no" ]; then
-    MODPROBE_OPTIONS="$MODPROBE_OPTIONS -Q"
-    export MODPROBE_OPTIONS
-fi
-
-case "$1" in
-    start)
-       log_daemon_msg "Loading PCMCIA bridge driver module" "$PCIC"
-
-       if [ "$CORE_OPTS" ]; then
-           modprobe -Qb pcmcia_core $CORE_OPTS
-       fi
-       
-       modprobe -Qb $PCIC $PCIC_OPTS
-       
-       log_end_msg $?
-       ;;
-
-    stop)
-       ;;
+def inputiter():
+    if os.isatty(sys.stdin.fileno()):
+        while 1:
+            try:
+                yield raw_input('bup> ')
+            except EOFError:
+                break
+    else:
+        for line in sys.stdin:
+            yield line
+
+
+def _completer_get_subs(line):
+    (qtype, lastword) = shquote.unfinished_word(line)
+    (dir,name) = os.path.split(lastword)
+    #log('\ncompleter: %r %r %r\n' % (qtype, lastword, text))
+    n = pwd.resolve(dir)
+    subs = list(filter(lambda x: x.name.startswith(name),
+                       n.subs()))
+    return (dir, name, qtype, lastword, subs)
+
+
+_last_line = None
+_last_res = None
+def completer(text, state):
+    global _last_line
+    global _last_res
+    try:
+        line = readline.get_line_buffer()[:readline.get_endidx()]
+        if _last_line != line:
+            _last_res = _completer_get_subs(line)
+            _last_line = line
+        (dir, name, qtype, lastword, subs) = _last_res
+        if state < len(subs):
+            sn = subs[state]
+            sn1 = sn.resolve('')  # deref symlinks
+            fullname = os.path.join(dir, sn.name)
+            if stat.S_ISDIR(sn1.mode):
+                ret = shquote.what_to_add(qtype, lastword, fullname+'/',
+                                          terminate=False)
+            else:
+                ret = shquote.what_to_add(qtype, lastword, fullname,
+                                          terminate=True) + ' '
+            return text + ret
+    except Exception, e:
+        log('\nerror in completion: %s\n' % e)
+
+            
+optspec = """
+bup ftp
+"""
+o = options.Options('bup ftp', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+git.check_repo_or_die()
+
+top = vfs.RefList(None)
+pwd = top
+
+if extra:
+    lines = extra
+else:
+    readline.set_completer_delims(' \t\n\r/')
+    readline.set_completer(completer)
+    readline.parse_and_bind("tab: complete")
+    lines = inputiter()
+
+for line in lines:
+    if not line.strip():
+        continue
+    words = [word for (wordstart,word) in shquote.quotesplit(line)]
+    cmd = words[0].lower()
+    #log('execute: %r %r\n' % (cmd, parm))
+    try:
+        if cmd == 'ls':
+            for parm in (words[1:] or ['.']):
+                do_ls(parm, pwd.resolve(parm))
+        elif cmd == 'cd':
+            for parm in words[1:]:
+                pwd = pwd.resolve(parm)
+        elif cmd == 'pwd':
+            print pwd.fullname()
+        elif cmd == 'cat':
+            for parm in words[1:]:
+                write_to_file(pwd.resolve(parm).open(), sys.stdout)
+        elif cmd == 'get':
+            if len(words) not in [2,3]:
+                raise Exception('Usage: get <filename> [localname]')
+            rname = words[1]
+            (dir,base) = os.path.split(rname)
+            lname = len(words)>2 and words[2] or base
+            inf = pwd.resolve(rname).open()
+            log('Saving %r\n' % lname)
+            write_to_file(inf, open(lname, 'wb'))
+        elif cmd == 'mget':
+            for parm in words[1:]:
+                (dir,base) = os.path.split(parm)
+                for n in pwd.resolve(dir).subs():
+                    if fnmatch.fnmatch(n.name, base):
+                        try:
+                            log('Saving %r\n' % n.name)
+                            inf = n.open()
+                            outf = open(n.name, 'wb')
+                            write_to_file(inf, outf)
+                            outf.close()
+                        except Exception, e:
+                            log('  error: %s\n' % e)
+        elif cmd == 'help' or cmd == '?':
+            log('Commands: ls cd pwd cat get mget help quit\n')
+        elif cmd == 'quit' or cmd == 'exit' or cmd == 'bye':
+            break
+        else:
+            raise Exception('no such command %r' % cmd)
+    except Exception, e:
+        log('error: %s\n' % e)
+        #raise
+#!/usr/bin/env python
+import sys, mmap
+from bup import options, _hashsplit
+from bup.helpers import *
+
+optspec = """
+bup random [-S seed] <numbytes>
+--
+S,seed=   optional random number seed (default 1)
+f,force   print random data to stdout even if it's a tty
+"""
+o = options.Options('bup random', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if len(extra) != 1:
+    o.fatal("exactly one argument expected")
+
+total = parse_num(extra[0])
+
+if opt.force or (not os.isatty(1) and
+                 not atoi(os.environ.get('BUP_FORCE_TTY')) & 1):
+    _hashsplit.write_random(sys.stdout.fileno(), total, opt.seed or 0)
+else:
+    log('error: not writing binary data to a terminal. Use -f to force.\n')
+    sys.exit(1)
+#!/usr/bin/env python
+import sys, os, glob
+from bup import options
+
+optspec = """
+bup help <command>
+"""
+o = options.Options('bup help', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if len(extra) == 0:
+    # the wrapper program provides the default usage string
+    os.execvp(os.environ['BUP_MAIN_EXE'], ['bup'])
+elif len(extra) == 1:
+    docname = (extra[0]=='bup' and 'bup' or ('bup-%s' % extra[0]))
+    exe = sys.argv[0]
+    (exepath, exefile) = os.path.split(exe)
+    manpath = os.path.join(exepath, '../Documentation/' + docname + '.[1-9]')
+    g = glob.glob(manpath)
+    if g:
+        os.execvp('man', ['man', '-l', g[0]])
+    else:
+        os.execvp('man', ['man', docname])
+else:
+    o.fatal("exactly one command name expected")
+#!/usr/bin/env python
+import sys, os, stat, errno, fuse, re, time, tempfile
+from bup import options, git, vfs
+from bup.helpers import *
+
+
+class Stat(fuse.Stat):
+    def __init__(self):
+        self.st_mode = 0
+        self.st_ino = 0
+        self.st_dev = 0
+        self.st_nlink = 0
+        self.st_uid = 0
+        self.st_gid = 0
+        self.st_size = 0
+        self.st_atime = 0
+        self.st_mtime = 0
+        self.st_ctime = 0
+        self.st_blocks = 0
+        self.st_blksize = 0
+        self.st_rdev = 0
+
+
+cache = {}
+def cache_get(top, path):
+    parts = path.split('/')
+    cache[('',)] = top
+    c = None
+    max = len(parts)
+    #log('cache: %r\n' % cache.keys())
+    for i in range(max):
+        pre = parts[:max-i]
+        #log('cache trying: %r\n' % pre)
+        c = cache.get(tuple(pre))
+        if c:
+            rest = parts[max-i:]
+            for r in rest:
+                #log('resolving %r from %r\n' % (r, c.fullname()))
+                c = c.lresolve(r)
+                key = tuple(pre + [r])
+                #log('saving: %r\n' % (key,))
+                cache[key] = c
+            break
+    assert(c)
+    return c
+        
     
-    restart)
-       $0 stop
-       $0 start
-       exit $?
-       ;;
-
-    reload|force-reload)
-       ;;
-
-    *)
-       log_success_msg "Usage: $0 {start|stop|restart|reload|force-reload}"
-       exit 2
-       ;;
-esac
-#!/bin/sh
-#
-# start/stop portmap daemon.
-
-### BEGIN INIT INFO
-# Provides:          portmap
-# Required-Start:    $network
-# Required-Stop:     $network
-# Should-Start:      $named
-# Should-Stop:       $named
-# Default-Start:     S 1 2 3 4 5
-# Default-Stop:      0 6
-### END INIT INFO
-
-test -f /sbin/portmap || exit 0
-
-. /lib/lsb/init-functions
-
-OPTIONS=""
-if [ -f /etc/default/portmap ]; then
-  . /etc/default/portmap
-elif [ -f /etc/portmap.conf ]; then
-  . /etc/portmap.conf
-fi
-
-case "$1" in
-    start)
-       pid=`pidof portmap`
-       if [ -n "$pid" ] ; then
-            log_begin_msg "Not starting portmap daemon.  Already running."
-            log_end_msg 0
-            exit 0
-       fi
-       log_begin_msg "Starting portmap daemon..."
-        start-stop-daemon --start --quiet --oknodo --exec /sbin/portmap -- $OPTIONS
-       log_end_msg $?
-
-       sleep 1 # needs a short pause or pmap_set won't work. :(
-       if [ -f /var/run/portmap.upgrade-state ]; then
-         log_begin_msg "Restoring old RPC service information..."
-         pmap_set </var/run/portmap.upgrade-state
-         log_end_msg $?
-         rm -f /var/run/portmap.upgrade-state
-       else
-         if [ -f /var/run/portmap.state ]; then
-           pmap_set </var/run/portmap.state
-           rm -f /var/run/portmap.state
-         fi
-       fi
-
-       ;;
-    stop)
-       log_begin_msg "Stopping portmap daemon..."
-       pmap_dump >/var/run/portmap.state
-       start-stop-daemon --stop --quiet --oknodo --exec /sbin/portmap
-       log_end_msg $?
-       ;;
-    force-reload)
-       $0 restart
-       ;;
-    restart)
-       $0 stop
-       $0 start
-       ;;
-    *)
-       log_success_msg "Usage: /etc/init.d/portmap {start|stop|force-reload|restart}"
-       exit 1
-       ;;
-esac
-
-exit 0
-
-#!/bin/sh -e
-#
-#   /etc/init.d/ppp: start or stop PPP link.
-#
-# This configuration method is deprecated, please use /etc/network/interfaces.
-
-[ -x /usr/sbin/pppd -a -f /etc/ppp/ppp_on_boot ] || exit 0
-if [ -x /etc/ppp/ppp_on_boot ]; then RUNFILE=1; fi
-. /lib/lsb/init-functions
-
-case "$1" in
-start)
-    log_begin_msg "Starting up PPP link..."
-    if [ "$RUNFILE" = "1" ]; then
-        /etc/ppp/ppp_on_boot
-    else
-        pppd call provider
-    fi
-    log_end_msg $?
-    ;;
-stop)
-    log_begin_msg "Shutting down PPP link..."
-    if [ "$RUNFILE" = "1" ]; then
-        poff -a
-    else
-        poff provider
-    fi
-    log_end_msg $?
-    ;;
-restart|force-reload)
-    log_begin_msg "Restarting PPP link..."
-    if [ "$RUNFILE" = "1" ]; then      
-        poff -a || true
-        sleep 5
-        /etc/ppp/ppp_on_boot
-    else                  
-        poff provider || true
-        sleep 5
-        pppd call provider
-    fi
-    log_end_msg $?
-    ;;
-*)
-    log_success_msg "Usage: /etc/init.d/ppp {start|stop|restart|force-reload}"
-    exit 1
-    ;;
-esac
-
-exit 0
-#!/bin/sh -e
-### BEGIN INIT INFO
-# Provides:          pppd-dns
-# Required-Start:    $local_fs
-# Default-Start:     S
-# Short-Description: Restore resolv.conf if the system crashed.
-### END INIT INFO
-#
-# Restore /etc/resolv.conf if the system crashed before the ppp link
-# was shut down.
-
-[ -x /etc/ppp/ip-down.d/0000usepeerdns ] \
-       && exec /etc/ppp/ip-down.d/0000usepeerdns
-
-#!/bin/sh
-###########################################################################
-# Autostart script for guest tools' service.
-#
-# Copyright (c) 2005-2008 Parallels Software International, Inc.
-# All rights reserved.
-# http://www.parallels.com
-###########################################################################
-
-
-###
-# chkconfig: 2345 99 20
-# description: Autostart script for guest tools' service.
-###
-
-### BEGIN INIT INFO
-# Provides: prltoolsd
-# required-start:
-# required-stop:
-# Default-Start: 2 3 4 5
-# Default-Stop:  0 1 6
-# Description:   Autostart script for guest tools' service.
-### END INIT INFO
-
-
-###########################################################################
-# Set configuration data
-###########################################################################
-
-prlfile="prltoolsd"
-exefile="/usr/bin/${prlfile}"
-pidfile="/var/run/${prlfile}.pid"
-
-# Set custom options if they are required
-PRLTOOLSD_OPTIONS="-p $pidfile"
-
-###########################################################################
-# Install client ID for wireless bridged networking
-###########################################################################
-
-# Install record for client ID sending for each networking card
-# in the system in the dhclient.conf (dhclient is installed)
-dhclient_install() {
-       # Locate dhclient.conf using strings. The directory can be
-       # different on different distributions
-       CONF=`strings /sbin/dhclient | grep etc | grep dhclient.conf`
-       IFACES=$*
-
-       # and can even not exists...
-       mkdir -p `dirname $CONF`
-       touch $CONF
-
-       for IFACE in $IFACES; do
-               HWADDR=`ifconfig -a | grep ^$IFACE | awk '{ print $5 }'`
-               export IFACE HWADDR
-
-               # Install section like
-                # interface "eth0" {
-               #       send dhcp-client-identifier 1:<real_mac>;
-               # }
-                # or leave it untouched if present
-               awk '
-                       BEGIN {
-                               inside_iface = 0
-                               iface_found = 0
-                       }
-                       END {
-                               iface = ENVIRON["IFACE"]
-                               addr = ENVIRON["HWADDR"]
-                               if (!iface_found) {
-                                       print "interface \""iface"\" {"
-                                       print " send dhcp-client-identifier 1:"addr"; # Remove this comment on manual client-id modification"
-                                       print "}"
-                               }
-                       }
-
-                       /^ *interface/ {
-                               iface = ENVIRON["IFACE"]
-                               test_if = $2
-                               gsub(/\"/, "", test_if)
-                               gsub(/ /, "", test_if)
-                               if (test_if == iface)
-                                       iface_found = inside_iface = 1
-                       }
-
-                       /dhcp-client-identifier/ {
-                               str = $0
-                               if (inside_iface &&
-                                   match(str, /Remove this/))
-                                       next
-                               else
-                                       inside_iface = 0
-                       }
-
-                       /\}/ {
-                               addr = ENVIRON["HWADDR"]
-
-                               if (inside_iface)
-                                       print " send dhcp-client-identifier 1:"addr"; # Remove this comment on manual client-id modification"
-                               inside_iface = 0
-                       }
-
-                       {
-                               print $0
-                       }
-               ' $CONF >$CONF.tmp1 || exit 0
-               mv $CONF.tmp1 $CONF
-       done
-}
-
-# Install key to send client ID (dhcpcd is installed)
-# Kludge to do this on the per/interface basis is not found
-dhcpc_install() {
-       CONF="/etc/sysconfig/network/dhcp"
-       HWADDR=`/sbin/ifconfig -a | awk '/HWaddr/ { print $5 ; exit }'`
-       export HWADDR
-       awk '/DHCLIENT_CLIENT_ID=/{
-               str = str1 = $0
-               sub(/\".*\"/, "", str1)
-               if (length(str1) + 2 >= length(str) || match($str, /Remove this/))
-                       print "DHCLIENT_CLIENT_ID=\"1:"ENVIRON["HWADDR"]"\" # Remove this comment on manual client-id modification"
-               else
-                       print $0
-               next
-       }
-       {
-               print $0
-       }
-       ' $CONF >$CONF.tmp1 || exit 0
-       mv $CONF.tmp1 $CONF
-}
-
-clientid_install() {
-       IFACES=`ifconfig -a | awk '/HWaddr/{ print $1 }' | xargs`
-       if [ -n "$IFACES" ]; then
-               [ -f /sbin/dhclient ] && dhclient_install $IFACES
-               [ -f /etc/sysconfig/network/dhcp ] && dhcpc_install $IFACES
-       fi
-}
-
-###########################################################################
-# Start and Stop operations for tools' daemon
-###########################################################################
-
-start() {
-    if [ -f $pidfile ]; then
-        rm -f $pidfile;
-    fi
-
-    echo -n $"Loading Parallels ToolsGate driver: "
-    if modprobe prl_tg; then
-        echo $"done"
-    else
-        echo $"failed"
-    fi
-
-    echo -n $"Loading Parallels Network driver: "
-
-       # Installing client-id to the DHCP client configuration
-       # is temporary disabled.
-
-    #clientid_install
-
-    if modprobe prl_eth; then
-        echo $"done"
-    else
-        echo $"failed"
-    fi
-
-    echo -n $"Loading Parallels Shared Folders driver: "
-    if modprobe prl_fs; then
-        echo $"done"
-    else
-        echo $"failed"
-    fi
-
-    echo -n $"Starting Parallels tools daemon: "
-    $exefile ${PRLTOOLSD_OPTIONS}
-    RETVAL=$?
-    if [ -n $RETVAL ]; then
-        echo $"done"
-    else
-        echo $"failed"
-    fi
-
-    return $RETVAL
-}
-
-stop() {
-    RETVAL=0
-
-    echo -n $"Shutting down Parallels tools daemon: "
-
-    if [ -f $pidfile ]; then
-        prlpid=`cat $pidfile 2>/dev/null`
-
-        if [ -n $prlpid ] && [ -e /proc/$prlpid ]; then
-            kill $prlpid;
-            RETVAL=$?
-        fi
-
-        rm -f $pidfile;
-    fi
-
-    if [ -n $RETVAL ]; then
-        echo $"done"
-    else
-        echo $"failed"
-    fi
-
-    return $RETVAL
-}
-
-###########################################################################
-# Perform initial operations
-###########################################################################
-
-[ -f $exefile ] || exit 0
-
-###########################################################################
-# Start/stop guest tools' service
-###########################################################################
-
-case "$1" in
-    start)
-        start
-    ;;
-    stop)
-        stop
-    ;;
-    restart)
-        stop
-        start
-    ;;
-    *)
-        echo "=> This script starts/stops Parallels guest tools' service"
-        echo "Usage: $0 <start | stop | restart>"
-        exit 1
-    ;;
-esac
-
-exit $?
-#! /bin/sh
-# /etc/init.d/procps: Set kernel variables from /etc/sysctl.conf
-#
-# written by Elrond <Elrond@Wunder-Nett.org>
-
-### BEGIN INIT INFO
-# Provides:          procps
-# Required-Start:    mountkernfs
-# Required-Stop:
-# Default-Start:     S
-# Default-Stop:
-# Short-Description: Configure kernel parameters at boottime
-# Description:  Loads kernel parameters that are specified in /etc/sysctl.conf
-### END INIT INFO
-
-
-# Check for existance of the default file and exit if not there,
-# Closes #52839 for the boot-floppy people
-[ -r /etc/default/rcS ] || exit 0
-. /etc/default/rcS
-. /lib/lsb/init-functions
-
-PATH=/sbin:$PATH
-which sysctl > /dev/null || exit 0
-
-
-case "$1" in
-       start|restart|force-reload)
-               if [ ! -r /etc/sysctl.conf ]
-               then
-                       exit 0
-               fi
-               quiet="-q"
-               if [ "$VERBOSE" = "yes" ]; then
-                       quiet=""
-               fi
-              log_action_begin_msg "Setting kernel variables"
-               sysctl $quiet -p
-              log_action_end_msg $?
-               ;;
-       stop)
-               ;;
-       *)
-               echo "Usage: /etc/init.d/procps {start|stop|restart|force-reload}" >&2
-               exit 3
-               ;;
-esac
-exit 0
-#! /bin/sh
-#
-# rc
-#
-# Starts/stops services on runlevel changes.
-#
-# Optimization: A start script is not run when the service was already
-# configured to run in the previous runlevel.  A stop script is not run
-# when the the service was already configured not to run in the previous
-# runlevel.
-#
-# Authors:
-#      Miquel van Smoorenburg <miquels@cistron.nl>
-#      Bruce Perens <Bruce@Pixar.com>
-
-PATH=/sbin:/bin:/usr/sbin:/usr/bin
-export PATH
-
-# Un-comment the following for debugging.
-# debug=echo
-
-# Specify method used to enable concurrent init.d scripts.
-# Valid options are 'none' and 'shell'.
-CONCURRENCY=none
 
-# Make sure the name survive changing the argument list
-scriptname="$0"
-
-umask 022
-
-#
-# Stub to do progress bar ticks (currently just for usplash) on startup
-#
-startup_progress() {
-    $@
-    step=$(($step + $step_change))
-    progress=$(($step * $progress_size / $num_steps + $first_step))
-    if type usplash_write >/dev/null 2>&1; then
-        usplash_write "PROGRESS $progress" || true
-    fi
-}
-
-#
-# Start script or program.
-#
-case "$CONCURRENCY" in
-  none)
-       startup() {
-               action=$1
-               shift
-               scripts="$@"
-               sh=sh
-               # Debian Policy Â§9.3.1 requires .sh scripts in runlevel S to be sourced
-               # However, some important packages currently contain .sh scripts
-               # that do "exit" at some point, thus killing this process.  Bad!
-               #[ S = "$runlevel" ] && sh=.
-               for script in $scripts ; do
-                       case "$script" in
-                         *.sh)
-                               if [ "." = "$sh" ] ; then
-                                       set "$action"
-                                       RC_SAVE_PATH="$PATH"
-                                       startup_progress $debug . "$script"
-                                       PATH="$RC_SAVE_PATH"
-                               else
-                                       startup_progress $debug $sh "$script" $action
-                               fi
-                               ;;
-                         *)
-                               startup_progress $debug "$script" $action
-                               ;;
-                       esac
-               done
-       }
-       ;;
-  shell)
-       startup() {
-               action=$1
-               shift
-               scripts="$@"
-               sh=sh
-               # Debian Policy Â§9.3.1 requires .sh scripts in runlevel S to be sourced
-               # However, some important packages currently contain .sh scripts
-               # that do "exit" at some point, thus killing this process.  Bad!
-               #[ S = "$runlevel" ] && sh=.
-               backgrounded=0
-               for script in $scripts ; do
-                       case "$script" in
-                         *.sh)
-                               if [ "." = "$sh" ] ; then
-                                       set "$action"
-                                       RC_SAVE_PATH="$PATH"
-                                       startup_progress $debug . "$script"
-                                       PATH="$RC_SAVE_PATH"
-                               else
-                                       startup_progress $debug $sh "$script" $action
-                               fi
-                               ;;
-                         *)
-                               startup_progress $debug "$script" $action &
-                               backgrounded=1
-                               ;;
-                       esac
-               done
-               [ 1 = "$backgrounded" ] && wait
-       }
-       ;;
-  startpar)
-       startup() {
-               action=$1
-               shift
-               scripts="$@"
-               sh=sh
-               # Debian Policy Â§9.3.1 requires .sh scripts in runlevel S to be sourced
-               # However, some important packages currently contain .sh scripts
-               # that do "exit" at some point, thus killing this process.  Bad!
-               #[ S = "$runlevel" ] && sh=.
-               # Make sure .sh scripts are sourced in runlevel S
-               if [ "." = "$sh" ] ; then
-                       newscripts=
-                       for script in $scripts ; do
-                               case "$script" in
-                                 *.sh)
-                                       set "$action"
-                                       RC_SAVE_PATH="$PATH"
-                                       startup_progress $debug . "$script"
-                                       PATH="$RC_SAVE_PATH"
-                                       ;;
-                                 *)
-                                       newscripts="$newscripts $script"
-                                       ;;
-                               esac
-                       done
-                       scripts="$newscripts"
-               fi
-
-               # startpar is not working as it should yet [pere 2005-09-10]
-               [ -n "$scripts" ] && startup_progress $debug startpar -a $action $scripts
-               startup_progress $debug startpar -a $action $scripts
-       }
-       ;;
-esac
-
-on_exit() {
-    echo "error: '$scriptname' exited outside the expected code flow."
-}
-trap on_exit EXIT # Enable emergency handler
-
-# Ignore CTRL-C only in this shell, so we can interrupt subprocesses.
-trap ":" INT QUIT TSTP
-
-# Should we also output to the console?
-# /proc won't be mounted if we don't have an initramfs, but then we're
-# dealing with custom systems so it's their own fault that they'll get
-# output from rcS ;)
-if grep -w -q quiet /proc/cmdline 2>/dev/null; then
-    QUIET=yes
-else
-    QUIET=no
-fi
-export QUIET
-
-# Set onlcr to avoid staircase effect.
-if [ "$QUIET" != yes ]; then
-    stty onlcr </dev/console >/dev/console 2>&1
-fi
-
-# Now find out what the current and what the previous runlevel are.
-runlevel=$RUNLEVEL
-
-# Get first argument. Set new runlevel to this argument.
-[ "$1" != "" ] && runlevel=$1
-if [ "$runlevel" = "" ]
-then
-       echo "Usage: $scriptname <runlevel>" >&2
-       exit 1
-fi
-previous=$PREVLEVEL
-[ "$previous" = "" ] && previous=N
-
-export runlevel previous
-
-if [ S = "$runlevel" ]
-then
-       #
-       # See if system needs to be setup. This is ONLY meant to
-       # be used for the initial setup after a fresh installation!
-       #
-       if [ -x /sbin/unconfigured.sh ]
-       then
-               /sbin/unconfigured.sh
-       fi
-fi
-
-. /etc/default/rcS
-export VERBOSE
-
-# Is there an rc directory for this new runlevel?
-if [ -d /etc/rc$runlevel.d ]
-then
-       # Split the progress bar into thirds
-       progress_size=$((100 / 3))
-
-       case "$runlevel" in
-               0|6)
-                       ACTION=stop
-                       # Count down from 0 to -100 and use the entire bar
-                       first_step=0
-                       progress_size=100
-                       step_change=-1
-                       ;;
-               S)
-                       ACTION=start
-                       # Use 2/3 of the space
-                       first_step=0
-                       progress_size=$(($progress_size * 2))
-                       step_change=1
-                       ;;
-               *)
-                       ACTION=start
-                       # Begin where rcS left off and use the final 1/3 of
-                       # the space (by leaving progress_size unchanged)
-                       first_step=$(($progress_size * 2))
-                       step_change=1
-                       ;;
-       esac
-
-       # Count the number of scripts we need to run (for usplash progress bar)
-       num_steps=0
-       for s in /etc/rc$runlevel.d/[SK]*; do
-            case "${s##/etc/rc$runlevel.d/S??}" in
-                gdm|xdm|kdm|ltsp-client-core|reboot|halt)
-                    break
-                    ;;
-            esac
-            num_steps=$(($num_steps + 1))
-        done
-
-        step=0
-
-       # First, run the KILL scripts.
-       if [ "$previous" != N ]
-       then
-               # Run all scripts with the same level in parallel
-               CURLEVEL=""
-               for s in /etc/rc$runlevel.d/K*
-               do
-                       level=$(echo $s | sed 's/.*\/K\([0-9][0-9]\).*/\1/')
-                       if [ "$level" = "$CURLEVEL" ]
-                       then
-                               continue
-                       fi
-                       CURLEVEL=$level
-                       SCRIPTS=""
-                       for i in /etc/rc$runlevel.d/K$level*
-                       do
-                               # Check if the script is there.
-                               [ ! -f $i ] && continue
-
-                               #
-                               # Find stop script in previous runlevel but
-                               # no start script there.
-                               #
-                               suffix=${i#/etc/rc$runlevel.d/K[0-9][0-9]}
-                               previous_stop=/etc/rc$previous.d/K[0-9][0-9]$suffix
-                               previous_start=/etc/rc$previous.d/S[0-9][0-9]$suffix
-                               #
-                               # If there is a stop script in the previous level
-                               # and _no_ start script there, we don't
-                               # have to re-stop the service.
-                               #
-                               [ -f $previous_stop ] && [ ! -f $previous_start ] && continue
-
-                               # Stop the service.
-                               SCRIPTS="$SCRIPTS $i"
-                       done
-                       startup stop $SCRIPTS
-               done
-       fi
-
-       # Now run the START scripts for this runlevel.
-       # Run all scripts with the same level in parallel
-       CURLEVEL=""
-       for s in /etc/rc$runlevel.d/S*
-       do
-               level=$(echo $s | sed 's/.*\/S\([0-9][0-9]\).*/\1/')
-               if [ "$level" = "$CURLEVEL" ]
-               then
-                       continue
-               fi
-               CURLEVEL=$level
-               SCRIPTS=""
-               for i in /etc/rc$runlevel.d/S$level*
-               do
-                       [ ! -f $i ] && continue
-
-                       if [ "$previous" != N ]
-                       then
-                               #
-                               # Find start script in previous runlevel and
-                               # stop script in this runlevel.
-                               #
-                               suffix=${i#/etc/rc$runlevel.d/S[0-9][0-9]}
-                               stop=/etc/rc$runlevel.d/K[0-9][0-9]$suffix
-                               previous_start=/etc/rc$previous.d/S[0-9][0-9]$suffix
-                               #
-                               # If there is a start script in the previous level
-                               # and _no_ stop script in this level, we don't
-                               # have to re-start the service.
-                               #
-                               [ -f $previous_start ] && [ ! -f $stop ] && continue
-                       fi
-                       SCRIPTS="$SCRIPTS $i"
-               done
-               startup $ACTION $SCRIPTS
-       done
-fi
-
-if [ S = "$runlevel" ]
-then
-       #
-       # For compatibility, run the files in /etc/rc.boot too.
-       #
-       [ -d /etc/rc.boot ] && run-parts /etc/rc.boot
-
-       #
-       # Finish setup if needed. The comment above about
-       # /sbin/unconfigured.sh applies here as well!
-       #
-       if [ -x /sbin/setup.sh ]
-       then
-               /sbin/setup.sh
-       fi
-fi
-
-trap - EXIT # Disable emergency handler
-
-exit 0
-
-#! /bin/sh
-
-PATH=/sbin:/bin:/usr/sbin:/usr/bin
-[ -f /etc/default/rcS ] && . /etc/default/rcS
-. /lib/lsb/init-functions
-
-do_start() {
-       if [ -x /etc/rc.local ]; then
-               log_begin_msg "Running local boot scripts (/etc/rc.local)"
-               /etc/rc.local
-               log_end_msg $?
-       fi
-}
-
-case "$1" in
-    start)
-       do_start
-        ;;
-    restart|reload|force-reload)
-        echo "Error: argument '$1' not supported" >&2
-        exit 3
-        ;;
-    stop)
-        ;;
-    *)
-        echo "Usage: $0 start|stop" >&2
-        exit 3
-        ;;
-esac
-#! /bin/sh
-#
-# rcS
-#
-# Call all S??* scripts in /etc/rcS.d/ in numerical/alphabetical order
-#
-
-exec /etc/init.d/rc S
-       Configuration of System V init under Debian GNU/Linux
-
-Most Unix versions have a file here that describes how the scripts
-in this directory work, and how the links in the /etc/rc?.d/ directories
-influence system startup/shutdown.
-
-For Debian, this information is contained in the policy manual, chapter 
-"System run levels and init.d scripts".  The Debian Policy Manual is 
-available at:
-
-    http://www.debian.org/doc/debian-policy/#contents
-
-The Debian Policy Manual is also available in the Debian package
-"debian-policy".  When this package is installed, the policy manual can be
-found in directory /usr/share/doc/debian-policy. If you have a browser
-installed you can probably read it at
-
-    file://localhost/usr/share/doc/debian-policy/
-
-Some more detailed information can also be found in the files in the
-/usr/share/doc/sysv-rc directory.
-
-Debian Policy dictates that /etc/init.d/*.sh scripts must work properly
-when sourced.  The following additional rules apply:
-
-* /etc/init.d/*.sh scripts may not rely for their correct functioning
-  on their being sourced rather than executed.  That is, they must work
-  properly when executed too. They must include "#!/bin/sh" at the top.
-
-* /etc/init.d/*.sh scripts must conform to the rules for sh scripts as
-  spelled out in the Debian policy section entitled "Scripts" (§10.4).
-
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          reboot
-# Required-Start:    umountroot $network
-# Required-Stop:
-# Should-Start:      lvm raid2
-# Default-Start:     6
-# Default-Stop:
-# Short-Description: Execute the reboot command.
-# Description:
-### END INIT INFO
-
-PATH=/usr/sbin:/usr/bin:/sbin:/bin
-
-. /lib/lsb/init-functions
-
-do_stop () {
-       # Message should end with a newline since kFreeBSD may
-       # print more stuff (see #323749)
-       log_action_msg "Will now restart"
-       reboot -d -f -i
-}
-
-case "$1" in
-  start)
-       # No-op
-       ;;
-  restart|reload|force-reload)
-       echo "Error: argument '$1' not supported" >&2
-       exit 3
-       ;;
-  stop)
-       do_stop
-       ;;
-  *)
-       echo "Usage: $0 start|stop" >&2
-       exit 3
-       ;;
-esac
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          rmnologin
-# Required-Start:    $local_fs $remote_fs
-# Required-Stop: 
-# Should-Start:      kdm xdm gdm $syslog
-# Default-Start:     0 1 2 3 4 5 6
-# Default-Stop:       
-# Short-Description: Remove /etc/nologin at boot
-# Description:       This script removes the /etc/nologin file as the
-#                    last step in the boot process, if DELAYLOGIN=yes.
-#                    If DELAYLOGIN=no, /etc/nologin was not created by
-#                    bootmisc earlier in the boot process.
-### END INIT INFO
-
-PATH=/sbin:/bin
-[ "$DELAYLOGIN" ] || DELAYLOGIN=yes
-. /lib/init/vars.sh
-
-do_start () {
-       #
-       # If login delaying is enabled then remove the flag file
-       #
-       case "$DELAYLOGIN" in
-         Y*|y*)
-               rm -f /var/lib/initscripts/nologin
-               ;;
-       esac
-}
-
-case "$1" in
-  start)
-       do_start
-       ;;
-  restart|reload|force-reload)
-       echo "Error: argument '$1' not supported" >&2
-       exit 3
-       ;;
-  stop)
-       # No-op
-       ;;
-  *)
-       echo "Usage: $0 start|stop" >&2
-       exit 3
-       ;;
-esac
-
-:
-#! /bin/sh
-
-### BEGIN INIT INFO
-# Provides:          rsyncd
-# Required-Start:    $network
-# Required-Stop:     $syslog
-# Should-Start:      $named $syslog
-# Should-Stop:       $syslog network
-# Default-Start:     2 3 4 5
-# Default-Stop:      0 1 6
-# Short-Description: fast remote file copy program daemon
-# Description:       rsync is a program that allows files to be copied to and
-#                    from remote machines in much the same way as rcp.
-#                    This provides rsyncd daemon functionality.
-### END INIT INFO
-
-set -e
-
-# /etc/init.d/rsync: start and stop the rsync daemon
-
-DAEMON=/usr/bin/rsync
-RSYNC_ENABLE=false
-RSYNC_OPTS=''
-RSYNC_DEFAULTS_FILE=/etc/default/rsync
-RSYNC_CONFIG_FILE=/etc/rsyncd.conf
-RSYNC_NICE_PARM=''
-
-test -x $DAEMON || exit 0
-
-. /lib/lsb/init-functions
-. /etc/default/rcS
-
-if [ -s $RSYNC_DEFAULTS_FILE ]; then
-    . $RSYNC_DEFAULTS_FILE
-    case "x$RSYNC_ENABLE" in
-        xtrue|xfalse)   ;;
-        xinetd)         exit 0
-                        ;;
-        *)              log_failure_msg "Value of RSYNC_ENABLE in $RSYNC_DEFAULTS_FILE must be either 'true' or 'false';"
-                        log_failure_msg "not starting rsync daemon."
-                        exit 1
-                        ;;
-    esac
-    case "x$RSYNC_NICE" in
-        x[0-9])         RSYNC_NICE_PARM="--nicelevel $RSYNC_NICE";;
-        x[1-9][0-9])    RSYNC_NICE_PARM="--nicelevel $RSYNC_NICE";;
-        x)              ;;
-        *)              log_warning_msg "Value of RSYNC_NICE in $RSYNC_DEFAULTS_FILE must be a value between 0 and 19 (inclusive);"
-                        log_warning_msg "ignoring RSYNC_NICE now."
-                        ;;
-    esac
-fi
-
-export PATH="${PATH:+$PATH:}/usr/sbin:/sbin"
-
-case "$1" in
-  start)
-       if "$RSYNC_ENABLE"; then
-            log_daemon_msg "Starting rsync daemon" "rsync"
-           if [ -s /var/run/rsync.pid ] && kill -0 $(cat /var/run/rsync.pid) >/dev/null 2>&1; then
-                log_progress_msg "apparently already running"
-                log_end_msg 0
-               exit 0
-           fi
-            if [ ! -s "$RSYNC_CONFIG_FILE" ]; then
-                log_failure_msg "missing or empty config file $RSYNC_CONFIG_FILE"
-               log_end_msg 1
-                exit 1
-            fi
-            if start-stop-daemon --start --quiet --background \
-                --pidfile /var/run/rsync.pid --make-pidfile \
-                $RSYNC_NICE_PARM --exec /usr/bin/rsync \
-                -- --no-detach --daemon --config "$RSYNC_CONFIG_FILE" $RSYNC_OPTS
-            then
-                rc=0
-                sleep 1
-                if ! kill -0 $(cat /var/run/rsync.pid) >/dev/null 2>&1; then
-                    log_failure_msg "rsync daemon failed to start"
-                    rc=1
-                fi
-            else
-                rc=1
-            fi
-            if [ $rc -eq 0 ]; then
-                log_end_msg 0
-            else
-                log_end_msg 1
-                rm -f /var/run/rsync.pid
-            fi
-        else
-            if [ -s "$RSYNC_CONFIG_FILE" ]; then
-               [ "$VERBOSE" != no ] && log_warning_msg "rsync daemon not enabled in /etc/default/rsync, not starting..."
-            fi
-        fi
-       ;;
-  stop)
-        log_daemon_msg "Stopping rsync daemon" "rsync"
-       start-stop-daemon --stop --quiet --oknodo --pidfile /var/run/rsync.pid
-        log_end_msg $?
-       rm -f /var/run/rsync.pid
-       ;;
-
-  reload|force-reload)
-        log_warning_msg "Reloading rsync daemon: not needed, as the daemon"
-        log_warning_msg "re-reads the config file whenever a client connects."
-       ;;
-
-  restart)
-       set +e
-        if $RSYNC_ENABLE; then
-            log_daemon_msg "Restarting rsync daemon" "rsync"
-           if [ -s /var/run/rsync.pid ] && kill -0 $(cat /var/run/rsync.pid) >/dev/null 2>&1; then
-               start-stop-daemon --stop --quiet --oknodo --pidfile /var/run/rsync.pid || true
-               sleep 1
-           else
-                log_warning_msg "rsync daemon not running, attempting to start."
-               rm -f /var/run/rsync.pid
-           fi
-            if start-stop-daemon --start --quiet --background \
-                --pidfile /var/run/rsync.pid --make-pidfile \
-                $RSYNC_NICE_PARM --exec /usr/bin/rsync \
-                -- --no-detach --daemon --config "$RSYNC_CONFIG_FILE" $RSYNC_OPTS
-            then
-                rc=0
-                sleep 1
-                if ! kill -0 $(cat /var/run/rsync.pid) >/dev/null 2>&1; then
-                    log_failure_msg "rsync daemon failed to start"
-                    rc=1
-                fi
-            else
-                rc=1
-            fi
-            if [ $rc -eq 0 ]; then
-                log_end_msg 0
-            else
-                log_end_msg 1
-                rm -f /var/run/rsync.pid
-            fi
-        else
-            [ "$VERBOSE" != no ] && log_warning_msg "rsync daemon not enabled in /etc/default/rsync, not starting..."
-        fi
-       ;;
-
-  *)
-       echo "Usage: /etc/init.d/rsync {start|stop|reload|force-reload|restart}"
-       exit 1
-esac
-
-exit 0
-#!/bin/sh
-
-### BEGIN INIT INFO
-# Provides:          samba
-# Required-Start:    $network $local_fs $remote_fs
-# Required-Stop:     $network $local_fs $remote_fs
-# Default-Start:     2 3 4 5
-# Default-Stop:      0 1 6
-# Short-Description: start Samba daemons (nmbd and smbd)
-### END INIT INFO
-
-
-# Defaults
-RUN_MODE="daemons"
-
-# Reads config file (will override defaults above)
-[ -r /etc/default/samba ] && . /etc/default/samba
-
-DAEMON=/usr/sbin/smbd
-PIDDIR=/var/run/samba
-NMBDPID=$PIDDIR/nmbd.pid
-SMBDPID=$PIDDIR/smbd.pid
-
-# clear conflicting settings from the environment
-unset TMPDIR
-
-# See if the daemons are there
-test -x /usr/sbin/nmbd -a -x /usr/sbin/smbd || exit 0
-
-. /lib/lsb/init-functions
-
-case "$1" in
-       start)
-               log_daemon_msg "Starting Samba daemons"
-               # Make sure we have our PIDDIR, even if it's on a tmpfs
-               install -o root -g root -m 755 -d $PIDDIR
-
-               NMBD_DISABLED=`testparm -s --parameter-name='disable netbios' 2>/dev/null`
-               if [ "$NMBD_DISABLED" != 'Yes' ]; then
-                       log_progress_msg "nmbd"
-                       if ! start-stop-daemon --start --quiet --oknodo --exec /usr/sbin/nmbd -- -D
-                       then
-                               log_end_msg 1
-                               exit 1
-                       fi
-               fi
-
-               if [ "$RUN_MODE" != "inetd" ]; then
-                       log_progress_msg "smbd"
-                       if ! start-stop-daemon --start --quiet --oknodo --exec /usr/sbin/smbd -- -D; then
-                               log_end_msg 1
-                               exit 1
-                       fi
-               fi
-
-               log_end_msg 0
-               ;;
-       stop)
-               log_daemon_msg "Stopping Samba daemons"
-               log_progress_msg "nmbd"
-
-               start-stop-daemon --stop --quiet --pidfile $NMBDPID
-               # Wait a little and remove stale PID file
-               sleep 1
-               if [ -f $NMBDPID ] && ! ps h `cat $NMBDPID` > /dev/null
-               then
-                       # Stale PID file (nmbd was succesfully stopped),
-                       # remove it (should be removed by nmbd itself IMHO.)
-                       rm -f $NMBDPID
-               fi
-
-               if [ "$RUN_MODE" != "inetd" ]; then
-                       log_progress_msg "smbd"
-                       start-stop-daemon --stop --quiet --pidfile $SMBDPID
-                       # Wait a little and remove stale PID file
-                       sleep 1
-                       if [ -f $SMBDPID ] && ! ps h `cat $SMBDPID` > /dev/null
-                       then
-                               # Stale PID file (nmbd was succesfully stopped),
-                               # remove it (should be removed by smbd itself IMHO.)
-                               rm -f $SMBDPID
-                       fi
-               fi
-
-               log_end_msg 0
-
-               ;;
-       reload)
-               log_daemon_msg "Reloading /etc/samba/smb.conf" "smbd only"
-
-               start-stop-daemon --stop --signal HUP --pidfile $SMBDPID
-
-               log_end_msg 0
-               ;;
-       restart|force-reload)
-               $0 stop
-               sleep 1
-               $0 start
-               ;;
-       status)
-               pidofproc -p $SMBDPID $DAEMON >/dev/null
-               status=$?
-               if [ $status -eq 0 ]; then
-                       log_success_msg "SMBD is running"
-               else
-                       log_failure_msg "SMBD is not running"
-               fi
-               exit $status
-               ;;
-       *)
-               echo "Usage: /etc/init.d/samba {start|stop|reload|restart|force-reload|status}"
-               exit 1
-               ;;
-esac
-
-exit 0
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          sendsigs
-# Required-Start:    
-# Required-Stop: 
-# Default-Start:     6
-# Default-Stop:       
-# Short-Description: Kill all remaining processes.
-# Description: 
-### END INIT INFO
-
-PATH=/usr/sbin:/usr/bin:/sbin:/bin
-
-. /lib/lsb/init-functions
-
-do_stop () {
-       OMITPIDS=
-       if [ -e /var/run/sendsigs.omit ]; then
-               for pid in $(cat /var/run/sendsigs.omit); do
-                       OMITPIDS="${OMITPIDS:+$OMITPIDS }-o $pid"
-               done
-       fi
-
-       if [ -d /var/run/sendsigs.omit.d/ ]; then
-               for pidfile in /var/run/sendsigs.omit.d/*; do
-                       [ -f "$pidfile" ] || continue
-                       for pid in $(cat $pidfile); do
-                               OMITPIDS="${OMITPIDS:+$OMITPIDS }-o $pid"
-                       done
-               done
-       fi
-
-       # Kill all processes.
-       log_action_begin_msg "Terminating all remaining processes"
-       killall5 -15 $OMITPIDS
-       log_action_end_msg 0
-       sleep 5
-       log_action_begin_msg "Sending all processes the KILL signal"
-       killall5 -9 $OMITPIDS
-       log_action_end_msg 0
-}
-
-case "$1" in
-  start)
-       # No-op
-       ;;
-  restart|reload|force-reload)
-       echo "Error: argument '$1' not supported" >&2
-       exit 3
-       ;;
-  stop)
-       do_stop
-       if which usplash_down >/dev/null; then
-               usplash_down
-       fi
-       ;;
-  *)
-       echo "Usage: $0 start|stop" >&2
-       exit 3
-       ;;
-esac
-
-:
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          single
-# Required-Start:    $local_fs killprocs
-# Required-Stop:
-# Default-Start:     1
-# Default-Stop:
-# Short-Description: executed by init(8) upon entering runlevel 1 (single).
-### END INIT INFO
-
-PATH=/sbin:/bin
-
-. /lib/lsb/init-functions
-
-do_start () {
-       log_action_msg "Will now switch to single-user mode"
-       exec init -t1 S
-}
-
-case "$1" in
-  start)
-       do_start
-       ;;
-  restart|reload|force-reload)
-       echo "Error: argument '$1' not supported" >&2
-       exit 3
-       ;;
-  stop)
-       # No-op
-       ;;
-  *)
-       echo "Usage: $0 start|stop" >&2
-       exit 3
-       ;;
-esac
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          skeleton
-# Required-Start:    $local_fs $remote_fs
-# Required-Stop:     $local_fs $remote_fs
-# Default-Start:     2 3 4 5
-# Default-Stop:      S 0 1 6
-# Short-Description: Example initscript
-# Description:       This file should be used to construct scripts to be
-#                    placed in /etc/init.d.
-### END INIT INFO
-
-# Author: Foo Bar <foobar@baz.org>
-#
-# Please remove the "Author" lines above and replace them
-# with your own name if you copy and modify this script.
-
-# Do NOT "set -e"
-
-# PATH should only include /usr/* if it runs after the mountnfs.sh script
-PATH=/usr/sbin:/usr/bin:/sbin:/bin
-DESC="Description of the service"
-NAME=daemonexecutablename
-DAEMON=/usr/sbin/$NAME
-DAEMON_ARGS="--options args"
-PIDFILE=/var/run/$NAME.pid
-SCRIPTNAME=/etc/init.d/$NAME
-
-# Exit if the package is not installed
-[ -x "$DAEMON" ] || exit 0
-
-# Read configuration variable file if it is present
-[ -r /etc/default/$NAME ] && . /etc/default/$NAME
-
-# Load the VERBOSE setting and other rcS variables
-[ -f /etc/default/rcS ] && . /etc/default/rcS
-
-# Define LSB log_* functions.
-# Depend on lsb-base (>= 3.0-6) to ensure that this file is present.
-. /lib/lsb/init-functions
-
-#
-# Function that starts the daemon/service
-#
-do_start()
-{
-       # Return
-       #   0 if daemon has been started
-       #   1 if daemon was already running
-       #   2 if daemon could not be started
-       start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON --test > /dev/null \
-               || return 1
-       start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON -- \
-               $DAEMON_ARGS \
-               || return 2
-       # Add code here, if necessary, that waits for the process to be ready
-       # to handle requests from services started subsequently which depend
-       # on this one.  As a last resort, sleep for some time.
-}
+class BupFs(fuse.Fuse):
+    def __init__(self, top):
+        fuse.Fuse.__init__(self)
+        self.top = top
+    
+    def getattr(self, path):
+        log('--getattr(%r)\n' % path)
+        try:
+            node = cache_get(self.top, path)
+            st = Stat()
+            st.st_mode = node.mode
+            st.st_nlink = node.nlinks()
+            st.st_size = node.size()
+            st.st_mtime = node.mtime
+            st.st_ctime = node.ctime
+            st.st_atime = node.atime
+            return st
+        except vfs.NoSuchFile:
+            return -errno.ENOENT
+
+    def readdir(self, path, offset):
+        log('--readdir(%r)\n' % path)
+        node = cache_get(self.top, path)
+        yield fuse.Direntry('.')
+        yield fuse.Direntry('..')
+        for sub in node.subs():
+            yield fuse.Direntry(sub.name)
+
+    def readlink(self, path):
+        log('--readlink(%r)\n' % path)
+        node = cache_get(self.top, path)
+        return node.readlink()
+
+    def open(self, path, flags):
+        log('--open(%r)\n' % path)
+        node = cache_get(self.top, path)
+        accmode = os.O_RDONLY | os.O_WRONLY | os.O_RDWR
+        if (flags & accmode) != os.O_RDONLY:
+            return -errno.EACCES
+        node.open()
+
+    def release(self, path, flags):
+        log('--release(%r)\n' % path)
+
+    def read(self, path, size, offset):
+        log('--read(%r)\n' % path)
+        n = cache_get(self.top, path)
+        o = n.open()
+        o.seek(offset)
+        return o.read(size)
+
+
+if not hasattr(fuse, '__version__'):
+    raise RuntimeError, "your fuse module is too old for fuse.__version__"
+fuse.fuse_python_api = (0, 2)
+
+
+optspec = """
+bup fuse [-d] [-f] <mountpoint>
+--
+d,debug   increase debug level
+f,foreground  run in foreground
+"""
+o = options.Options('bup fuse', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if len(extra) != 1:
+    o.fatal("exactly one argument expected")
+
+git.check_repo_or_die()
+top = vfs.RefList(None)
+f = BupFs(top)
+f.fuse_args.mountpoint = extra[0]
+if opt.debug:
+    f.fuse_args.add('debug')
+if opt.foreground:
+    f.fuse_args.setmod('foreground')
+print f.multithreaded
+f.multithreaded = False
+
+f.main()
+#!/usr/bin/env python
+from bup import git, options, client
+from bup.helpers import *
+
+optspec = """
+[BUP_DIR=...] bup init [-r host:path]
+--
+r,remote=  remote repository path
+"""
+o = options.Options('bup init', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if extra:
+    o.fatal("no arguments expected")
+
+
+if opt.remote:
+    git.init_repo()  # local repo
+    git.check_repo_or_die()
+    cli = client.Client(opt.remote, create=True)
+    cli.close()
+else:
+    git.init_repo()
+#!/usr/bin/env python
+import sys, math, struct, glob
+from bup import options, git
+from bup.helpers import *
+
+PAGE_SIZE=4096
+SHA_PER_PAGE=PAGE_SIZE/200.
+
+
+def merge(idxlist, bits, table):
+    count = 0
+    for e in git.idxmerge(idxlist):
+        count += 1
+        prefix = git.extract_bits(e, bits)
+        table[prefix] = count
+        yield e
+
+
+def do_midx(outdir, outfilename, infilenames):
+    if not outfilename:
+        assert(outdir)
+        sum = Sha1('\0'.join(infilenames)).hexdigest()
+        outfilename = '%s/midx-%s.midx' % (outdir, sum)
+    
+    inp = []
+    total = 0
+    for name in infilenames:
+        ix = git.PackIdx(name)
+        inp.append(ix)
+        total += len(ix)
+
+    log('Merging %d indexes (%d objects).\n' % (len(infilenames), total))
+    if (not opt.force and (total < 1024 and len(infilenames) < 3)) \
+       or (opt.force and not total):
+        log('midx: nothing to do.\n')
+        return
+
+    pages = int(total/SHA_PER_PAGE) or 1
+    bits = int(math.ceil(math.log(pages, 2)))
+    entries = 2**bits
+    log('Table size: %d (%d bits)\n' % (entries*4, bits))
+    
+    table = [0]*entries
+
+    try:
+        os.unlink(outfilename)
+    except OSError:
+        pass
+    f = open(outfilename + '.tmp', 'w+')
+    f.write('MIDX\0\0\0\2')
+    f.write(struct.pack('!I', bits))
+    assert(f.tell() == 12)
+    f.write('\0'*4*entries)
+    
+    for e in merge(inp, bits, table):
+        f.write(e)
+        
+    f.write('\0'.join(os.path.basename(p) for p in infilenames))
+
+    f.seek(12)
+    f.write(struct.pack('!%dI' % entries, *table))
+    f.close()
+    os.rename(outfilename + '.tmp', outfilename)
+
+    # this is just for testing
+    if 0:
+        p = git.PackMidx(outfilename)
+        assert(len(p.idxnames) == len(infilenames))
+        print p.idxnames
+        assert(len(p) == total)
+        pi = iter(p)
+        for i in merge(inp, total, bits, table):
+            assert(i == pi.next())
+            assert(p.exists(i))
+
+    print outfilename
+
+optspec = """
+bup midx [options...] <idxnames...>
+--
+o,output=  output midx filename (default: auto-generated)
+a,auto     automatically create .midx from any unindexed .idx files
+f,force    automatically create .midx from *all* .idx files
+"""
+o = options.Options('bup midx', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if extra and (opt.auto or opt.force):
+    o.fatal("you can't use -f/-a and also provide filenames")
+
+git.check_repo_or_die()
+
+if extra:
+    do_midx(git.repo('objects/pack'), opt.output, extra)
+elif opt.auto or opt.force:
+    paths = [git.repo('objects/pack')]
+    paths += glob.glob(git.repo('index-cache/*/.'))
+    for path in paths:
+        log('midx: scanning %s\n' % path)
+        if opt.force:
+            do_midx(path, opt.output, glob.glob('%s/*.idx' % path))
+        elif opt.auto:
+            m = git.PackIdxList(path)
+            needed = {}
+            for pack in m.packs:  # only .idx files without a .midx are open
+                if pack.name.endswith('.idx'):
+                    needed[pack.name] = 1
+            del m
+            do_midx(path, opt.output, needed.keys())
+        log('\n')
+else:
+    o.fatal("you must use -f or -a or provide input filenames")
+#!/usr/bin/env python
+import sys, os, random
+from bup import options
+from bup.helpers import *
+
+
+def randblock(n):
+    l = []
+    for i in xrange(n):
+        l.append(chr(random.randrange(0,256)))
+    return ''.join(l)
+
+
+optspec = """
+bup damage [-n count] [-s maxsize] [-S seed] <filenames...>
+--
+   WARNING: THIS COMMAND IS EXTREMELY DANGEROUS
+n,num=   number of blocks to damage
+s,size=  maximum size of each damaged block
+percent= maximum size of each damaged block (as a percent of entire file)
+equal    spread damage evenly throughout the file
+S,seed=  random number seed (for repeatable tests)
+"""
+o = options.Options('bup damage', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if not extra:
+    o.fatal('filenames expected')
+
+if opt.seed != None:
+    random.seed(opt.seed)
+
+for name in extra:
+    log('Damaging "%s"...\n' % name)
+    f = open(name, 'r+b')
+    st = os.fstat(f.fileno())
+    size = st.st_size
+    if opt.percent or opt.size:
+        ms1 = int(float(opt.percent or 0)/100.0*size) or size
+        ms2 = opt.size or size
+        maxsize = min(ms1, ms2)
+    else:
+        maxsize = 1
+    chunks = opt.num or 10
+    chunksize = size/chunks
+    for r in range(chunks):
+        sz = random.randrange(1, maxsize+1)
+        if sz > size:
+            sz = size
+        if opt.equal:
+            ofs = r*chunksize
+        else:
+            ofs = random.randrange(0, size - sz + 1)
+        log('  %6d bytes at %d\n' % (sz, ofs))
+        f.seek(ofs)
+        f.write(randblock(sz))
+    f.close()
+#!/usr/bin/env python
+import sys, struct, mmap
+from bup import options, git
+from bup.helpers import *
+
+suspended_w = None
+
+
+def init_dir(conn, arg):
+    git.init_repo(arg)
+    log('bup server: bupdir initialized: %r\n' % git.repodir)
+    conn.ok()
+
+
+def set_dir(conn, arg):
+    git.check_repo_or_die(arg)
+    log('bup server: bupdir is %r\n' % git.repodir)
+    conn.ok()
 
-#
-# Function that stops the daemon/service
-#
-do_stop()
-{
-       # Return
-       #   0 if daemon has been stopped
-       #   1 if daemon was already stopped
-       #   2 if daemon could not be stopped
-       #   other if a failure occurred
-       start-stop-daemon --stop --quiet --retry=TERM/30/KILL/5 --pidfile $PIDFILE --name $NAME
-       RETVAL="$?"
-       [ "$RETVAL" = 2 ] && return 2
-       # Wait for children to finish too if this is a daemon that forks
-       # and if the daemon is only ever run from this initscript.
-       # If the above conditions are not satisfied then add some other code
-       # that waits for the process to drop all resources that could be
-       # needed by services started subsequently.  A last resort is to
-       # sleep for some time.
-       start-stop-daemon --stop --quiet --oknodo --retry=0/30/KILL/5 --exec $DAEMON
-       [ "$?" = 2 ] && return 2
-       # Many daemons don't delete their pidfiles when they exit.
-       rm -f $PIDFILE
-       return "$RETVAL"
+    
+def list_indexes(conn, junk):
+    git.check_repo_or_die()
+    for f in os.listdir(git.repo('objects/pack')):
+        if f.endswith('.idx'):
+            conn.write('%s\n' % f)
+    conn.ok()
+
+
+def send_index(conn, name):
+    git.check_repo_or_die()
+    assert(name.find('/') < 0)
+    assert(name.endswith('.idx'))
+    idx = git.PackIdx(git.repo('objects/pack/%s' % name))
+    conn.write(struct.pack('!I', len(idx.map)))
+    conn.write(idx.map)
+    conn.ok()
+
+
+def receive_objects(conn, junk):
+    global suspended_w
+    git.check_repo_or_die()
+    suggested = {}
+    if suspended_w:
+        w = suspended_w
+        suspended_w = None
+    else:
+        w = git.PackWriter()
+    while 1:
+        ns = conn.read(4)
+        if not ns:
+            w.abort()
+            raise Exception('object read: expected length header, got EOF\n')
+        n = struct.unpack('!I', ns)[0]
+        #log('expecting %d bytes\n' % n)
+        if not n:
+            log('bup server: received %d object%s.\n' 
+                % (w.count, w.count!=1 and "s" or ''))
+            fullpath = w.close()
+            if fullpath:
+                (dir, name) = os.path.split(fullpath)
+                conn.write('%s.idx\n' % name)
+            conn.ok()
+            return
+        elif n == 0xffffffff:
+            log('bup server: receive-objects suspended.\n')
+            suspended_w = w
+            conn.ok()
+            return
+            
+        buf = conn.read(n)  # object sizes in bup are reasonably small
+        #log('read %d bytes\n' % n)
+        if len(buf) < n:
+            w.abort()
+            raise Exception('object read: expected %d bytes, got %d\n'
+                            % (n, len(buf)))
+        (type, content) = git._decode_packobj(buf)
+        sha = git.calc_hash(type, content)
+        oldpack = w.exists(sha)
+        # FIXME: we only suggest a single index per cycle, because the client
+        # is currently dumb to download more than one per cycle anyway.
+        # Actually we should fix the client, but this is a minor optimization
+        # on the server side.
+        if not suggested and \
+          oldpack and (oldpack == True or oldpack.endswith('.midx')):
+            # FIXME: we shouldn't really have to know about midx files
+            # at this layer.  But exists() on a midx doesn't return the
+            # packname (since it doesn't know)... probably we should just
+            # fix that deficiency of midx files eventually, although it'll
+            # make the files bigger.  This method is certainly not very
+            # efficient.
+            w.objcache.refresh(skip_midx = True)
+            oldpack = w.objcache.exists(sha)
+            log('new suggestion: %r\n' % oldpack)
+            assert(oldpack)
+            assert(oldpack != True)
+            assert(not oldpack.endswith('.midx'))
+            w.objcache.refresh(skip_midx = False)
+        if not suggested and oldpack:
+            assert(oldpack.endswith('.idx'))
+            (dir,name) = os.path.split(oldpack)
+            if not (name in suggested):
+                log("bup server: suggesting index %s\n" % name)
+                conn.write('index %s\n' % name)
+                suggested[name] = 1
+        else:
+            w._raw_write([buf])
+    # NOTREACHED
+
+
+def read_ref(conn, refname):
+    git.check_repo_or_die()
+    r = git.read_ref(refname)
+    conn.write('%s\n' % (r or '').encode('hex'))
+    conn.ok()
+
+
+def update_ref(conn, refname):
+    git.check_repo_or_die()
+    newval = conn.readline().strip()
+    oldval = conn.readline().strip()
+    git.update_ref(refname, newval.decode('hex'), oldval.decode('hex'))
+    conn.ok()
+
+
+def cat(conn, id):
+    git.check_repo_or_die()
+    try:
+        for blob in git.cat(id):
+            conn.write(struct.pack('!I', len(blob)))
+            conn.write(blob)
+    except KeyError, e:
+        log('server: error: %s\n' % e)
+        conn.write('\0\0\0\0')
+        conn.error(e)
+    else:
+        conn.write('\0\0\0\0')
+        conn.ok()
+
+
+optspec = """
+bup server
+"""
+o = options.Options('bup server', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if extra:
+    o.fatal('no arguments expected')
+
+log('bup server: reading from stdin.\n')
+
+commands = {
+    'init-dir': init_dir,
+    'set-dir': set_dir,
+    'list-indexes': list_indexes,
+    'send-index': send_index,
+    'receive-objects': receive_objects,
+    'read-ref': read_ref,
+    'update-ref': update_ref,
+    'cat': cat,
 }
 
+# FIXME: this protocol is totally lame and not at all future-proof.
+# (Especially since we abort completely as soon as *anything* bad happens)
+conn = Conn(sys.stdin, sys.stdout)
+lr = linereader(conn)
+for _line in lr:
+    line = _line.strip()
+    if not line:
+        continue
+    log('bup server: command: %r\n' % line)
+    words = line.split(' ', 1)
+    cmd = words[0]
+    rest = len(words)>1 and words[1] or ''
+    if cmd == 'quit':
+        break
+    else:
+        cmd = commands.get(cmd)
+        if cmd:
+            cmd(conn, rest)
+        else:
+            raise Exception('unknown server command: %r\n' % line)
+
+log('bup server: done\n')
+#!/usr/bin/env python
+import sys, time, struct
+from bup import hashsplit, git, options, client
+from bup.helpers import *
+from subprocess import PIPE
+
+
+optspec = """
+bup join [-r host:path] [refs or hashes...]
+--
+r,remote=  remote repository path
+"""
+o = options.Options('bup join', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+git.check_repo_or_die()
+
+if not extra:
+    extra = linereader(sys.stdin)
+
+ret = 0
+
+if opt.remote:
+    cli = client.Client(opt.remote)
+    cat = cli.cat
+else:
+    cp = git.CatPipe()
+    cat = cp.join
+
+for id in extra:
+    try:
+        for blob in cat(id):
+            sys.stdout.write(blob)
+    except KeyError, e:
+        sys.stdout.flush()
+        log('error: %s\n' % e)
+        ret = 1
+
+sys.exit(ret)
+#!/usr/bin/env python
+import sys, re, errno, stat, time, math
+from bup import hashsplit, git, options, index, client
+from bup.helpers import *
+
+
+optspec = """
+bup save [-tc] [-n name] <filenames...>
+--
+r,remote=  remote repository path
+t,tree     output a tree id
+c,commit   output a commit id
+n,name=    name of backup set to update (if any)
+v,verbose  increase log output (can be used more than once)
+q,quiet    don't show progress meter
+smaller=   only back up files smaller than n bytes
+"""
+o = options.Options('bup save', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+git.check_repo_or_die()
+if not (opt.tree or opt.commit or opt.name):
+    o.fatal("use one or more of -t, -c, -n")
+if not extra:
+    o.fatal("no filenames given")
+
+opt.progress = (istty and not opt.quiet)
+opt.smaller = parse_num(opt.smaller or 0)
+
+is_reverse = os.environ.get('BUP_SERVER_REVERSE')
+if is_reverse and opt.remote:
+    o.fatal("don't use -r in reverse mode; it's automatic")
+
+refname = opt.name and 'refs/heads/%s' % opt.name or None
+if opt.remote or is_reverse:
+    cli = client.Client(opt.remote)
+    oldref = refname and cli.read_ref(refname) or None
+    w = cli.new_packwriter()
+else:
+    cli = None
+    oldref = refname and git.read_ref(refname) or None
+    w = git.PackWriter()
+
+handle_ctrl_c()
+
+
+def eatslash(dir):
+    if dir.endswith('/'):
+        return dir[:-1]
+    else:
+        return dir
+
+
+parts = ['']
+shalists = [[]]
+
+def _push(part):
+    assert(part)
+    parts.append(part)
+    shalists.append([])
+
+def _pop(force_tree):
+    assert(len(parts) >= 1)
+    part = parts.pop()
+    shalist = shalists.pop()
+    tree = force_tree or w.new_tree(shalist)
+    if shalists:
+        shalists[-1].append(('40000', part, tree))
+    else:  # this was the toplevel, so put it back for sanity
+        shalists.append(shalist)
+    return tree
+
+lastremain = None
+def progress_report(n):
+    global count, subcount, lastremain
+    subcount += n
+    cc = count + subcount
+    pct = total and (cc*100.0/total) or 0
+    now = time.time()
+    elapsed = now - tstart
+    kps = elapsed and int(cc/1024./elapsed)
+    kps_frac = 10 ** int(math.log(kps+1, 10) - 1)
+    kps = int(kps/kps_frac)*kps_frac
+    if cc:
+        remain = elapsed*1.0/cc * (total-cc)
+    else:
+        remain = 0.0
+    if (lastremain and (remain > lastremain)
+          and ((remain - lastremain)/lastremain < 0.05)):
+        remain = lastremain
+    else:
+        lastremain = remain
+    hours = int(remain/60/60)
+    mins = int(remain/60 - hours*60)
+    secs = int(remain - hours*60*60 - mins*60)
+    if elapsed < 30:
+        remainstr = ''
+        kpsstr = ''
+    else:
+        kpsstr = '%dk/s' % kps
+        if hours:
+            remainstr = '%dh%dm' % (hours, mins)
+        elif mins:
+            remainstr = '%dm%d' % (mins, secs)
+        else:
+            remainstr = '%ds' % secs
+    progress('Saving: %.2f%% (%d/%dk, %d/%d files) %s %s\r'
+             % (pct, cc/1024, total/1024, fcount, ftotal,
+                remainstr, kpsstr))
+
+
+r = index.Reader(git.repo('bupindex'))
+
+def already_saved(ent):
+    return ent.is_valid() and w.exists(ent.sha) and ent.sha
+
+def wantrecurse_pre(ent):
+    return not already_saved(ent)
+
+def wantrecurse_during(ent):
+    return not already_saved(ent) or ent.sha_missing()
+
+total = ftotal = 0
+if opt.progress:
+    for (transname,ent) in r.filter(extra, wantrecurse=wantrecurse_pre):
+        if not (ftotal % 10024):
+            progress('Reading index: %d\r' % ftotal)
+        exists = ent.exists()
+        hashvalid = already_saved(ent)
+        ent.set_sha_missing(not hashvalid)
+        if not opt.smaller or ent.size < opt.smaller:
+            if exists and not hashvalid:
+                total += ent.size
+        ftotal += 1
+    progress('Reading index: %d, done.\n' % ftotal)
+    hashsplit.progress_callback = progress_report
+
+tstart = time.time()
+count = subcount = fcount = 0
+lastskip_name = None
+lastdir = ''
+for (transname,ent) in r.filter(extra, wantrecurse=wantrecurse_during):
+    (dir, file) = os.path.split(ent.name)
+    exists = (ent.flags & index.IX_EXISTS)
+    hashvalid = already_saved(ent)
+    wasmissing = ent.sha_missing()
+    oldsize = ent.size
+    if opt.verbose:
+        if not exists:
+            status = 'D'
+        elif not hashvalid:
+            if ent.sha == index.EMPTY_SHA:
+                status = 'A'
+            else:
+                status = 'M'
+        else:
+            status = ' '
+        if opt.verbose >= 2:
+            log('%s %-70s\n' % (status, ent.name))
+        elif not stat.S_ISDIR(ent.mode) and lastdir != dir:
+            if not lastdir.startswith(dir):
+                log('%s %-70s\n' % (status, os.path.join(dir, '')))
+            lastdir = dir
+
+    if opt.progress:
+        progress_report(0)
+    fcount += 1
+    
+    if not exists:
+        continue
+    if opt.smaller and ent.size >= opt.smaller:
+        if exists and not hashvalid:
+            add_error('skipping large file "%s"' % ent.name)
+            lastskip_name = ent.name
+        continue
+
+    assert(dir.startswith('/'))
+    dirp = dir.split('/')
+    while parts > dirp:
+        _pop(force_tree = None)
+    if dir != '/':
+        for part in dirp[len(parts):]:
+            _push(part)
+
+    if not file:
+        # no filename portion means this is a subdir.  But
+        # sub/parentdirectories already handled in the pop/push() part above.
+        oldtree = already_saved(ent) # may be None
+        newtree = _pop(force_tree = oldtree)
+        if not oldtree:
+            if lastskip_name and lastskip_name.startswith(ent.name):
+                ent.invalidate()
+            else:
+                ent.validate(040000, newtree)
+            ent.repack()
+        if exists and wasmissing:
+            count += oldsize
+        continue
+
+    # it's not a directory
+    id = None
+    if hashvalid:
+        mode = '%o' % ent.gitmode
+        id = ent.sha
+        shalists[-1].append((mode, 
+                             git.mangle_name(file, ent.mode, ent.gitmode),
+                             id))
+    else:
+        if stat.S_ISREG(ent.mode):
+            try:
+                f = hashsplit.open_noatime(ent.name)
+            except IOError, e:
+                add_error(e)
+                lastskip_name = ent.name
+            except OSError, e:
+                add_error(e)
+                lastskip_name = ent.name
+            else:
+                (mode, id) = hashsplit.split_to_blob_or_tree(w, [f])
+        else:
+            if stat.S_ISDIR(ent.mode):
+                assert(0)  # handled above
+            elif stat.S_ISLNK(ent.mode):
+                try:
+                    rl = os.readlink(ent.name)
+                except OSError, e:
+                    add_error(e)
+                    lastskip_name = ent.name
+                except IOError, e:
+                    add_error(e)
+                    lastskip_name = ent.name
+                else:
+                    (mode, id) = ('120000', w.new_blob(rl))
+            else:
+                add_error(Exception('skipping special file "%s"' % ent.name))
+                lastskip_name = ent.name
+        if id:
+            ent.validate(int(mode, 8), id)
+            ent.repack()
+            shalists[-1].append((mode,
+                                 git.mangle_name(file, ent.mode, ent.gitmode),
+                                 id))
+    if exists and wasmissing:
+        count += oldsize
+        subcount = 0
+
+
+if opt.progress:
+    pct = total and count*100.0/total or 100
+    progress('Saving: %.2f%% (%d/%dk, %d/%d files), done.    \n'
+             % (pct, count/1024, total/1024, fcount, ftotal))
+
+while len(parts) > 1:
+    _pop(force_tree = None)
+assert(len(shalists) == 1)
+tree = w.new_tree(shalists[-1])
+if opt.tree:
+    print tree.encode('hex')
+if opt.commit or opt.name:
+    msg = 'bup save\n\nGenerated by command:\n%r' % sys.argv
+    ref = opt.name and ('refs/heads/%s' % opt.name) or None
+    commit = w.new_commit(oldref, tree, msg)
+    if opt.commit:
+        print commit.encode('hex')
+
+w.close()  # must close before we can update the ref
+        
+if opt.name:
+    if cli:
+        cli.update_ref(refname, commit, oldref)
+    else:
+        git.update_ref(refname, commit, oldref)
+
+if cli:
+    cli.close()
+
+if saved_errors:
+    log('WARNING: %d errors encountered while saving.\n' % len(saved_errors))
+    sys.exit(1)
+#!/usr/bin/env python
+import sys, time
+from bup import options
+
+optspec = """
+bup tick
+"""
+o = options.Options('bup tick', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if extra:
+    o.fatal("no arguments expected")
+
+t = time.time()
+tleft = 1 - (t - int(t))
+time.sleep(tleft)
+#!/usr/bin/env python
+import os, sys, stat, time
+from bup import options, git, index, drecurse
+from bup.helpers import *
+
+
+def merge_indexes(out, r1, r2):
+    for e in index.MergeIter([r1, r2]):
+        # FIXME: shouldn't we remove deleted entries eventually?  When?
+        out.add_ixentry(e)
+
+
+class IterHelper:
+    def __init__(self, l):
+        self.i = iter(l)
+        self.cur = None
+        self.next()
+
+    def next(self):
+        try:
+            self.cur = self.i.next()
+        except StopIteration:
+            self.cur = None
+        return self.cur
+
+
+def check_index(reader):
+    try:
+        log('check: checking forward iteration...\n')
+        e = None
+        d = {}
+        for e in reader.forward_iter():
+            if e.children_n:
+                if opt.verbose:
+                    log('%08x+%-4d %r\n' % (e.children_ofs, e.children_n,
+                                            e.name))
+                assert(e.children_ofs)
+                assert(e.name.endswith('/'))
+                assert(not d.get(e.children_ofs))
+                d[e.children_ofs] = 1
+            if e.flags & index.IX_HASHVALID:
+                assert(e.sha != index.EMPTY_SHA)
+                assert(e.gitmode)
+        assert(not e or e.name == '/')  # last entry is *always* /
+        log('check: checking normal iteration...\n')
+        last = None
+        for e in reader:
+            if last:
+                assert(last > e.name)
+            last = e.name
+    except:
+        log('index error! at %r\n' % e)
+        raise
+    log('check: passed.\n')
+
+
+def update_index(top):
+    ri = index.Reader(indexfile)
+    wi = index.Writer(indexfile)
+    rig = IterHelper(ri.iter(name=top))
+    tstart = int(time.time())
+
+    hashgen = None
+    if opt.fake_valid:
+        def hashgen(name):
+            return (0100644, index.FAKE_SHA)
+
+    total = 0
+    for (path,pst) in drecurse.recursive_dirlist([top], xdev=opt.xdev):
+        if opt.verbose>=2 or (opt.verbose==1 and stat.S_ISDIR(pst.st_mode)):
+            sys.stdout.write('%s\n' % path)
+            sys.stdout.flush()
+            progress('Indexing: %d\r' % total)
+        elif not (total % 128):
+            progress('Indexing: %d\r' % total)
+        total += 1
+        while rig.cur and rig.cur.name > path:  # deleted paths
+            if rig.cur.exists():
+                rig.cur.set_deleted()
+                rig.cur.repack()
+            rig.next()
+        if rig.cur and rig.cur.name == path:    # paths that already existed
+            if pst:
+                rig.cur.from_stat(pst, tstart)
+            if not (rig.cur.flags & index.IX_HASHVALID):
+                if hashgen:
+                    (rig.cur.gitmode, rig.cur.sha) = hashgen(path)
+                    rig.cur.flags |= index.IX_HASHVALID
+            if opt.fake_invalid:
+                rig.cur.invalidate()
+            rig.cur.repack()
+            rig.next()
+        else:  # new paths
+            wi.add(path, pst, hashgen = hashgen)
+    progress('Indexing: %d, done.\n' % total)
+    
+    if ri.exists():
+        ri.save()
+        wi.flush()
+        if wi.count:
+            wr = wi.new_reader()
+            if opt.check:
+                log('check: before merging: oldfile\n')
+                check_index(ri)
+                log('check: before merging: newfile\n')
+                check_index(wr)
+            mi = index.Writer(indexfile)
+            merge_indexes(mi, ri, wr)
+            ri.close()
+            mi.close()
+            wr.close()
+        wi.abort()
+    else:
+        wi.close()
+
+
+optspec = """
+bup index <-p|m|u> [options...] <filenames...>
+--
+p,print    print the index entries for the given names (also works with -u)
+m,modified print only added/deleted/modified files (implies -p)
+s,status   print each filename with a status char (A/M/D) (implies -p)
+H,hash     print the hash for each object next to its name (implies -p)
+l,long     print more information about each file
+u,update   (recursively) update the index entries for the given filenames
+x,xdev,one-file-system  don't cross filesystem boundaries
+fake-valid mark all index entries as up-to-date even if they aren't
+fake-invalid mark all index entries as invalid
+check      carefully check index file integrity
+f,indexfile=  the name of the index file (default 'index')
+v,verbose  increase log output (can be used more than once)
+"""
+o = options.Options('bup index', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if not (opt.modified or opt['print'] or opt.status or opt.update or opt.check):
+    o.fatal('supply one or more of -p, -s, -m, -u, or --check')
+if (opt.fake_valid or opt.fake_invalid) and not opt.update:
+    o.fatal('--fake-{in,}valid are meaningless without -u')
+if opt.fake_valid and opt.fake_invalid:
+    o.fatal('--fake-valid is incompatible with --fake-invalid')
+
+git.check_repo_or_die()
+indexfile = opt.indexfile or git.repo('bupindex')
+
+handle_ctrl_c()
+
+if opt.check:
+    log('check: starting initial check.\n')
+    check_index(index.Reader(indexfile))
+
+paths = index.reduce_paths(extra)
+
+if opt.update:
+    if not paths:
+        o.fatal('update (-u) requested but no paths given')
+    for (rp,path) in paths:
+        update_index(rp)
+
+if opt['print'] or opt.status or opt.modified:
+    for (name, ent) in index.Reader(indexfile).filter(extra or ['']):
+        if (opt.modified 
+            and (ent.is_valid() or ent.is_deleted() or not ent.mode)):
+            continue
+        line = ''
+        if opt.status:
+            if ent.is_deleted():
+                line += 'D '
+            elif not ent.is_valid():
+                if ent.sha == index.EMPTY_SHA:
+                    line += 'A '
+                else:
+                    line += 'M '
+            else:
+                line += '  '
+        if opt.hash:
+            line += ent.sha.encode('hex') + ' '
+        if opt.long:
+            line += "%7s %7s " % (oct(ent.mode), oct(ent.gitmode))
+        print line + (name or './')
+
+if opt.check and (opt['print'] or opt.status or opt.modified or opt.update):
+    log('check: starting final check.\n')
+    check_index(index.Reader(indexfile))
+
+if saved_errors:
+    log('WARNING: %d errors encountered.\n' % len(saved_errors))
+    sys.exit(1)
+#!/usr/bin/env python
+import sys, os, struct
+from bup import options, helpers
+
+optspec = """
+bup rbackup-server
+--
+    This command is not intended to be run manually.
+"""
+o = options.Options('bup rbackup-server', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+if extra:
+    o.fatal('no arguments expected')
+
+# get the subcommand's argv.
+# Normally we could just pass this on the command line, but since we'll often
+# be getting called on the other end of an ssh pipe, which tends to mangle
+# argv (by sending it via the shell), this way is much safer.
+buf = sys.stdin.read(4)
+sz = struct.unpack('!I', buf)[0]
+assert(sz > 0)
+assert(sz < 1000000)
+buf = sys.stdin.read(sz)
+assert(len(buf) == sz)
+argv = buf.split('\0')
+
+# stdin/stdout are supposedly connected to 'bup server' that the caller
+# started for us (often on the other end of an ssh tunnel), so we don't want
+# to misuse them.  Move them out of the way, then replace stdout with
+# a pointer to stderr in case our subcommand wants to do something with it.
 #
-# Function that sends a SIGHUP to the daemon/service
+# It might be nice to do the same with stdin, but my experiments showed that
+# ssh seems to make its child's stderr a readable-but-never-reads-anything
+# socket.  They really should have used shutdown(SHUT_WR) on the other end
+# of it, but probably didn't.  Anyway, it's too messy, so let's just make sure
+# anyone reading from stdin is disappointed.
 #
-do_reload() {
-       #
-       # If the daemon can reload its configuration without
-       # restarting (for example, when it is sent a SIGHUP),
-       # then implement that here.
-       #
-       start-stop-daemon --stop --signal 1 --quiet --pidfile $PIDFILE --name $NAME
-       return 0
-}
-
-case "$1" in
-  start)
-       [ "$VERBOSE" != no ] && log_daemon_msg "Starting $DESC" "$NAME"
-       do_start
-       case "$?" in
-               0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
-               2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
-       esac
-       ;;
-  stop)
-       [ "$VERBOSE" != no ] && log_daemon_msg "Stopping $DESC" "$NAME"
-       do_stop
-       case "$?" in
-               0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
-               2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
-       esac
-       ;;
-  #reload|force-reload)
-       #
-       # If do_reload() is not implemented then leave this commented out
-       # and leave 'force-reload' as an alias for 'restart'.
-       #
-       #log_daemon_msg "Reloading $DESC" "$NAME"
-       #do_reload
-       #log_end_msg $?
-       #;;
-  restart|force-reload)
-       #
-       # If the "reload" option is implemented then remove the
-       # 'force-reload' alias
-       #
-       log_daemon_msg "Restarting $DESC" "$NAME"
-       do_stop
-       case "$?" in
-         0|1)
-               do_start
-               case "$?" in
-                       0) log_end_msg 0 ;;
-                       1) log_end_msg 1 ;; # Old process is still running
-                       *) log_end_msg 1 ;; # Failed to start
-               esac
-               ;;
-         *)
-               # Failed to stop
-               log_end_msg 1
-               ;;
-       esac
-       ;;
-  *)
-       #echo "Usage: $SCRIPTNAME {start|stop|restart|reload|force-reload}" >&2
-       echo "Usage: $SCRIPTNAME {start|stop|restart|force-reload}" >&2
-       exit 3
-       ;;
-esac
-
-:
-#! /bin/sh
-
-### BEGIN INIT INFO
-# Provides:            sshd
-# Required-Start:      $network $local_fs $remote_fs
-# Required-Stop:
-# Default-Start:       2 3 4 5
-# Default-Stop:                0 1 6
-# Short-Description:   OpenBSD Secure Shell server
-### END INIT INFO
-
-set -e
-
-# /etc/init.d/ssh: start and stop the OpenBSD "secure shell(tm)" daemon
-
-test -x /usr/sbin/sshd || exit 0
-( /usr/sbin/sshd -\? 2>&1 | grep -q OpenSSH ) 2>/dev/null || exit 0
-
-SSHD_OOM_ADJUST=-17
-if test -f /etc/default/ssh; then
-    . /etc/default/ssh
-fi
-
-. /lib/lsb/init-functions
-
-if [ -n "$2" ]; then
-    SSHD_OPTS="$SSHD_OPTS $2"
-fi
-
-# Are we running from init?
-run_by_init() {
-    ([ "$previous" ] && [ "$runlevel" ]) || [ "$runlevel" = S ]
-}
-
-check_for_no_start() {
-    # forget it if we're trying to start, and /etc/ssh/sshd_not_to_be_run exists
-    if [ -e /etc/ssh/sshd_not_to_be_run ]; then 
-       if [ "$1" = log_end_msg ]; then
-           log_end_msg 0
-       fi
-       if ! run_by_init; then
-           log_action_msg "OpenBSD Secure Shell server not in use (/etc/ssh/sshd_not_to_be_run)"
-       fi
-       exit 0
-    fi
-}
-
-check_dev_null() {
-    if [ ! -c /dev/null ]; then
-       if [ "$1" = log_end_msg ]; then
-           log_end_msg 1 || true
-       fi
-       if ! run_by_init; then
-           log_action_msg "/dev/null is not a character device!"
-       fi
-       exit 1
-    fi
-}
-
-check_privsep_dir() {
-    # Create the PrivSep empty dir if necessary
-    if [ ! -d /var/run/sshd ]; then
-       mkdir /var/run/sshd
-       chmod 0755 /var/run/sshd
-    fi
-}
-
-check_config() {
-    if [ ! -e /etc/ssh/sshd_not_to_be_run ]; then
-       /usr/sbin/sshd -t || exit 1
-    fi
-}
+# (You can't just leave stdin/stdout "not open" by closing the file
+# descriptors.  Then the next file that opens is automatically assigned 0 or 1,
+# and people *trying* to read/write stdin/stdout get screwed.)
+os.dup2(0, 3)
+os.dup2(1, 4)
+os.dup2(2, 1)
+fd = os.open('/dev/null', os.O_RDONLY)
+os.dup2(fd, 0)
+os.close(fd)
+
+os.environ['BUP_SERVER_REVERSE'] = helpers.hostname()
+os.execvp(argv[0], argv)
+sys.exit(99)
+#!/usr/bin/env python
+import sys, os, glob, subprocess, time
+from bup import options, git
+from bup.helpers import *
+
+par2_ok = 0
+nullf = open('/dev/null')
+
+def debug(s):
+    if opt.verbose:
+        log(s)
+
+def run(argv):
+    # at least in python 2.5, using "stdout=2" or "stdout=sys.stderr" below
+    # doesn't actually work, because subprocess closes fd #2 right before
+    # execing for some reason.  So we work around it by duplicating the fd
+    # first.
+    fd = os.dup(2)  # copy stderr
+    try:
+        p = subprocess.Popen(argv, stdout=fd, close_fds=False)
+        return p.wait()
+    finally:
+        os.close(fd)
+
+def par2_setup():
+    global par2_ok
+    rv = 1
+    try:
+        p = subprocess.Popen(['par2', '--help'],
+                             stdout=nullf, stderr=nullf, stdin=nullf)
+        rv = p.wait()
+    except OSError:
+        log('fsck: warning: par2 not found; disabling recovery features.\n')
+    else:
+        par2_ok = 1
+
+def parv(lvl):
+    if opt.verbose >= lvl:
+        if istty:
+            return []
+        else:
+            return ['-q']
+    else:
+        return ['-qq']
+
+def par2_generate(base):
+    return run(['par2', 'create', '-n1', '-c200'] + parv(2)
+               + ['--', base, base+'.pack', base+'.idx'])
+
+def par2_verify(base):
+    return run(['par2', 'verify'] + parv(3) + ['--', base])
+
+def par2_repair(base):
+    return run(['par2', 'repair'] + parv(2) + ['--', base])
+
+def quick_verify(base):
+    f = open(base + '.pack', 'rb')
+    f.seek(-20, 2)
+    wantsum = f.read(20)
+    assert(len(wantsum) == 20)
+    f.seek(0)
+    sum = Sha1()
+    for b in chunkyreader(f, os.fstat(f.fileno()).st_size - 20):
+        sum.update(b)
+    if sum.digest() != wantsum:
+        raise ValueError('expected %r, got %r' % (wantsum.encode('hex'),
+                                                  sum.hexdigest()))
+        
 
-adjust_oom() {
-    if [ -e /var/run/sshd.pid ]; then
-       PID="$(head -n1 /var/run/sshd.pid)"
-       if [ -e "/proc/$PID/oom_adj" ]; then
-           printf '%s' "$SSHD_OOM_ADJUST" >"/proc/$PID/oom_adj" || true
-       fi
-    fi
-}
+def git_verify(base):
+    if opt.quick:
+        try:
+            quick_verify(base)
+        except Exception, e:
+            debug('error: %s\n' % e)
+            return 1
+        return 0
+    else:
+        return run(['git', 'verify-pack', '--', base])
+    
+    
+def do_pack(base, last):
+    code = 0
+    if par2_ok and par2_exists and (opt.repair or not opt.generate):
+        vresult = par2_verify(base)
+        if vresult != 0:
+            if opt.repair:
+                rresult = par2_repair(base)
+                if rresult != 0:
+                    print '%s par2 repair: failed (%d)' % (last, rresult)
+                    code = rresult
+                else:
+                    print '%s par2 repair: succeeded (0)' % last
+                    code = 100
+            else:
+                print '%s par2 verify: failed (%d)' % (last, vresult)
+                code = vresult
+        else:
+            print '%s ok' % last
+    elif not opt.generate or (par2_ok and not par2_exists):
+        gresult = git_verify(base)
+        if gresult != 0:
+            print '%s git verify: failed (%d)' % (last, gresult)
+            code = gresult
+        else:
+            if par2_ok and opt.generate:
+                presult = par2_generate(base)
+                if presult != 0:
+                    print '%s par2 create: failed (%d)' % (last, presult)
+                    code = presult
+                else:
+                    print '%s ok' % last
+            else:
+                print '%s ok' % last
+    else:
+        assert(opt.generate and (not par2_ok or par2_exists))
+        debug('    skipped: par2 file already generated.\n')
+    return code
+
+
+optspec = """
+bup fsck [options...] [filenames...]
+--
+r,repair    attempt to repair errors using par2 (dangerous!)
+g,generate  generate auto-repair information using par2
+v,verbose   increase verbosity (can be used more than once)
+quick       just check pack sha1sum, don't use git verify-pack
+j,jobs=     run 'n' jobs in parallel
+par2-ok     immediately return 0 if par2 is ok, 1 if not
+disable-par2  ignore par2 even if it is available
+"""
+o = options.Options('bup fsck', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+par2_setup()
+if opt.par2_ok:
+    if par2_ok:
+        sys.exit(0)  # 'true' in sh
+    else:
+        sys.exit(1)
+if opt.disable_par2:
+    par2_ok = 0
+
+git.check_repo_or_die()
+
+if not extra:
+    debug('fsck: No filenames given: checking all packs.\n')
+    extra = glob.glob(git.repo('objects/pack/*.pack'))
+
+code = 0
+count = 0
+outstanding = {}
+for name in extra:
+    if name.endswith('.pack'):
+        base = name[:-5]
+    elif name.endswith('.idx'):
+        base = name[:-4]
+    elif name.endswith('.par2'):
+        base = name[:-5]
+    elif os.path.exists(name + '.pack'):
+        base = name
+    else:
+        raise Exception('%s is not a pack file!' % name)
+    (dir,last) = os.path.split(base)
+    par2_exists = os.path.exists(base + '.par2')
+    if par2_exists and os.stat(base + '.par2').st_size == 0:
+        par2_exists = 0
+    sys.stdout.flush()
+    debug('fsck: checking %s (%s)\n' 
+          % (last, par2_ok and par2_exists and 'par2' or 'git'))
+    if not opt.verbose:
+        progress('fsck (%d/%d)\r' % (count, len(extra)))
+    
+    if not opt.jobs:
+        nc = do_pack(base, last)
+        code = code or nc
+        count += 1
+    else:
+        while len(outstanding) >= opt.jobs:
+            (pid,nc) = os.wait()
+            nc >>= 8
+            if pid in outstanding:
+                del outstanding[pid]
+                code = code or nc
+                count += 1
+        pid = os.fork()
+        if pid:  # parent
+            outstanding[pid] = 1
+        else: # child
+            try:
+                sys.exit(do_pack(base, last))
+            except Exception, e:
+                log('exception: %r\n' % e)
+                sys.exit(99)
+                
+while len(outstanding):
+    (pid,nc) = os.wait()
+    nc >>= 8
+    if pid in outstanding:
+        del outstanding[pid]
+        code = code or nc
+        count += 1
+    if not opt.verbose:
+        progress('fsck (%d/%d)\r' % (count, len(extra)))
+
+if not opt.verbose and istty:
+    log('fsck done.           \n')
+sys.exit(code)
+#!/usr/bin/env python
+import sys, os, struct, getopt, subprocess, signal
+from bup import options, ssh
+from bup.helpers import *
+
+optspec = """
+bup rbackup <hostname> index ...
+bup rbackup <hostname> save ...
+bup rbackup <hostname> split ...
+"""
+o = options.Options('bup rbackup', optspec, optfunc=getopt.getopt)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+if len(extra) < 2:
+    o.fatal('arguments expected')
+
+class SigException(Exception):
+    def __init__(self, signum):
+        self.signum = signum
+        Exception.__init__(self, 'signal %d received' % signum)
+def handler(signum, frame):
+    raise SigException(signum)
+
+signal.signal(signal.SIGTERM, handler)
+signal.signal(signal.SIGINT, handler)
+
+sp = None
+p = None
+ret = 99
+
+try:
+    hostname = extra[0]
+    argv = extra[1:]
+    p = ssh.connect(hostname, 'rbackup-server')
+
+    argvs = '\0'.join(['bup'] + argv)
+    p.stdin.write(struct.pack('!I', len(argvs)) + argvs)
+    p.stdin.flush()
+
+    main_exe = os.environ.get('BUP_MAIN_EXE') or sys.argv[0]
+    sp = subprocess.Popen([main_exe, 'server'], stdin=p.stdout, stdout=p.stdin)
+
+    p.stdin.close()
+    p.stdout.close()
+
+finally:
+    while 1:
+        # if we get a signal while waiting, we have to keep waiting, just
+        # in case our child doesn't die.
+        try:
+            ret = p.wait()
+            sp.wait()
+            break
+        except SigException, e:
+            log('\nbup rbackup: %s\n' % e)
+            os.kill(p.pid, e.signum)
+            ret = 84
+sys.exit(ret)
+#!/usr/bin/env python
+import sys, os, re
+from bup import options
+
+optspec = """
+bup newliner
+"""
+o = options.Options('bup newliner', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if extra:
+    o.fatal("no arguments expected")
+
+r = re.compile(r'([\r\n])')
+lastlen = 0
+all = ''
+while 1:
+    l = r.split(all, 1)
+    if len(l) <= 1:
+        try:
+            b = os.read(sys.stdin.fileno(), 4096)
+        except KeyboardInterrupt:
+            break
+        if not b:
+            break
+        all += b
+    else:
+        assert(len(l) == 3)
+        (line, splitchar, all) = l
+        #splitchar = '\n'
+        sys.stdout.write('%-*s%s' % (lastlen, line, splitchar))
+        if splitchar == '\r':
+            lastlen = len(line)
+        else:
+            lastlen = 0
+        sys.stdout.flush()
+
+if lastlen or all:
+    sys.stdout.write('%-*s\n' % (lastlen, all))
+#!/usr/bin/env python
+import sys
+from bup import options, git, _hashsplit
+from bup.helpers import *
+
+
+optspec = """
+bup margin
+"""
+o = options.Options('bup margin', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if extra:
+    o.fatal("no arguments expected")
+
+git.check_repo_or_die()
+#git.ignore_midx = 1
+
+mi = git.PackIdxList(git.repo('objects/pack'))
+last = '\0'*20
+longmatch = 0
+for i in mi:
+    if i == last:
+        continue
+    #assert(str(i) >= last)
+    pm = _hashsplit.bitmatch(last, i)
+    longmatch = max(longmatch, pm)
+    last = i
+print longmatch
+#!/usr/bin/env python
+from bup import options, drecurse
+from bup.helpers import *
+
+optspec = """
+bup drecurse <path>
+--
+x,xdev,one-file-system   don't cross filesystem boundaries
+q,quiet  don't actually print filenames
+profile  run under the python profiler
+"""
+o = options.Options('bup drecurse', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if len(extra) != 1:
+    o.fatal("exactly one filename expected")
+
+it = drecurse.recursive_dirlist(extra, opt.xdev)
+if opt.profile:
+    import cProfile
+    def do_it():
+        for i in it:
+            pass
+    cProfile.run('do_it()')
+else:
+    if opt.quiet:
+        for i in it:
+            pass
+    else:
+        for (name,st) in it:
+            print name
+
+if saved_errors:
+    log('WARNING: %d errors encountered.\n' % len(saved_errors))
+    sys.exit(1)
+#!/usr/bin/env python
+import sys, time, struct
+from bup import hashsplit, git, options, client
+from bup.helpers import *
+from subprocess import PIPE
+
+
+optspec = """
+bup split [-tcb] [-n name] [--bench] [filenames...]
+--
+r,remote=  remote repository path
+b,blobs    output a series of blob ids
+t,tree     output a tree id
+c,commit   output a commit id
+n,name=    name of backup set to update (if any)
+N,noop     don't actually save the data anywhere
+q,quiet    don't print progress messages
+v,verbose  increase log output (can be used more than once)
+copy       just copy input to output, hashsplitting along the way
+bench      print benchmark timings to stderr
+max-pack-size=  maximum bytes in a single pack
+max-pack-objects=  maximum number of objects in a single pack
+fanout=  maximum number of blobs in a single tree
+"""
+o = options.Options('bup split', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+git.check_repo_or_die()
+if not (opt.blobs or opt.tree or opt.commit or opt.name or
+        opt.noop or opt.copy):
+    o.fatal("use one or more of -b, -t, -c, -n, -N, --copy")
+if (opt.noop or opt.copy) and (opt.blobs or opt.tree or 
+                               opt.commit or opt.name):
+    o.fatal('-N is incompatible with -b, -t, -c, -n')
+
+if opt.verbose >= 2:
+    git.verbose = opt.verbose - 1
+    opt.bench = 1
+if opt.max_pack_size:
+    hashsplit.max_pack_size = parse_num(opt.max_pack_size)
+if opt.max_pack_objects:
+    hashsplit.max_pack_objects = parse_num(opt.max_pack_objects)
+if opt.fanout:
+    hashsplit.fanout = parse_num(opt.fanout)
+if opt.blobs:
+    hashsplit.fanout = 0
+
+is_reverse = os.environ.get('BUP_SERVER_REVERSE')
+if is_reverse and opt.remote:
+    o.fatal("don't use -r in reverse mode; it's automatic")
+start_time = time.time()
+
+refname = opt.name and 'refs/heads/%s' % opt.name or None
+if opt.noop or opt.copy:
+    cli = w = oldref = None
+elif opt.remote or is_reverse:
+    cli = client.Client(opt.remote)
+    oldref = refname and cli.read_ref(refname) or None
+    w = cli.new_packwriter()
+else:
+    cli = None
+    oldref = refname and git.read_ref(refname) or None
+    w = git.PackWriter()
+
+files = extra and (open(fn) for fn in extra) or [sys.stdin]
+if w:
+    shalist = hashsplit.split_to_shalist(w, files)
+    tree = w.new_tree(shalist)
+else:
+    last = 0
+    for (blob, bits) in hashsplit.hashsplit_iter(files):
+        hashsplit.total_split += len(blob)
+        if opt.copy:
+            sys.stdout.write(str(blob))
+        megs = hashsplit.total_split/1024/1024
+        if not opt.quiet and last != megs:
+            progress('%d Mbytes read\r' % megs)
+            last = megs
+    progress('%d Mbytes read, done.\n' % megs)
+
+if opt.verbose:
+    log('\n')
+if opt.blobs:
+    for (mode,name,bin) in shalist:
+        print bin.encode('hex')
+if opt.tree:
+    print tree.encode('hex')
+if opt.commit or opt.name:
+    msg = 'bup split\n\nGenerated by command:\n%r' % sys.argv
+    ref = opt.name and ('refs/heads/%s' % opt.name) or None
+    commit = w.new_commit(oldref, tree, msg)
+    if opt.commit:
+        print commit.encode('hex')
+
+if w:
+    w.close()  # must close before we can update the ref
+        
+if opt.name:
+    if cli:
+        cli.update_ref(refname, commit, oldref)
+    else:
+        git.update_ref(refname, commit, oldref)
+
+if cli:
+    cli.close()
+
+secs = time.time() - start_time
+size = hashsplit.total_split
+if opt.bench:
+    log('\nbup: %.2fkbytes in %.2f secs = %.2f kbytes/sec\n'
+        % (size/1024., secs, size/1024./secs))
+#!/usr/bin/env python
+import sys, re, struct, mmap
+from bup import git, options
+from bup.helpers import *
+
+
+def s_from_bytes(bytes):
+    clist = [chr(b) for b in bytes]
+    return ''.join(clist)
+
+
+def report(count):
+    fields = ['VmSize', 'VmRSS', 'VmData', 'VmStk']
+    d = {}
+    for line in open('/proc/self/status').readlines():
+        l = re.split(r':\s*', line.strip(), 1)
+        d[l[0]] = l[1]
+    if count >= 0:
+        e1 = count
+        fields = [d[k] for k in fields]
+    else:
+        e1 = ''
+    print ('%9s  ' + ('%10s ' * len(fields))) % tuple([e1] + fields)
+    sys.stdout.flush()
+
+
+optspec = """
+bup memtest [-n elements] [-c cycles]
+--
+n,number=  number of objects per cycle
+c,cycles=  number of cycles to run
+ignore-midx  ignore .midx files, use only .idx files
+"""
+o = options.Options('bup memtest', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if extra:
+    o.fatal('no arguments expected')
+
+git.ignore_midx = opt.ignore_midx
+
+git.check_repo_or_die()
+m = git.PackIdxList(git.repo('objects/pack'))
+
+cycles = opt.cycles or 100
+number = opt.number or 10000
+
+report(-1)
+f = open('/dev/urandom')
+a = mmap.mmap(-1, 20)
+report(0)
+for c in xrange(cycles):
+    for n in xrange(number):
+        b = f.read(3)
+        if 0:
+            bytes = list(struct.unpack('!BBB', b)) + [0]*17
+            bytes[2] &= 0xf0
+            bin = struct.pack('!20s', s_from_bytes(bytes))
+        else:
+            a[0:2] = b[0:2]
+            a[2] = chr(ord(b[2]) & 0xf0)
+            bin = str(a[0:20])
+        #print bin.encode('hex')
+        m.exists(bin)
+    report((c+1)*number)
+#!/usr/bin/env python
+import sys, os, stat
+from bup import options, git, vfs
+from bup.helpers import *
+
+def print_node(text, n):
+    prefix = ''
+    if opt.hash:
+        prefix += "%s " % n.hash.encode('hex')
+    if stat.S_ISDIR(n.mode):
+        print '%s%s/' % (prefix, text)
+    elif stat.S_ISLNK(n.mode):
+        print '%s%s@' % (prefix, text)
+    else:
+        print '%s%s' % (prefix, text)
+
+
+optspec = """
+bup ls <dirs...>
+--
+s,hash   show hash for each file
+"""
+o = options.Options('bup ls', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+git.check_repo_or_die()
+top = vfs.RefList(None)
+
+if not extra:
+    extra = ['/']
+
+ret = 0
+for d in extra:
+    try:
+        n = top.lresolve(d)
+        if stat.S_ISDIR(n.mode):
+            for sub in n:
+                print_node(sub.name, sub)
+        else:
+            print_node(d, n)
+    except vfs.NodeError, e:
+        log('error: %s\n' % e)
+        ret = 1
+
+sys.exit(ret)
+#!/usr/bin/env python
+import sys, os, re, stat, readline, fnmatch
+from bup import options, git, shquote, vfs
+from bup.helpers import *
+
+def node_name(text, n):
+    if stat.S_ISDIR(n.mode):
+        return '%s/' % text
+    elif stat.S_ISLNK(n.mode):
+        return '%s@' % text
+    else:
+        return '%s' % text
+
+
+def do_ls(path, n):
+    l = []
+    if stat.S_ISDIR(n.mode):
+        for sub in n:
+            l.append(node_name(sub.name, sub))
+    else:
+        l.append(node_name(path, n))
+    print columnate(l, '')
+    
 
-export PATH="${PATH:+$PATH:}/usr/sbin:/sbin"
-
-case "$1" in
-  start)
-       check_privsep_dir
-       check_for_no_start
-       check_dev_null
-       log_daemon_msg "Starting OpenBSD Secure Shell server" "sshd"
-       if start-stop-daemon --start --quiet --oknodo --pidfile /var/run/sshd.pid --exec /usr/sbin/sshd -- $SSHD_OPTS; then
-           log_end_msg 0
-           adjust_oom
-       else
-           log_end_msg 1
-       fi
-       ;;
-  stop)
-       log_daemon_msg "Stopping OpenBSD Secure Shell server" "sshd"
-       if start-stop-daemon --stop --quiet --oknodo --pidfile /var/run/sshd.pid; then
-           log_end_msg 0
-       else
-           log_end_msg 1
-       fi
-       ;;
-
-  reload|force-reload)
-       check_for_no_start
-       check_config
-       log_daemon_msg "Reloading OpenBSD Secure Shell server's configuration" "sshd"
-       if start-stop-daemon --stop --signal 1 --quiet --oknodo --pidfile /var/run/sshd.pid --exec /usr/sbin/sshd; then
-           log_end_msg 0
-       else
-           log_end_msg 1
-       fi
-       ;;
-
-  restart)
-       check_privsep_dir
-       check_config
-       log_daemon_msg "Restarting OpenBSD Secure Shell server" "sshd"
-       start-stop-daemon --stop --quiet --oknodo --retry 30 --pidfile /var/run/sshd.pid
-       check_for_no_start log_end_msg
-       check_dev_null log_end_msg
-       if start-stop-daemon --start --quiet --oknodo --pidfile /var/run/sshd.pid --exec /usr/sbin/sshd -- $SSHD_OPTS; then
-           log_end_msg 0
-           adjust_oom
-       else
-           log_end_msg 1
-       fi
-       ;;
-
-  try-restart)
-       check_privsep_dir
-       check_config
-       log_daemon_msg "Restarting OpenBSD Secure Shell server" "sshd"
-       set +e
-       start-stop-daemon --stop --quiet --retry 30 --pidfile /var/run/sshd.pid
-       RET="$?"
-       set -e
-       case $RET in
-           0)
-               # old daemon stopped
-               check_for_no_start log_end_msg
-               check_dev_null log_end_msg
-               if start-stop-daemon --start --quiet --oknodo --pidfile /var/run/sshd.pid --exec /usr/sbin/sshd -- $SSHD_OPTS; then
-                   log_end_msg 0
-               else
-                   log_end_msg 1
-               fi
-               ;;
-           1)
-               # daemon not running
-               log_progress_msg "(not running)"
-               log_end_msg 0
-               ;;
-           *)
-               # failed to stop
-               log_progress_msg "(failed to stop)"
-               log_end_msg 1
-               ;;
-       esac
-       ;;
-
-  *)
-       log_action_msg "Usage: /etc/init.d/ssh {start|stop|reload|force-reload|restart|try-restart}"
-       exit 1
-esac
-
-exit 0
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          stop-bootlogd
-# Required-Start:    $remote_fs
-# Required-Stop:
-# Default-Start:     1 2 3 4 5
-# Default-Stop:
-# Short-Description: Stop bootlogd
-# Description:       See the bootlogd script
-### END INIT INFO
-
-NAME=stop-bootlogd
-DAEMON=/sbin/bootlogd
-
-[ -x "$DAEMON" ] || exit 0
-
-case "$1" in
-  start)
-       /etc/init.d/bootlogd stop
-       ;;
-  stop|restart|force-reload)
-       # No-op
-       ;;
-  *)
-       echo "Usage: $NAME {start|stop|restart|force-reload}" >&2
-       exit 3
-       ;;
-esac
-
-:
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          stop-bootlogd-single
-# Required-Start:    $remote_fs
-# Required-Stop:
-# Default-Start:     S
-# Default-Stop:
-# Short-Description: Stop bootlogd in single user mode
-# Description:       See the bootlogd script
-### END INIT INFO
-
-PATH=/usr/sbin:/usr/bin:/sbin:/bin
-NAME=stop-bootlogd-single
-DAEMON=/sbin/bootlogd
-
-[ -x "$DAEMON" ] || exit 0
-
-case "$1" in
-  start)
-       if [ ! -e /proc/cmdline ] || grep -q '\<single\>' /proc/cmdline
-       then
-               /etc/init.d/bootlogd stop
-       fi
-       ;;
-  stop|restart|force-reload)
-       # No-op
-       ;;
-  *)
-       echo "Usage: $NAME {start|stop|restart|force-reload}" >&2
-       exit 3
-       ;;
-esac
-
-:
-#! /bin/sh
-# /etc/init.d/sysklogd: start the system log daemon.
-
-### BEGIN INIT INFO
-# Provides:             syslog
-# Required-Start:       $local_fs $time
-# Required-Stop:        $local_fs $time
-# Should-Start:         $network $named
-# Should-Stop:          $network $named
-# Default-Start:        S 1 2 3 4 5
-# Default-Stop:         0 6
-# Short-Description:    System logger
-### END INIT INFO
-
-PATH=/bin:/usr/bin:/sbin:/usr/sbin
-
-pidfile=/var/run/syslogd.pid
-binpath=/sbin/syslogd
-
-test -x $binpath || exit 0
-
-# syslogd options should be set in /etc/default/syslogd
-SYSLOGD=""
-
-# user to run syslogd as - this can overriden in /etc/default/syslogd
-USER="syslog"
-
-test ! -r /etc/default/syslogd || . /etc/default/syslogd
-
-# allow ltsp to override
-test ! -r /etc/ltsp/syslogd || . /etc/ltsp/syslogd
-
-# Figure out under which user syslogd should be running as
-if echo ${SYSLOGD} | grep -q '^.*-u[[:space:]]*\([[:alnum:]]*\)[[:space:]]*.*$'
-then
-       # A specific user has been set on the command line, try to extract it.
-       USER=$(echo ${SYSLOGD} | sed -e 's/^.*-u[[:space:]]*\([[:alnum:]]*\)[[:space:]]*.*$/\1/')
-else
-       # By default, run syslogd under the syslog user
-       SYSLOGD="${SYSLOGD} -u ${USER}"
-fi
-
-# Unable to get the user under which syslogd should be running, stop.
-if [ -z "${USER}" ]
-then
-       log_failure_msg "Unable to get syslog user"
-       exit 1
-fi
-
-. /lib/lsb/init-functions
-
-create_xconsole()
-{
-    # Only proceed if /dev/xconsole is used at all
-    if ! grep -q '^[^#].*/dev/xconsole' /etc/syslog.conf
-    then
-       return
-    fi
-
-    if [ ! -e /dev/xconsole ]; then
-       mknod -m 640 /dev/xconsole p
-    else
-       chmod 0640 /dev/xconsole
-    fi
-
-    chown ${USER}:adm /dev/xconsole
+def write_to_file(inf, outf):
+    for blob in chunkyreader(inf):
+        outf.write(blob)
+    
 
-}
+def inputiter():
+    if os.isatty(sys.stdin.fileno()):
+        while 1:
+            try:
+                yield raw_input('bup> ')
+            except EOFError:
+                break
+    else:
+        for line in sys.stdin:
+            yield line
+
+
+def _completer_get_subs(line):
+    (qtype, lastword) = shquote.unfinished_word(line)
+    (dir,name) = os.path.split(lastword)
+    #log('\ncompleter: %r %r %r\n' % (qtype, lastword, text))
+    n = pwd.resolve(dir)
+    subs = list(filter(lambda x: x.name.startswith(name),
+                       n.subs()))
+    return (dir, name, qtype, lastword, subs)
+
+
+_last_line = None
+_last_res = None
+def completer(text, state):
+    global _last_line
+    global _last_res
+    try:
+        line = readline.get_line_buffer()[:readline.get_endidx()]
+        if _last_line != line:
+            _last_res = _completer_get_subs(line)
+            _last_line = line
+        (dir, name, qtype, lastword, subs) = _last_res
+        if state < len(subs):
+            sn = subs[state]
+            sn1 = sn.resolve('')  # deref symlinks
+            fullname = os.path.join(dir, sn.name)
+            if stat.S_ISDIR(sn1.mode):
+                ret = shquote.what_to_add(qtype, lastword, fullname+'/',
+                                          terminate=False)
+            else:
+                ret = shquote.what_to_add(qtype, lastword, fullname,
+                                          terminate=True) + ' '
+            return text + ret
+    except Exception, e:
+        log('\nerror in completion: %s\n' % e)
+
+            
+optspec = """
+bup ftp
+"""
+o = options.Options('bup ftp', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+git.check_repo_or_die()
+
+top = vfs.RefList(None)
+pwd = top
+
+if extra:
+    lines = extra
+else:
+    readline.set_completer_delims(' \t\n\r/')
+    readline.set_completer(completer)
+    readline.parse_and_bind("tab: complete")
+    lines = inputiter()
+
+for line in lines:
+    if not line.strip():
+        continue
+    words = [word for (wordstart,word) in shquote.quotesplit(line)]
+    cmd = words[0].lower()
+    #log('execute: %r %r\n' % (cmd, parm))
+    try:
+        if cmd == 'ls':
+            for parm in (words[1:] or ['.']):
+                do_ls(parm, pwd.resolve(parm))
+        elif cmd == 'cd':
+            for parm in words[1:]:
+                pwd = pwd.resolve(parm)
+        elif cmd == 'pwd':
+            print pwd.fullname()
+        elif cmd == 'cat':
+            for parm in words[1:]:
+                write_to_file(pwd.resolve(parm).open(), sys.stdout)
+        elif cmd == 'get':
+            if len(words) not in [2,3]:
+                raise Exception('Usage: get <filename> [localname]')
+            rname = words[1]
+            (dir,base) = os.path.split(rname)
+            lname = len(words)>2 and words[2] or base
+            inf = pwd.resolve(rname).open()
+            log('Saving %r\n' % lname)
+            write_to_file(inf, open(lname, 'wb'))
+        elif cmd == 'mget':
+            for parm in words[1:]:
+                (dir,base) = os.path.split(parm)
+                for n in pwd.resolve(dir).subs():
+                    if fnmatch.fnmatch(n.name, base):
+                        try:
+                            log('Saving %r\n' % n.name)
+                            inf = n.open()
+                            outf = open(n.name, 'wb')
+                            write_to_file(inf, outf)
+                            outf.close()
+                        except Exception, e:
+                            log('  error: %s\n' % e)
+        elif cmd == 'help' or cmd == '?':
+            log('Commands: ls cd pwd cat get mget help quit\n')
+        elif cmd == 'quit' or cmd == 'exit' or cmd == 'bye':
+            break
+        else:
+            raise Exception('no such command %r' % cmd)
+    except Exception, e:
+        log('error: %s\n' % e)
+        #raise
+#!/usr/bin/env python
+import sys, mmap
+from bup import options, _hashsplit
+from bup.helpers import *
+
+optspec = """
+bup random [-S seed] <numbytes>
+--
+S,seed=   optional random number seed (default 1)
+f,force   print random data to stdout even if it's a tty
+"""
+o = options.Options('bup random', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if len(extra) != 1:
+    o.fatal("exactly one argument expected")
+
+total = parse_num(extra[0])
+
+if opt.force or (not os.isatty(1) and
+                 not atoi(os.environ.get('BUP_FORCE_TTY')) & 1):
+    _hashsplit.write_random(sys.stdout.fileno(), total, opt.seed or 0)
+else:
+    log('error: not writing binary data to a terminal. Use -f to force.\n')
+    sys.exit(1)
+#!/usr/bin/env python
+import sys, os, glob
+from bup import options
+
+optspec = """
+bup help <command>
+"""
+o = options.Options('bup help', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if len(extra) == 0:
+    # the wrapper program provides the default usage string
+    os.execvp(os.environ['BUP_MAIN_EXE'], ['bup'])
+elif len(extra) == 1:
+    docname = (extra[0]=='bup' and 'bup' or ('bup-%s' % extra[0]))
+    exe = sys.argv[0]
+    (exepath, exefile) = os.path.split(exe)
+    manpath = os.path.join(exepath, '../Documentation/' + docname + '.[1-9]')
+    g = glob.glob(manpath)
+    if g:
+        os.execvp('man', ['man', '-l', g[0]])
+    else:
+        os.execvp('man', ['man', docname])
+else:
+    o.fatal("exactly one command name expected")
+#!/usr/bin/env python
+import sys, os, stat, errno, fuse, re, time, tempfile
+from bup import options, git, vfs
+from bup.helpers import *
+
+
+class Stat(fuse.Stat):
+    def __init__(self):
+        self.st_mode = 0
+        self.st_ino = 0
+        self.st_dev = 0
+        self.st_nlink = 0
+        self.st_uid = 0
+        self.st_gid = 0
+        self.st_size = 0
+        self.st_atime = 0
+        self.st_mtime = 0
+        self.st_ctime = 0
+        self.st_blocks = 0
+        self.st_blksize = 0
+        self.st_rdev = 0
+
+
+cache = {}
+def cache_get(top, path):
+    parts = path.split('/')
+    cache[('',)] = top
+    c = None
+    max = len(parts)
+    #log('cache: %r\n' % cache.keys())
+    for i in range(max):
+        pre = parts[:max-i]
+        #log('cache trying: %r\n' % pre)
+        c = cache.get(tuple(pre))
+        if c:
+            rest = parts[max-i:]
+            for r in rest:
+                #log('resolving %r from %r\n' % (r, c.fullname()))
+                c = c.lresolve(r)
+                key = tuple(pre + [r])
+                #log('saving: %r\n' % (key,))
+                cache[key] = c
+            break
+    assert(c)
+    return c
+        
+    
 
-fix_log_ownership()
-{
-       for l in `syslogd-listfiles -a`
-       do
-               chown ${USER}:adm $l
-       done
-}
+class BupFs(fuse.Fuse):
+    def __init__(self, top):
+        fuse.Fuse.__init__(self)
+        self.top = top
+    
+    def getattr(self, path):
+        log('--getattr(%r)\n' % path)
+        try:
+            node = cache_get(self.top, path)
+            st = Stat()
+            st.st_mode = node.mode
+            st.st_nlink = node.nlinks()
+            st.st_size = node.size()
+            st.st_mtime = node.mtime
+            st.st_ctime = node.ctime
+            st.st_atime = node.atime
+            return st
+        except vfs.NoSuchFile:
+            return -errno.ENOENT
+
+    def readdir(self, path, offset):
+        log('--readdir(%r)\n' % path)
+        node = cache_get(self.top, path)
+        yield fuse.Direntry('.')
+        yield fuse.Direntry('..')
+        for sub in node.subs():
+            yield fuse.Direntry(sub.name)
+
+    def readlink(self, path):
+        log('--readlink(%r)\n' % path)
+        node = cache_get(self.top, path)
+        return node.readlink()
+
+    def open(self, path, flags):
+        log('--open(%r)\n' % path)
+        node = cache_get(self.top, path)
+        accmode = os.O_RDONLY | os.O_WRONLY | os.O_RDWR
+        if (flags & accmode) != os.O_RDONLY:
+            return -errno.EACCES
+        node.open()
+
+    def release(self, path, flags):
+        log('--release(%r)\n' % path)
+
+    def read(self, path, size, offset):
+        log('--read(%r)\n' % path)
+        n = cache_get(self.top, path)
+        o = n.open()
+        o.seek(offset)
+        return o.read(size)
+
+
+if not hasattr(fuse, '__version__'):
+    raise RuntimeError, "your fuse module is too old for fuse.__version__"
+fuse.fuse_python_api = (0, 2)
+
+
+optspec = """
+bup fuse [-d] [-f] <mountpoint>
+--
+d,debug   increase debug level
+f,foreground  run in foreground
+"""
+o = options.Options('bup fuse', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if len(extra) != 1:
+    o.fatal("exactly one argument expected")
+
+git.check_repo_or_die()
+top = vfs.RefList(None)
+f = BupFs(top)
+f.fuse_args.mountpoint = extra[0]
+if opt.debug:
+    f.fuse_args.add('debug')
+if opt.foreground:
+    f.fuse_args.setmod('foreground')
+print f.multithreaded
+f.multithreaded = False
+
+f.main()
+#!/usr/bin/env python
+from bup import git, options, client
+from bup.helpers import *
+
+optspec = """
+[BUP_DIR=...] bup init [-r host:path]
+--
+r,remote=  remote repository path
+"""
+o = options.Options('bup init', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if extra:
+    o.fatal("no arguments expected")
+
+
+if opt.remote:
+    git.init_repo()  # local repo
+    git.check_repo_or_die()
+    cli = client.Client(opt.remote, create=True)
+    cli.close()
+else:
+    git.init_repo()
+#!/usr/bin/env python
+import sys, math, struct, glob
+from bup import options, git
+from bup.helpers import *
+
+PAGE_SIZE=4096
+SHA_PER_PAGE=PAGE_SIZE/200.
+
+
+def merge(idxlist, bits, table):
+    count = 0
+    for e in git.idxmerge(idxlist):
+        count += 1
+        prefix = git.extract_bits(e, bits)
+        table[prefix] = count
+        yield e
+
+
+def do_midx(outdir, outfilename, infilenames):
+    if not outfilename:
+        assert(outdir)
+        sum = Sha1('\0'.join(infilenames)).hexdigest()
+        outfilename = '%s/midx-%s.midx' % (outdir, sum)
+    
+    inp = []
+    total = 0
+    for name in infilenames:
+        ix = git.PackIdx(name)
+        inp.append(ix)
+        total += len(ix)
+
+    log('Merging %d indexes (%d objects).\n' % (len(infilenames), total))
+    if (not opt.force and (total < 1024 and len(infilenames) < 3)) \
+       or (opt.force and not total):
+        log('midx: nothing to do.\n')
+        return
+
+    pages = int(total/SHA_PER_PAGE) or 1
+    bits = int(math.ceil(math.log(pages, 2)))
+    entries = 2**bits
+    log('Table size: %d (%d bits)\n' % (entries*4, bits))
+    
+    table = [0]*entries
+
+    try:
+        os.unlink(outfilename)
+    except OSError:
+        pass
+    f = open(outfilename + '.tmp', 'w+')
+    f.write('MIDX\0\0\0\2')
+    f.write(struct.pack('!I', bits))
+    assert(f.tell() == 12)
+    f.write('\0'*4*entries)
+    
+    for e in merge(inp, bits, table):
+        f.write(e)
+        
+    f.write('\0'.join(os.path.basename(p) for p in infilenames))
+
+    f.seek(12)
+    f.write(struct.pack('!%dI' % entries, *table))
+    f.close()
+    os.rename(outfilename + '.tmp', outfilename)
+
+    # this is just for testing
+    if 0:
+        p = git.PackMidx(outfilename)
+        assert(len(p.idxnames) == len(infilenames))
+        print p.idxnames
+        assert(len(p) == total)
+        pi = iter(p)
+        for i in merge(inp, total, bits, table):
+            assert(i == pi.next())
+            assert(p.exists(i))
+
+    print outfilename
+
+optspec = """
+bup midx [options...] <idxnames...>
+--
+o,output=  output midx filename (default: auto-generated)
+a,auto     automatically create .midx from any unindexed .idx files
+f,force    automatically create .midx from *all* .idx files
+"""
+o = options.Options('bup midx', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if extra and (opt.auto or opt.force):
+    o.fatal("you can't use -f/-a and also provide filenames")
+
+git.check_repo_or_die()
+
+if extra:
+    do_midx(git.repo('objects/pack'), opt.output, extra)
+elif opt.auto or opt.force:
+    paths = [git.repo('objects/pack')]
+    paths += glob.glob(git.repo('index-cache/*/.'))
+    for path in paths:
+        log('midx: scanning %s\n' % path)
+        if opt.force:
+            do_midx(path, opt.output, glob.glob('%s/*.idx' % path))
+        elif opt.auto:
+            m = git.PackIdxList(path)
+            needed = {}
+            for pack in m.packs:  # only .idx files without a .midx are open
+                if pack.name.endswith('.idx'):
+                    needed[pack.name] = 1
+            del m
+            do_midx(path, opt.output, needed.keys())
+        log('\n')
+else:
+    o.fatal("you must use -f or -a or provide input filenames")
+#!/usr/bin/env python
+import sys, os, random
+from bup import options
+from bup.helpers import *
+
+
+def randblock(n):
+    l = []
+    for i in xrange(n):
+        l.append(chr(random.randrange(0,256)))
+    return ''.join(l)
+
+
+optspec = """
+bup damage [-n count] [-s maxsize] [-S seed] <filenames...>
+--
+   WARNING: THIS COMMAND IS EXTREMELY DANGEROUS
+n,num=   number of blocks to damage
+s,size=  maximum size of each damaged block
+percent= maximum size of each damaged block (as a percent of entire file)
+equal    spread damage evenly throughout the file
+S,seed=  random number seed (for repeatable tests)
+"""
+o = options.Options('bup damage', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if not extra:
+    o.fatal('filenames expected')
+
+if opt.seed != None:
+    random.seed(opt.seed)
+
+for name in extra:
+    log('Damaging "%s"...\n' % name)
+    f = open(name, 'r+b')
+    st = os.fstat(f.fileno())
+    size = st.st_size
+    if opt.percent or opt.size:
+        ms1 = int(float(opt.percent or 0)/100.0*size) or size
+        ms2 = opt.size or size
+        maxsize = min(ms1, ms2)
+    else:
+        maxsize = 1
+    chunks = opt.num or 10
+    chunksize = size/chunks
+    for r in range(chunks):
+        sz = random.randrange(1, maxsize+1)
+        if sz > size:
+            sz = size
+        if opt.equal:
+            ofs = r*chunksize
+        else:
+            ofs = random.randrange(0, size - sz + 1)
+        log('  %6d bytes at %d\n' % (sz, ofs))
+        f.seek(ofs)
+        f.write(randblock(sz))
+    f.close()
+#!/usr/bin/env python
+import sys, struct, mmap
+from bup import options, git
+from bup.helpers import *
+
+suspended_w = None
+
+
+def init_dir(conn, arg):
+    git.init_repo(arg)
+    log('bup server: bupdir initialized: %r\n' % git.repodir)
+    conn.ok()
+
+
+def set_dir(conn, arg):
+    git.check_repo_or_die(arg)
+    log('bup server: bupdir is %r\n' % git.repodir)
+    conn.ok()
 
-running()
-{
-    # No pidfile, probably no daemon present
-    #
-    if [ ! -f $pidfile ]
-    then
-       return 1
-    fi
-
-    pid=`cat $pidfile`
-
-    # No pid, probably no daemon present
-    #
-    if [ -z "$pid" ]
-    then
-       return 1
-    fi
-
-    if [ ! -d /proc/$pid ]
-    then
-       return 1
-    fi
-
-    cmd=`cat /proc/$pid/cmdline | tr "\000" "\n"|head -n 1`
-
-    # No syslogd?
-    #
-    if [ "$cmd" != "$binpath" ]
-    then
-       return 1
-    fi
-
-    return 0
+    
+def list_indexes(conn, junk):
+    git.check_repo_or_die()
+    for f in os.listdir(git.repo('objects/pack')):
+        if f.endswith('.idx'):
+            conn.write('%s\n' % f)
+    conn.ok()
+
+
+def send_index(conn, name):
+    git.check_repo_or_die()
+    assert(name.find('/') < 0)
+    assert(name.endswith('.idx'))
+    idx = git.PackIdx(git.repo('objects/pack/%s' % name))
+    conn.write(struct.pack('!I', len(idx.map)))
+    conn.write(idx.map)
+    conn.ok()
+
+
+def receive_objects(conn, junk):
+    global suspended_w
+    git.check_repo_or_die()
+    suggested = {}
+    if suspended_w:
+        w = suspended_w
+        suspended_w = None
+    else:
+        w = git.PackWriter()
+    while 1:
+        ns = conn.read(4)
+        if not ns:
+            w.abort()
+            raise Exception('object read: expected length header, got EOF\n')
+        n = struct.unpack('!I', ns)[0]
+        #log('expecting %d bytes\n' % n)
+        if not n:
+            log('bup server: received %d object%s.\n' 
+                % (w.count, w.count!=1 and "s" or ''))
+            fullpath = w.close()
+            if fullpath:
+                (dir, name) = os.path.split(fullpath)
+                conn.write('%s.idx\n' % name)
+            conn.ok()
+            return
+        elif n == 0xffffffff:
+            log('bup server: receive-objects suspended.\n')
+            suspended_w = w
+            conn.ok()
+            return
+            
+        buf = conn.read(n)  # object sizes in bup are reasonably small
+        #log('read %d bytes\n' % n)
+        if len(buf) < n:
+            w.abort()
+            raise Exception('object read: expected %d bytes, got %d\n'
+                            % (n, len(buf)))
+        (type, content) = git._decode_packobj(buf)
+        sha = git.calc_hash(type, content)
+        oldpack = w.exists(sha)
+        # FIXME: we only suggest a single index per cycle, because the client
+        # is currently dumb to download more than one per cycle anyway.
+        # Actually we should fix the client, but this is a minor optimization
+        # on the server side.
+        if not suggested and \
+          oldpack and (oldpack == True or oldpack.endswith('.midx')):
+            # FIXME: we shouldn't really have to know about midx files
+            # at this layer.  But exists() on a midx doesn't return the
+            # packname (since it doesn't know)... probably we should just
+            # fix that deficiency of midx files eventually, although it'll
+            # make the files bigger.  This method is certainly not very
+            # efficient.
+            w.objcache.refresh(skip_midx = True)
+            oldpack = w.objcache.exists(sha)
+            log('new suggestion: %r\n' % oldpack)
+            assert(oldpack)
+            assert(oldpack != True)
+            assert(not oldpack.endswith('.midx'))
+            w.objcache.refresh(skip_midx = False)
+        if not suggested and oldpack:
+            assert(oldpack.endswith('.idx'))
+            (dir,name) = os.path.split(oldpack)
+            if not (name in suggested):
+                log("bup server: suggesting index %s\n" % name)
+                conn.write('index %s\n' % name)
+                suggested[name] = 1
+        else:
+            w._raw_write([buf])
+    # NOTREACHED
+
+
+def read_ref(conn, refname):
+    git.check_repo_or_die()
+    r = git.read_ref(refname)
+    conn.write('%s\n' % (r or '').encode('hex'))
+    conn.ok()
+
+
+def update_ref(conn, refname):
+    git.check_repo_or_die()
+    newval = conn.readline().strip()
+    oldval = conn.readline().strip()
+    git.update_ref(refname, newval.decode('hex'), oldval.decode('hex'))
+    conn.ok()
+
+
+def cat(conn, id):
+    git.check_repo_or_die()
+    try:
+        for blob in git.cat(id):
+            conn.write(struct.pack('!I', len(blob)))
+            conn.write(blob)
+    except KeyError, e:
+        log('server: error: %s\n' % e)
+        conn.write('\0\0\0\0')
+        conn.error(e)
+    else:
+        conn.write('\0\0\0\0')
+        conn.ok()
+
+
+optspec = """
+bup server
+"""
+o = options.Options('bup server', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if extra:
+    o.fatal('no arguments expected')
+
+log('bup server: reading from stdin.\n')
+
+commands = {
+    'init-dir': init_dir,
+    'set-dir': set_dir,
+    'list-indexes': list_indexes,
+    'send-index': send_index,
+    'receive-objects': receive_objects,
+    'read-ref': read_ref,
+    'update-ref': update_ref,
+    'cat': cat,
 }
 
-case "$1" in
-  start)
-    log_begin_msg "Starting system log daemon..."
-    create_xconsole
-    fix_log_ownership
-    start-stop-daemon --start --quiet --pidfile $pidfile --name syslogd --startas $binpath -- $SYSLOGD
-    log_end_msg $?
-    ;;
-  stop)
-    log_begin_msg "Stopping system log daemon..."
-    start-stop-daemon --stop --quiet --pidfile $pidfile --name syslogd
-    log_end_msg $?
-    ;;
-  reload|force-reload)
-    log_begin_msg "Reloading system log daemon..."
-    fix_log_ownership
-    start-stop-daemon --stop --quiet --signal 1 --pidfile $pidfile --name syslogd
-    log_end_msg $?
-    ;;
-  restart)
-    log_begin_msg "Restarting system log daemon..."
-    start-stop-daemon --stop --retry 5 --quiet --pidfile $pidfile --name syslogd
-    fix_log_ownership
-    start-stop-daemon --start --quiet --pidfile $pidfile --name syslogd --startas $binpath -- $SYSLOGD
-    log_end_msg $?
-    ;;
-  reload-or-restart)
-    if running
-    then
-       $0 reload
-    else
-       $0 start
-    fi
-    ;;
-  *)
-    log_success_msg "Usage: /etc/init.d/sysklogd {start|stop|reload|restart|force-reload|reload-or-restart}"
-    exit 1
-esac
-
-exit 0
-#!/bin/sh -e
-# init script for udev
-
-# Check the package is still installed
-[ -x /sbin/udevd ] || exit 0
-
-# Get LSB functions
-. /lib/lsb/init-functions
-. /etc/default/rcS
-
-
-case "$1" in
-    start)
-       # We need the uevent support introduced in 2.6.15, bail out if we
-       # don't have it and fall back to a static /dev
-       if [ ! -f /sys/class/mem/null/uevent ]; then
-           if mountpoint -q /dev; then
-               # uh-oh, initramfs made some kind of /dev, get rid of it
-               umount -l /dev/.static/dev
-               umount -l /dev
-           fi
-           exit 1
-       fi
-
-       if ! mountpoint -q /dev; then
-           # initramfs didn't mount /dev, so we'll need to do that
-           mount -n --bind /dev /etc/udev
-           mount -n -t tmpfs -o mode=0755 udev /dev
-           mkdir -m 0700 -p /dev/.static/dev
-           mount -n --move /etc/udev /dev/.static/dev
-       fi
-
-       # Copy over default device tree
-       cp -a -f /lib/udev/devices/* /dev
-
-       # It's all over netlink now
-       if [ -e /proc/sys/kernel/hotplug ]; then
-           echo "" > /proc/sys/kernel/hotplug
-       fi
-       
-       # Start udevd
-       log_begin_msg "Starting kernel event manager..."
-       if start-stop-daemon --start --quiet --exec /sbin/udevd -- --daemon; then
-           log_end_msg 0
-       else
-           log_end_msg $?
-       fi
-
-       # This next bit can take a while
-       if type usplash_write >/dev/null 2>&1; then
-           usplash_write "TIMEOUT 360" ||:
-           trap "usplash_write 'TIMEOUT 15' ||:" 0
-       fi
-
-       # Log things that trigger does
-       /sbin/udevadm monitor -e >/dev/.udev.log &
-       UDEV_MONITOR_PID=$!
-
-       # Fix permissions and missing symlinks/programs for devices made in
-       # initramfs, and catch up on everything we missed
-       log_begin_msg "Loading hardware drivers..."
-       /sbin/udevadm trigger
-       if /sbin/udevadm settle; then
-           log_end_msg 0
-       else
-           log_end_msg $?
-       fi
-
-       # Kill the udev monitor again
-       kill $UDEV_MONITOR_PID
-       ;;
-    stop)
-       log_begin_msg "Stopping kernel event manager..."
-       if start-stop-daemon --stop --quiet --oknodo --exec /sbin/udevd; then
-           log_end_msg 0
-       else
-           log_end_msg $?
-       fi
-       umount -l /dev/.static/dev
-       umount -l /dev
-       ;;
-    restart)
-       cp -au /lib/udev/devices/* /dev
-
-       log_begin_msg "Loading additional hardware drivers..."
-       /sbin/udevadm trigger
-       if /sbin/udevadm settle; then
-           log_end_msg 0
-       else
-           log_end_msg $?
-       fi
-       ;;
-    reload|force-reload)
-       log_begin_msg "Reloading kernel event manager..."
-       if start-stop-daemon --stop --signal 1 --exec /sbin/udevd; then
-           log_end_msg 0
-       else
-           log_end_msg $?
-       fi
-       ;;
-*)
-       echo "Usage: /etc/init.d/udev {start|stop|restart|reload|force-reload}"
-       exit 1
-       ;;
-esac
-
-exit 0
-#!/bin/sh -e
-# init script to finish up udev
-
-# Check the package is still installed
-[ -x /sbin/udevd ] || exit 0
-
-# Get LSB functions
-. /lib/lsb/init-functions
-. /etc/default/rcS
-
-
-case "$1" in
-    start)
-       # Save udev log in /var/log/udev
-       if [ -e /dev/.udev.log ]; then
-           mv -f /dev/.udev.log /var/log/udev
-       fi
-
-       # Copy any rules generated while the root filesystem was read-only
-       for file in /dev/.udev/tmp-rules--*; do
-           dest=${file##*tmp-rules--}
-           [ "$dest" = '*' ] && break
-           cat $file >> /etc/udev/rules.d/$dest
-           rm -f $file
-       done
-       ;;
-    stop|restart|reload|force-reload)
-       ;;
-*)
-       echo "Usage: /etc/init.d/udev {start|stop|restart|reload|force-reload}"
-       exit 1
-       ;;
-esac
-
-exit 0
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          umountfs
-# Required-Start:    umountnfs urandom
-# Required-Stop:
-# Default-Start:     0 6
-# Default-Stop:
-# Short-Description: Turn off swap and unmount all local file systems.
-# Description:
-### END INIT INFO
-
-PATH=/usr/sbin:/usr/bin:/sbin:/bin
-. /lib/init/vars.sh
-
-. /lib/lsb/init-functions
-
-umask 022
-
-# Print in order of decreasing length
-#
-# Algorithm: Find and print longest argument, then call self
-# to print remaining arguments in order of decreasing length
-#
-# This function runs at one tenth the speed of the sort program
-# but we use the function because we don't want to rely on any
-# programs in /usr/.
+# FIXME: this protocol is totally lame and not at all future-proof.
+# (Especially since we abort completely as soon as *anything* bad happens)
+conn = Conn(sys.stdin, sys.stdout)
+lr = linereader(conn)
+for _line in lr:
+    line = _line.strip()
+    if not line:
+        continue
+    log('bup server: command: %r\n' % line)
+    words = line.split(' ', 1)
+    cmd = words[0]
+    rest = len(words)>1 and words[1] or ''
+    if cmd == 'quit':
+        break
+    else:
+        cmd = commands.get(cmd)
+        if cmd:
+            cmd(conn, rest)
+        else:
+            raise Exception('unknown server command: %r\n' % line)
+
+log('bup server: done\n')
+#!/usr/bin/env python
+import sys, time, struct
+from bup import hashsplit, git, options, client
+from bup.helpers import *
+from subprocess import PIPE
+
+
+optspec = """
+bup join [-r host:path] [refs or hashes...]
+--
+r,remote=  remote repository path
+"""
+o = options.Options('bup join', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+git.check_repo_or_die()
+
+if not extra:
+    extra = linereader(sys.stdin)
+
+ret = 0
+
+if opt.remote:
+    cli = client.Client(opt.remote)
+    cat = cli.cat
+else:
+    cp = git.CatPipe()
+    cat = cp.join
+
+for id in extra:
+    try:
+        for blob in cat(id):
+            sys.stdout.write(blob)
+    except KeyError, e:
+        sys.stdout.flush()
+        log('error: %s\n' % e)
+        ret = 1
+
+sys.exit(ret)
+#!/usr/bin/env python
+import sys, re, errno, stat, time, math
+from bup import hashsplit, git, options, index, client
+from bup.helpers import *
+
+
+optspec = """
+bup save [-tc] [-n name] <filenames...>
+--
+r,remote=  remote repository path
+t,tree     output a tree id
+c,commit   output a commit id
+n,name=    name of backup set to update (if any)
+v,verbose  increase log output (can be used more than once)
+q,quiet    don't show progress meter
+smaller=   only back up files smaller than n bytes
+"""
+o = options.Options('bup save', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+git.check_repo_or_die()
+if not (opt.tree or opt.commit or opt.name):
+    o.fatal("use one or more of -t, -c, -n")
+if not extra:
+    o.fatal("no filenames given")
+
+opt.progress = (istty and not opt.quiet)
+opt.smaller = parse_num(opt.smaller or 0)
+
+is_reverse = os.environ.get('BUP_SERVER_REVERSE')
+if is_reverse and opt.remote:
+    o.fatal("don't use -r in reverse mode; it's automatic")
+
+refname = opt.name and 'refs/heads/%s' % opt.name or None
+if opt.remote or is_reverse:
+    cli = client.Client(opt.remote)
+    oldref = refname and cli.read_ref(refname) or None
+    w = cli.new_packwriter()
+else:
+    cli = None
+    oldref = refname and git.read_ref(refname) or None
+    w = git.PackWriter()
+
+handle_ctrl_c()
+
+
+def eatslash(dir):
+    if dir.endswith('/'):
+        return dir[:-1]
+    else:
+        return dir
+
+
+parts = ['']
+shalists = [[]]
+
+def _push(part):
+    assert(part)
+    parts.append(part)
+    shalists.append([])
+
+def _pop(force_tree):
+    assert(len(parts) >= 1)
+    part = parts.pop()
+    shalist = shalists.pop()
+    tree = force_tree or w.new_tree(shalist)
+    if shalists:
+        shalists[-1].append(('40000', part, tree))
+    else:  # this was the toplevel, so put it back for sanity
+        shalists.append(shalist)
+    return tree
+
+lastremain = None
+def progress_report(n):
+    global count, subcount, lastremain
+    subcount += n
+    cc = count + subcount
+    pct = total and (cc*100.0/total) or 0
+    now = time.time()
+    elapsed = now - tstart
+    kps = elapsed and int(cc/1024./elapsed)
+    kps_frac = 10 ** int(math.log(kps+1, 10) - 1)
+    kps = int(kps/kps_frac)*kps_frac
+    if cc:
+        remain = elapsed*1.0/cc * (total-cc)
+    else:
+        remain = 0.0
+    if (lastremain and (remain > lastremain)
+          and ((remain - lastremain)/lastremain < 0.05)):
+        remain = lastremain
+    else:
+        lastremain = remain
+    hours = int(remain/60/60)
+    mins = int(remain/60 - hours*60)
+    secs = int(remain - hours*60*60 - mins*60)
+    if elapsed < 30:
+        remainstr = ''
+        kpsstr = ''
+    else:
+        kpsstr = '%dk/s' % kps
+        if hours:
+            remainstr = '%dh%dm' % (hours, mins)
+        elif mins:
+            remainstr = '%dm%d' % (mins, secs)
+        else:
+            remainstr = '%ds' % secs
+    progress('Saving: %.2f%% (%d/%dk, %d/%d files) %s %s\r'
+             % (pct, cc/1024, total/1024, fcount, ftotal,
+                remainstr, kpsstr))
+
+
+r = index.Reader(git.repo('bupindex'))
+
+def already_saved(ent):
+    return ent.is_valid() and w.exists(ent.sha) and ent.sha
+
+def wantrecurse_pre(ent):
+    return not already_saved(ent)
+
+def wantrecurse_during(ent):
+    return not already_saved(ent) or ent.sha_missing()
+
+total = ftotal = 0
+if opt.progress:
+    for (transname,ent) in r.filter(extra, wantrecurse=wantrecurse_pre):
+        if not (ftotal % 10024):
+            progress('Reading index: %d\r' % ftotal)
+        exists = ent.exists()
+        hashvalid = already_saved(ent)
+        ent.set_sha_missing(not hashvalid)
+        if not opt.smaller or ent.size < opt.smaller:
+            if exists and not hashvalid:
+                total += ent.size
+        ftotal += 1
+    progress('Reading index: %d, done.\n' % ftotal)
+    hashsplit.progress_callback = progress_report
+
+tstart = time.time()
+count = subcount = fcount = 0
+lastskip_name = None
+lastdir = ''
+for (transname,ent) in r.filter(extra, wantrecurse=wantrecurse_during):
+    (dir, file) = os.path.split(ent.name)
+    exists = (ent.flags & index.IX_EXISTS)
+    hashvalid = already_saved(ent)
+    wasmissing = ent.sha_missing()
+    oldsize = ent.size
+    if opt.verbose:
+        if not exists:
+            status = 'D'
+        elif not hashvalid:
+            if ent.sha == index.EMPTY_SHA:
+                status = 'A'
+            else:
+                status = 'M'
+        else:
+            status = ' '
+        if opt.verbose >= 2:
+            log('%s %-70s\n' % (status, ent.name))
+        elif not stat.S_ISDIR(ent.mode) and lastdir != dir:
+            if not lastdir.startswith(dir):
+                log('%s %-70s\n' % (status, os.path.join(dir, '')))
+            lastdir = dir
+
+    if opt.progress:
+        progress_report(0)
+    fcount += 1
+    
+    if not exists:
+        continue
+    if opt.smaller and ent.size >= opt.smaller:
+        if exists and not hashvalid:
+            add_error('skipping large file "%s"' % ent.name)
+            lastskip_name = ent.name
+        continue
+
+    assert(dir.startswith('/'))
+    dirp = dir.split('/')
+    while parts > dirp:
+        _pop(force_tree = None)
+    if dir != '/':
+        for part in dirp[len(parts):]:
+            _push(part)
+
+    if not file:
+        # no filename portion means this is a subdir.  But
+        # sub/parentdirectories already handled in the pop/push() part above.
+        oldtree = already_saved(ent) # may be None
+        newtree = _pop(force_tree = oldtree)
+        if not oldtree:
+            if lastskip_name and lastskip_name.startswith(ent.name):
+                ent.invalidate()
+            else:
+                ent.validate(040000, newtree)
+            ent.repack()
+        if exists and wasmissing:
+            count += oldsize
+        continue
+
+    # it's not a directory
+    id = None
+    if hashvalid:
+        mode = '%o' % ent.gitmode
+        id = ent.sha
+        shalists[-1].append((mode, 
+                             git.mangle_name(file, ent.mode, ent.gitmode),
+                             id))
+    else:
+        if stat.S_ISREG(ent.mode):
+            try:
+                f = hashsplit.open_noatime(ent.name)
+            except IOError, e:
+                add_error(e)
+                lastskip_name = ent.name
+            except OSError, e:
+                add_error(e)
+                lastskip_name = ent.name
+            else:
+                (mode, id) = hashsplit.split_to_blob_or_tree(w, [f])
+        else:
+            if stat.S_ISDIR(ent.mode):
+                assert(0)  # handled above
+            elif stat.S_ISLNK(ent.mode):
+                try:
+                    rl = os.readlink(ent.name)
+                except OSError, e:
+                    add_error(e)
+                    lastskip_name = ent.name
+                except IOError, e:
+                    add_error(e)
+                    lastskip_name = ent.name
+                else:
+                    (mode, id) = ('120000', w.new_blob(rl))
+            else:
+                add_error(Exception('skipping special file "%s"' % ent.name))
+                lastskip_name = ent.name
+        if id:
+            ent.validate(int(mode, 8), id)
+            ent.repack()
+            shalists[-1].append((mode,
+                                 git.mangle_name(file, ent.mode, ent.gitmode),
+                                 id))
+    if exists and wasmissing:
+        count += oldsize
+        subcount = 0
+
+
+if opt.progress:
+    pct = total and count*100.0/total or 100
+    progress('Saving: %.2f%% (%d/%dk, %d/%d files), done.    \n'
+             % (pct, count/1024, total/1024, fcount, ftotal))
+
+while len(parts) > 1:
+    _pop(force_tree = None)
+assert(len(shalists) == 1)
+tree = w.new_tree(shalists[-1])
+if opt.tree:
+    print tree.encode('hex')
+if opt.commit or opt.name:
+    msg = 'bup save\n\nGenerated by command:\n%r' % sys.argv
+    ref = opt.name and ('refs/heads/%s' % opt.name) or None
+    commit = w.new_commit(oldref, tree, msg)
+    if opt.commit:
+        print commit.encode('hex')
+
+w.close()  # must close before we can update the ref
+        
+if opt.name:
+    if cli:
+        cli.update_ref(refname, commit, oldref)
+    else:
+        git.update_ref(refname, commit, oldref)
+
+if cli:
+    cli.close()
+
+if saved_errors:
+    log('WARNING: %d errors encountered while saving.\n' % len(saved_errors))
+    sys.exit(1)
+#!/usr/bin/env python
+import sys, time
+from bup import options
+
+optspec = """
+bup tick
+"""
+o = options.Options('bup tick', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if extra:
+    o.fatal("no arguments expected")
+
+t = time.time()
+tleft = 1 - (t - int(t))
+time.sleep(tleft)
+#!/usr/bin/env python
+import os, sys, stat, time
+from bup import options, git, index, drecurse
+from bup.helpers import *
+
+
+def merge_indexes(out, r1, r2):
+    for e in index.MergeIter([r1, r2]):
+        # FIXME: shouldn't we remove deleted entries eventually?  When?
+        out.add_ixentry(e)
+
+
+class IterHelper:
+    def __init__(self, l):
+        self.i = iter(l)
+        self.cur = None
+        self.next()
+
+    def next(self):
+        try:
+            self.cur = self.i.next()
+        except StopIteration:
+            self.cur = None
+        return self.cur
+
+
+def check_index(reader):
+    try:
+        log('check: checking forward iteration...\n')
+        e = None
+        d = {}
+        for e in reader.forward_iter():
+            if e.children_n:
+                if opt.verbose:
+                    log('%08x+%-4d %r\n' % (e.children_ofs, e.children_n,
+                                            e.name))
+                assert(e.children_ofs)
+                assert(e.name.endswith('/'))
+                assert(not d.get(e.children_ofs))
+                d[e.children_ofs] = 1
+            if e.flags & index.IX_HASHVALID:
+                assert(e.sha != index.EMPTY_SHA)
+                assert(e.gitmode)
+        assert(not e or e.name == '/')  # last entry is *always* /
+        log('check: checking normal iteration...\n')
+        last = None
+        for e in reader:
+            if last:
+                assert(last > e.name)
+            last = e.name
+    except:
+        log('index error! at %r\n' % e)
+        raise
+    log('check: passed.\n')
+
+
+def update_index(top):
+    ri = index.Reader(indexfile)
+    wi = index.Writer(indexfile)
+    rig = IterHelper(ri.iter(name=top))
+    tstart = int(time.time())
+
+    hashgen = None
+    if opt.fake_valid:
+        def hashgen(name):
+            return (0100644, index.FAKE_SHA)
+
+    total = 0
+    for (path,pst) in drecurse.recursive_dirlist([top], xdev=opt.xdev):
+        if opt.verbose>=2 or (opt.verbose==1 and stat.S_ISDIR(pst.st_mode)):
+            sys.stdout.write('%s\n' % path)
+            sys.stdout.flush()
+            progress('Indexing: %d\r' % total)
+        elif not (total % 128):
+            progress('Indexing: %d\r' % total)
+        total += 1
+        while rig.cur and rig.cur.name > path:  # deleted paths
+            if rig.cur.exists():
+                rig.cur.set_deleted()
+                rig.cur.repack()
+            rig.next()
+        if rig.cur and rig.cur.name == path:    # paths that already existed
+            if pst:
+                rig.cur.from_stat(pst, tstart)
+            if not (rig.cur.flags & index.IX_HASHVALID):
+                if hashgen:
+                    (rig.cur.gitmode, rig.cur.sha) = hashgen(path)
+                    rig.cur.flags |= index.IX_HASHVALID
+            if opt.fake_invalid:
+                rig.cur.invalidate()
+            rig.cur.repack()
+            rig.next()
+        else:  # new paths
+            wi.add(path, pst, hashgen = hashgen)
+    progress('Indexing: %d, done.\n' % total)
+    
+    if ri.exists():
+        ri.save()
+        wi.flush()
+        if wi.count:
+            wr = wi.new_reader()
+            if opt.check:
+                log('check: before merging: oldfile\n')
+                check_index(ri)
+                log('check: before merging: newfile\n')
+                check_index(wr)
+            mi = index.Writer(indexfile)
+            merge_indexes(mi, ri, wr)
+            ri.close()
+            mi.close()
+            wr.close()
+        wi.abort()
+    else:
+        wi.close()
+
+
+optspec = """
+bup index <-p|m|u> [options...] <filenames...>
+--
+p,print    print the index entries for the given names (also works with -u)
+m,modified print only added/deleted/modified files (implies -p)
+s,status   print each filename with a status char (A/M/D) (implies -p)
+H,hash     print the hash for each object next to its name (implies -p)
+l,long     print more information about each file
+u,update   (recursively) update the index entries for the given filenames
+x,xdev,one-file-system  don't cross filesystem boundaries
+fake-valid mark all index entries as up-to-date even if they aren't
+fake-invalid mark all index entries as invalid
+check      carefully check index file integrity
+f,indexfile=  the name of the index file (default 'index')
+v,verbose  increase log output (can be used more than once)
+"""
+o = options.Options('bup index', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if not (opt.modified or opt['print'] or opt.status or opt.update or opt.check):
+    o.fatal('supply one or more of -p, -s, -m, -u, or --check')
+if (opt.fake_valid or opt.fake_invalid) and not opt.update:
+    o.fatal('--fake-{in,}valid are meaningless without -u')
+if opt.fake_valid and opt.fake_invalid:
+    o.fatal('--fake-valid is incompatible with --fake-invalid')
+
+git.check_repo_or_die()
+indexfile = opt.indexfile or git.repo('bupindex')
+
+handle_ctrl_c()
+
+if opt.check:
+    log('check: starting initial check.\n')
+    check_index(index.Reader(indexfile))
+
+paths = index.reduce_paths(extra)
+
+if opt.update:
+    if not paths:
+        o.fatal('update (-u) requested but no paths given')
+    for (rp,path) in paths:
+        update_index(rp)
+
+if opt['print'] or opt.status or opt.modified:
+    for (name, ent) in index.Reader(indexfile).filter(extra or ['']):
+        if (opt.modified 
+            and (ent.is_valid() or ent.is_deleted() or not ent.mode)):
+            continue
+        line = ''
+        if opt.status:
+            if ent.is_deleted():
+                line += 'D '
+            elif not ent.is_valid():
+                if ent.sha == index.EMPTY_SHA:
+                    line += 'A '
+                else:
+                    line += 'M '
+            else:
+                line += '  '
+        if opt.hash:
+            line += ent.sha.encode('hex') + ' '
+        if opt.long:
+            line += "%7s %7s " % (oct(ent.mode), oct(ent.gitmode))
+        print line + (name or './')
+
+if opt.check and (opt['print'] or opt.status or opt.modified or opt.update):
+    log('check: starting final check.\n')
+    check_index(index.Reader(indexfile))
+
+if saved_errors:
+    log('WARNING: %d errors encountered.\n' % len(saved_errors))
+    sys.exit(1)
+#!/usr/bin/env python
+import sys, os, struct
+from bup import options, helpers
+
+optspec = """
+bup rbackup-server
+--
+    This command is not intended to be run manually.
+"""
+o = options.Options('bup rbackup-server', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+if extra:
+    o.fatal('no arguments expected')
+
+# get the subcommand's argv.
+# Normally we could just pass this on the command line, but since we'll often
+# be getting called on the other end of an ssh pipe, which tends to mangle
+# argv (by sending it via the shell), this way is much safer.
+buf = sys.stdin.read(4)
+sz = struct.unpack('!I', buf)[0]
+assert(sz > 0)
+assert(sz < 1000000)
+buf = sys.stdin.read(sz)
+assert(len(buf) == sz)
+argv = buf.split('\0')
+
+# stdin/stdout are supposedly connected to 'bup server' that the caller
+# started for us (often on the other end of an ssh tunnel), so we don't want
+# to misuse them.  Move them out of the way, then replace stdout with
+# a pointer to stderr in case our subcommand wants to do something with it.
 #
-# N.B.: Arguments must not be null and must not contain whitespace
+# It might be nice to do the same with stdin, but my experiments showed that
+# ssh seems to make its child's stderr a readable-but-never-reads-anything
+# socket.  They really should have used shutdown(SHUT_WR) on the other end
+# of it, but probably didn't.  Anyway, it's too messy, so let's just make sure
+# anyone reading from stdin is disappointed.
 #
-pioodl() {
-       [ "$1" ] || return 0
-       ARGNUM=1
-       ARGNUM_LONGEST=0
-       ARGLENGTH_LONGEST=0
-       for ARG in "$@"
-       do
-               ARGLENGTH="${#ARG}"
-               if [ "$ARGLENGTH" -gt "$ARGLENGTH_LONGEST" ]
-               then
-                       ARGLENGTH_LONGEST="$ARGLENGTH"
-                       ARGNUM_LONGEST="$ARGNUM"
-               fi
-               ARGNUM=$(($ARGNUM + 1))
-       done
-       # The method of passing prevargs assumes that args can be
-       # delimited with spaces
-       ARGNUM=1
-       PREVARGS=""
-       while [ "$ARGNUM" -lt "$ARGNUM_LONGEST" ]
-       do
-               PREVARGS="$PREVARGS $1"
-               shift
-               ARGNUM=$(($ARGNUM + 1))
-       done
-       echo "$1"
-       shift
-       pioodl $PREVARGS "$@"
-}
+# (You can't just leave stdin/stdout "not open" by closing the file
+# descriptors.  Then the next file that opens is automatically assigned 0 or 1,
+# and people *trying* to read/write stdin/stdout get screwed.)
+os.dup2(0, 3)
+os.dup2(1, 4)
+os.dup2(2, 1)
+fd = os.open('/dev/null', os.O_RDONLY)
+os.dup2(fd, 0)
+os.close(fd)
+
+os.environ['BUP_SERVER_REVERSE'] = helpers.hostname()
+os.execvp(argv[0], argv)
+sys.exit(99)
+#!/usr/bin/env python
+import sys, os, glob, subprocess, time
+from bup import options, git
+from bup.helpers import *
+
+par2_ok = 0
+nullf = open('/dev/null')
+
+def debug(s):
+    if opt.verbose:
+        log(s)
+
+def run(argv):
+    # at least in python 2.5, using "stdout=2" or "stdout=sys.stderr" below
+    # doesn't actually work, because subprocess closes fd #2 right before
+    # execing for some reason.  So we work around it by duplicating the fd
+    # first.
+    fd = os.dup(2)  # copy stderr
+    try:
+        p = subprocess.Popen(argv, stdout=fd, close_fds=False)
+        return p.wait()
+    finally:
+        os.close(fd)
+
+def par2_setup():
+    global par2_ok
+    rv = 1
+    try:
+        p = subprocess.Popen(['par2', '--help'],
+                             stdout=nullf, stderr=nullf, stdin=nullf)
+        rv = p.wait()
+    except OSError:
+        log('fsck: warning: par2 not found; disabling recovery features.\n')
+    else:
+        par2_ok = 1
+
+def parv(lvl):
+    if opt.verbose >= lvl:
+        if istty:
+            return []
+        else:
+            return ['-q']
+    else:
+        return ['-qq']
+
+def par2_generate(base):
+    return run(['par2', 'create', '-n1', '-c200'] + parv(2)
+               + ['--', base, base+'.pack', base+'.idx'])
+
+def par2_verify(base):
+    return run(['par2', 'verify'] + parv(3) + ['--', base])
+
+def par2_repair(base):
+    return run(['par2', 'repair'] + parv(2) + ['--', base])
+
+def quick_verify(base):
+    f = open(base + '.pack', 'rb')
+    f.seek(-20, 2)
+    wantsum = f.read(20)
+    assert(len(wantsum) == 20)
+    f.seek(0)
+    sum = Sha1()
+    for b in chunkyreader(f, os.fstat(f.fileno()).st_size - 20):
+        sum.update(b)
+    if sum.digest() != wantsum:
+        raise ValueError('expected %r, got %r' % (wantsum.encode('hex'),
+                                                  sum.hexdigest()))
+        
 
+def git_verify(base):
+    if opt.quick:
+        try:
+            quick_verify(base)
+        except Exception, e:
+            debug('error: %s\n' % e)
+            return 1
+        return 0
+    else:
+        return run(['git', 'verify-pack', '--', base])
+    
+    
+def do_pack(base, last):
+    code = 0
+    if par2_ok and par2_exists and (opt.repair or not opt.generate):
+        vresult = par2_verify(base)
+        if vresult != 0:
+            if opt.repair:
+                rresult = par2_repair(base)
+                if rresult != 0:
+                    print '%s par2 repair: failed (%d)' % (last, rresult)
+                    code = rresult
+                else:
+                    print '%s par2 repair: succeeded (0)' % last
+                    code = 100
+            else:
+                print '%s par2 verify: failed (%d)' % (last, vresult)
+                code = vresult
+        else:
+            print '%s ok' % last
+    elif not opt.generate or (par2_ok and not par2_exists):
+        gresult = git_verify(base)
+        if gresult != 0:
+            print '%s git verify: failed (%d)' % (last, gresult)
+            code = gresult
+        else:
+            if par2_ok and opt.generate:
+                presult = par2_generate(base)
+                if presult != 0:
+                    print '%s par2 create: failed (%d)' % (last, presult)
+                    code = presult
+                else:
+                    print '%s ok' % last
+            else:
+                print '%s ok' % last
+    else:
+        assert(opt.generate and (not par2_ok or par2_exists))
+        debug('    skipped: par2 file already generated.\n')
+    return code
+
+
+optspec = """
+bup fsck [options...] [filenames...]
+--
+r,repair    attempt to repair errors using par2 (dangerous!)
+g,generate  generate auto-repair information using par2
+v,verbose   increase verbosity (can be used more than once)
+quick       just check pack sha1sum, don't use git verify-pack
+j,jobs=     run 'n' jobs in parallel
+par2-ok     immediately return 0 if par2 is ok, 1 if not
+disable-par2  ignore par2 even if it is available
+"""
+o = options.Options('bup fsck', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+par2_setup()
+if opt.par2_ok:
+    if par2_ok:
+        sys.exit(0)  # 'true' in sh
+    else:
+        sys.exit(1)
+if opt.disable_par2:
+    par2_ok = 0
+
+git.check_repo_or_die()
+
+if not extra:
+    debug('fsck: No filenames given: checking all packs.\n')
+    extra = glob.glob(git.repo('objects/pack/*.pack'))
+
+code = 0
+count = 0
+outstanding = {}
+for name in extra:
+    if name.endswith('.pack'):
+        base = name[:-5]
+    elif name.endswith('.idx'):
+        base = name[:-4]
+    elif name.endswith('.par2'):
+        base = name[:-5]
+    elif os.path.exists(name + '.pack'):
+        base = name
+    else:
+        raise Exception('%s is not a pack file!' % name)
+    (dir,last) = os.path.split(base)
+    par2_exists = os.path.exists(base + '.par2')
+    if par2_exists and os.stat(base + '.par2').st_size == 0:
+        par2_exists = 0
+    sys.stdout.flush()
+    debug('fsck: checking %s (%s)\n' 
+          % (last, par2_ok and par2_exists and 'par2' or 'git'))
+    if not opt.verbose:
+        progress('fsck (%d/%d)\r' % (count, len(extra)))
+    
+    if not opt.jobs:
+        nc = do_pack(base, last)
+        code = code or nc
+        count += 1
+    else:
+        while len(outstanding) >= opt.jobs:
+            (pid,nc) = os.wait()
+            nc >>= 8
+            if pid in outstanding:
+                del outstanding[pid]
+                code = code or nc
+                count += 1
+        pid = os.fork()
+        if pid:  # parent
+            outstanding[pid] = 1
+        else: # child
+            try:
+                sys.exit(do_pack(base, last))
+            except Exception, e:
+                log('exception: %r\n' % e)
+                sys.exit(99)
+                
+while len(outstanding):
+    (pid,nc) = os.wait()
+    nc >>= 8
+    if pid in outstanding:
+        del outstanding[pid]
+        code = code or nc
+        count += 1
+    if not opt.verbose:
+        progress('fsck (%d/%d)\r' % (count, len(extra)))
+
+if not opt.verbose and istty:
+    log('fsck done.           \n')
+sys.exit(code)
+#!/usr/bin/env python
+import sys, os, struct, getopt, subprocess, signal
+from bup import options, ssh
+from bup.helpers import *
+
+optspec = """
+bup rbackup <hostname> index ...
+bup rbackup <hostname> save ...
+bup rbackup <hostname> split ...
+"""
+o = options.Options('bup rbackup', optspec, optfunc=getopt.getopt)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+if len(extra) < 2:
+    o.fatal('arguments expected')
+
+class SigException(Exception):
+    def __init__(self, signum):
+        self.signum = signum
+        Exception.__init__(self, 'signal %d received' % signum)
+def handler(signum, frame):
+    raise SigException(signum)
+
+signal.signal(signal.SIGTERM, handler)
+signal.signal(signal.SIGINT, handler)
+
+sp = None
+p = None
+ret = 99
+
+try:
+    hostname = extra[0]
+    argv = extra[1:]
+    p = ssh.connect(hostname, 'rbackup-server')
+
+    argvs = '\0'.join(['bup'] + argv)
+    p.stdin.write(struct.pack('!I', len(argvs)) + argvs)
+    p.stdin.flush()
+
+    main_exe = os.environ.get('BUP_MAIN_EXE') or sys.argv[0]
+    sp = subprocess.Popen([main_exe, 'server'], stdin=p.stdout, stdout=p.stdin)
+
+    p.stdin.close()
+    p.stdout.close()
+
+finally:
+    while 1:
+        # if we get a signal while waiting, we have to keep waiting, just
+        # in case our child doesn't die.
+        try:
+            ret = p.wait()
+            sp.wait()
+            break
+        except SigException, e:
+            log('\nbup rbackup: %s\n' % e)
+            os.kill(p.pid, e.signum)
+            ret = 84
+sys.exit(ret)
+#!/usr/bin/env python
+import sys, os, re
+from bup import options
+
+optspec = """
+bup newliner
+"""
+o = options.Options('bup newliner', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if extra:
+    o.fatal("no arguments expected")
+
+r = re.compile(r'([\r\n])')
+lastlen = 0
+all = ''
+while 1:
+    l = r.split(all, 1)
+    if len(l) <= 1:
+        try:
+            b = os.read(sys.stdin.fileno(), 4096)
+        except KeyboardInterrupt:
+            break
+        if not b:
+            break
+        all += b
+    else:
+        assert(len(l) == 3)
+        (line, splitchar, all) = l
+        #splitchar = '\n'
+        sys.stdout.write('%-*s%s' % (lastlen, line, splitchar))
+        if splitchar == '\r':
+            lastlen = len(line)
+        else:
+            lastlen = 0
+        sys.stdout.flush()
+
+if lastlen or all:
+    sys.stdout.write('%-*s\n' % (lastlen, all))
+#!/usr/bin/env python
+import sys
+from bup import options, git, _hashsplit
+from bup.helpers import *
+
+
+optspec = """
+bup margin
+"""
+o = options.Options('bup margin', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if extra:
+    o.fatal("no arguments expected")
+
+git.check_repo_or_die()
+#git.ignore_midx = 1
+
+mi = git.PackIdxList(git.repo('objects/pack'))
+last = '\0'*20
+longmatch = 0
+for i in mi:
+    if i == last:
+        continue
+    #assert(str(i) >= last)
+    pm = _hashsplit.bitmatch(last, i)
+    longmatch = max(longmatch, pm)
+    last = i
+print longmatch
+#!/usr/bin/env python
+from bup import options, drecurse
+from bup.helpers import *
+
+optspec = """
+bup drecurse <path>
+--
+x,xdev,one-file-system   don't cross filesystem boundaries
+q,quiet  don't actually print filenames
+profile  run under the python profiler
+"""
+o = options.Options('bup drecurse', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if len(extra) != 1:
+    o.fatal("exactly one filename expected")
+
+it = drecurse.recursive_dirlist(extra, opt.xdev)
+if opt.profile:
+    import cProfile
+    def do_it():
+        for i in it:
+            pass
+    cProfile.run('do_it()')
+else:
+    if opt.quiet:
+        for i in it:
+            pass
+    else:
+        for (name,st) in it:
+            print name
+
+if saved_errors:
+    log('WARNING: %d errors encountered.\n' % len(saved_errors))
+    sys.exit(1)
+#!/usr/bin/env python
+import sys, time, struct
+from bup import hashsplit, git, options, client
+from bup.helpers import *
+from subprocess import PIPE
+
+
+optspec = """
+bup split [-tcb] [-n name] [--bench] [filenames...]
+--
+r,remote=  remote repository path
+b,blobs    output a series of blob ids
+t,tree     output a tree id
+c,commit   output a commit id
+n,name=    name of backup set to update (if any)
+N,noop     don't actually save the data anywhere
+q,quiet    don't print progress messages
+v,verbose  increase log output (can be used more than once)
+copy       just copy input to output, hashsplitting along the way
+bench      print benchmark timings to stderr
+max-pack-size=  maximum bytes in a single pack
+max-pack-objects=  maximum number of objects in a single pack
+fanout=  maximum number of blobs in a single tree
+"""
+o = options.Options('bup split', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+git.check_repo_or_die()
+if not (opt.blobs or opt.tree or opt.commit or opt.name or
+        opt.noop or opt.copy):
+    o.fatal("use one or more of -b, -t, -c, -n, -N, --copy")
+if (opt.noop or opt.copy) and (opt.blobs or opt.tree or 
+                               opt.commit or opt.name):
+    o.fatal('-N is incompatible with -b, -t, -c, -n')
+
+if opt.verbose >= 2:
+    git.verbose = opt.verbose - 1
+    opt.bench = 1
+if opt.max_pack_size:
+    hashsplit.max_pack_size = parse_num(opt.max_pack_size)
+if opt.max_pack_objects:
+    hashsplit.max_pack_objects = parse_num(opt.max_pack_objects)
+if opt.fanout:
+    hashsplit.fanout = parse_num(opt.fanout)
+if opt.blobs:
+    hashsplit.fanout = 0
+
+is_reverse = os.environ.get('BUP_SERVER_REVERSE')
+if is_reverse and opt.remote:
+    o.fatal("don't use -r in reverse mode; it's automatic")
+start_time = time.time()
+
+refname = opt.name and 'refs/heads/%s' % opt.name or None
+if opt.noop or opt.copy:
+    cli = w = oldref = None
+elif opt.remote or is_reverse:
+    cli = client.Client(opt.remote)
+    oldref = refname and cli.read_ref(refname) or None
+    w = cli.new_packwriter()
+else:
+    cli = None
+    oldref = refname and git.read_ref(refname) or None
+    w = git.PackWriter()
+
+files = extra and (open(fn) for fn in extra) or [sys.stdin]
+if w:
+    shalist = hashsplit.split_to_shalist(w, files)
+    tree = w.new_tree(shalist)
+else:
+    last = 0
+    for (blob, bits) in hashsplit.hashsplit_iter(files):
+        hashsplit.total_split += len(blob)
+        if opt.copy:
+            sys.stdout.write(str(blob))
+        megs = hashsplit.total_split/1024/1024
+        if not opt.quiet and last != megs:
+            progress('%d Mbytes read\r' % megs)
+            last = megs
+    progress('%d Mbytes read, done.\n' % megs)
+
+if opt.verbose:
+    log('\n')
+if opt.blobs:
+    for (mode,name,bin) in shalist:
+        print bin.encode('hex')
+if opt.tree:
+    print tree.encode('hex')
+if opt.commit or opt.name:
+    msg = 'bup split\n\nGenerated by command:\n%r' % sys.argv
+    ref = opt.name and ('refs/heads/%s' % opt.name) or None
+    commit = w.new_commit(oldref, tree, msg)
+    if opt.commit:
+        print commit.encode('hex')
+
+if w:
+    w.close()  # must close before we can update the ref
+        
+if opt.name:
+    if cli:
+        cli.update_ref(refname, commit, oldref)
+    else:
+        git.update_ref(refname, commit, oldref)
+
+if cli:
+    cli.close()
+
+secs = time.time() - start_time
+size = hashsplit.total_split
+if opt.bench:
+    log('\nbup: %.2fkbytes in %.2f secs = %.2f kbytes/sec\n'
+        % (size/1024., secs, size/1024./secs))
+#!/usr/bin/env python
+import sys, re, struct, mmap
+from bup import git, options
+from bup.helpers import *
+
+
+def s_from_bytes(bytes):
+    clist = [chr(b) for b in bytes]
+    return ''.join(clist)
+
+
+def report(count):
+    fields = ['VmSize', 'VmRSS', 'VmData', 'VmStk']
+    d = {}
+    for line in open('/proc/self/status').readlines():
+        l = re.split(r':\s*', line.strip(), 1)
+        d[l[0]] = l[1]
+    if count >= 0:
+        e1 = count
+        fields = [d[k] for k in fields]
+    else:
+        e1 = ''
+    print ('%9s  ' + ('%10s ' * len(fields))) % tuple([e1] + fields)
+    sys.stdout.flush()
+
+
+optspec = """
+bup memtest [-n elements] [-c cycles]
+--
+n,number=  number of objects per cycle
+c,cycles=  number of cycles to run
+ignore-midx  ignore .midx files, use only .idx files
+"""
+o = options.Options('bup memtest', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if extra:
+    o.fatal('no arguments expected')
+
+git.ignore_midx = opt.ignore_midx
+
+git.check_repo_or_die()
+m = git.PackIdxList(git.repo('objects/pack'))
+
+cycles = opt.cycles or 100
+number = opt.number or 10000
+
+report(-1)
+f = open('/dev/urandom')
+a = mmap.mmap(-1, 20)
+report(0)
+for c in xrange(cycles):
+    for n in xrange(number):
+        b = f.read(3)
+        if 0:
+            bytes = list(struct.unpack('!BBB', b)) + [0]*17
+            bytes[2] &= 0xf0
+            bin = struct.pack('!20s', s_from_bytes(bytes))
+        else:
+            a[0:2] = b[0:2]
+            a[2] = chr(ord(b[2]) & 0xf0)
+            bin = str(a[0:20])
+        #print bin.encode('hex')
+        m.exists(bin)
+    report((c+1)*number)
+#!/usr/bin/env python
+import sys, os, stat
+from bup import options, git, vfs
+from bup.helpers import *
+
+def print_node(text, n):
+    prefix = ''
+    if opt.hash:
+        prefix += "%s " % n.hash.encode('hex')
+    if stat.S_ISDIR(n.mode):
+        print '%s%s/' % (prefix, text)
+    elif stat.S_ISLNK(n.mode):
+        print '%s%s@' % (prefix, text)
+    else:
+        print '%s%s' % (prefix, text)
+
+
+optspec = """
+bup ls <dirs...>
+--
+s,hash   show hash for each file
+"""
+o = options.Options('bup ls', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+git.check_repo_or_die()
+top = vfs.RefList(None)
+
+if not extra:
+    extra = ['/']
+
+ret = 0
+for d in extra:
+    try:
+        n = top.lresolve(d)
+        if stat.S_ISDIR(n.mode):
+            for sub in n:
+                print_node(sub.name, sub)
+        else:
+            print_node(d, n)
+    except vfs.NodeError, e:
+        log('error: %s\n' % e)
+        ret = 1
+
+sys.exit(ret)
+#!/usr/bin/env python
+import sys, os, re, stat, readline, fnmatch
+from bup import options, git, shquote, vfs
+from bup.helpers import *
+
+def node_name(text, n):
+    if stat.S_ISDIR(n.mode):
+        return '%s/' % text
+    elif stat.S_ISLNK(n.mode):
+        return '%s@' % text
+    else:
+        return '%s' % text
+
+
+def do_ls(path, n):
+    l = []
+    if stat.S_ISDIR(n.mode):
+        for sub in n:
+            l.append(node_name(sub.name, sub))
+    else:
+        l.append(node_name(path, n))
+    print columnate(l, '')
+    
 
-do_stop () {
-       exec 9<&0 </proc/mounts
-       PROTECTED_MOUNTS="$(sed -n '0,/^\/[^ ]* \/ /p' /proc/mounts)"
-       WEAK_MTPTS="" #be gentle, don't use force
-       REG_MTPTS=""
-       TMPFS_MTPTS=""
-       while read DEV MTPT FSTYPE REST
-       do
-               echo "$PROTECTED_MOUNTS" | grep -qs "^$DEV $MTPT " && continue
-               case "$MTPT" in
-                       /|/proc|/dev|/.dev|/dev/pts|/dev/shm|/proc/*|/sys|/var/run|/var/lock)
-                       continue
-                       ;;
-               esac
-               case "$FSTYPE" in
-                       proc|procfs|linprocfs|devfs|sysfs|usbfs|usbdevfs|devpts|securityfs)
-                       continue
-                       ;;
-                 tmpfs)
-                       if [ -d "$MTPT" ]; then
-                               TMPFS_MTPTS="$TMPFS_MTPTS $MTPT"
-                       fi
-                       ;;
-                 *)
-                       REG_MTPTS="$REG_MTPTS $MTPT"
-                       if echo "$PROTECTED_MOUNTS" | grep -qs "^$DEV "; then
-                               WEAK_MTPTS="$WEAK_MTPTS $MTPT "
-                       fi
-                       ;;
-               esac
-       done
-
-       exec 0<&9 9<&-
-
-       #
-       # Make sure tmpfs file systems are umounted before turning off
-       # swap, to avoid running out of memory if the tmpfs filesystems
-       # use a lot of space.
-       #
-       if [ "$TMPFS_MTPTS" ]
-       then
-               if [ "$VERBOSE" = no ]
-               then
-                       log_action_begin_msg "Unmounting temporary filesystems"
-                       umount $TMPFS_MTPTS
-                       log_action_end_msg $?
-               else
-                       log_action_msg "Will now unmount temporary filesystems"
-                       umount -v $TMPFS_MTPTS
-                       ES=$?
-                       if [ "$ES" = 0 ]
-                       then
-                               log_success_msg "Done unmounting temporary filesystems."
-                       else
-                               log_failure_msg "Unmounting temporary filesystems failed with error code ${ES}."
-                       fi
-               fi
-       fi
-
-       #
-       # Deactivate swap
-       #
-       if [ "$VERBOSE" = no ]
-       then
-               log_action_begin_msg "Deactivating swap"
-               swapoff -a >/dev/null
-               log_action_end_msg $?
-       else
-               log_action_msg "Will now deactivate swap"
-               swapoff -a -v
-               ES=$?
-               if [ "$ES" = 0 ]
-               then
-                       log_success_msg "Done deactivating swap."
-               else
-                       log_failure_msg "Swap deactivation failed with error code ${ES}."
-               fi
-       fi
-
-       #
-       # Unmount local filesystems
-       #
-       [ -z "$REG_MTPTS" ] && return
-       [ "$VERBOSE" = no ] && log_action_begin_msg "Unmounting local filesystems"
-       REG_MTPTS="$(pioodl $REG_MTPTS)"
-       local ES2=0
-       for MTPT in $REG_MTPTS; do
-               if echo "$WEAK_MTPTS" | grep -qs " $MTPT "; then
-                       FORCE=""
-               else
-                       FORCE="-f"
-               fi
-               if [ "$VERBOSE" = no ]; then
-                       umount $FORCE -r -d $MTPT
-                       ES=$?
-                       [ "$ES" != 0 ] && [ "$ES2" = 0 ] && ES2=$ES
-               else
-                       log_action_begin_msg "Unmounting local filesystem $MTPT"
-                       umount $FORCE -v -r -d $MTPT
-                       ES=$?
-                       if [ "$ES" = 0 ]; then
-                               log_success_msg "Done unmounting local filesystem $MTPT."
-                       else
-                               log_failure_msg "Unmounting local filesystem $MTPT failed with error code $ES."
-                       fi
-               fi
-       done
-       [ "$VERBOSE" = no ] && log_action_end_msg $ES2
-}
+def write_to_file(inf, outf):
+    for blob in chunkyreader(inf):
+        outf.write(blob)
+    
 
-case "$1" in
-  start)
-       # No-op
-       ;;
-  restart|reload|force-reload)
-       echo "Error: argument '$1' not supported" >&2
-       exit 3
-       ;;
-  stop)
-       do_stop
-       ;;
-  *)
-       echo "Usage: $0 start|stop" >&2
-       exit 3
-       ;;
-esac
-
-:
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          umountnfs
-# Required-Start:    sendsigs
-# Required-Stop:
-# Default-Start:     6
-# Default-Stop:
-# Short-Description: Unmount all network filesystems except the root file system.
-# Description:       Also unmounts all virtual filesystems (proc, devfs, devpts,
-#                    usbfs, sysfs) that are not mounted at the top level.
-### END INIT INFO
-
-PATH=/usr/sbin:/usr/bin:/sbin:/bin
-KERNEL="$(uname -s)"
-RELEASE="$(uname -r)"
-. /lib/init/vars.sh
-
-. /lib/lsb/init-functions
-
-case "${KERNEL}:${RELEASE}" in
-  Linux:[01].*|Linux:2.[01].*)
-       FLAGS=""
-       ;;
-  Linux:2.[23].*|Linux:2.4.?|Linux:2.4.?-*|Linux:2.4.10|Linux:2.4.10-*)
-       FLAGS="-f"
-       ;;
-  *)
-       FLAGS="-f -l"
-       ;;
-esac
-
-do_stop () {
-       # Write a reboot record to /var/log/wtmp before unmounting
-       halt -w
-
-       # Remove bootclean flag files (precaution against symlink attacks)
-       rm -f /tmp/.clean /var/lock/.clean /var/run/.clean
-
-       [ "$VERBOSE" = no ] || log_action_begin_msg "Unmounting remote and non-toplevel virtual filesystems"
-
-       #
-       # Make list of points to unmount in reverse order of their creation
-       #
-
-       exec 9<&0 </proc/mounts
-
-       DIRS=""
-       while read DEV MTPT FSTYPE REST
-       do
-               case "$MTPT" in
-                 /|/proc|/dev|/dev/pts|/dev/shm|/proc/*|/sys|/var/run|/var/lock)
-                       continue
-                       ;;
-               esac
-               case "$FSTYPE" in
-                 nfs|nfs4|smbfs|ncp|ncpfs|cifs|coda|ocfs2|gfs)
-                       DIRS="$MTPT $DIRS"
-                       ;;
-                 proc|procfs|linprocfs|devfs|devpts|usbfs|usbdevfs|sysfs)
-                       DIRS="$MTPT $DIRS"
-                       ;;
-               esac
-       done
-
-       exec 0<&9 9<&-
-
-       if [ "$DIRS" ]
-       then
-               umount $FLAGS $DIRS
-       fi
-       ES=$?
-
-       [ "$VERBOSE" = no ] || log_action_end_msg $ES
-}
+def inputiter():
+    if os.isatty(sys.stdin.fileno()):
+        while 1:
+            try:
+                yield raw_input('bup> ')
+            except EOFError:
+                break
+    else:
+        for line in sys.stdin:
+            yield line
+
+
+def _completer_get_subs(line):
+    (qtype, lastword) = shquote.unfinished_word(line)
+    (dir,name) = os.path.split(lastword)
+    #log('\ncompleter: %r %r %r\n' % (qtype, lastword, text))
+    n = pwd.resolve(dir)
+    subs = list(filter(lambda x: x.name.startswith(name),
+                       n.subs()))
+    return (dir, name, qtype, lastword, subs)
+
+
+_last_line = None
+_last_res = None
+def completer(text, state):
+    global _last_line
+    global _last_res
+    try:
+        line = readline.get_line_buffer()[:readline.get_endidx()]
+        if _last_line != line:
+            _last_res = _completer_get_subs(line)
+            _last_line = line
+        (dir, name, qtype, lastword, subs) = _last_res
+        if state < len(subs):
+            sn = subs[state]
+            sn1 = sn.resolve('')  # deref symlinks
+            fullname = os.path.join(dir, sn.name)
+            if stat.S_ISDIR(sn1.mode):
+                ret = shquote.what_to_add(qtype, lastword, fullname+'/',
+                                          terminate=False)
+            else:
+                ret = shquote.what_to_add(qtype, lastword, fullname,
+                                          terminate=True) + ' '
+            return text + ret
+    except Exception, e:
+        log('\nerror in completion: %s\n' % e)
+
+            
+optspec = """
+bup ftp
+"""
+o = options.Options('bup ftp', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+git.check_repo_or_die()
+
+top = vfs.RefList(None)
+pwd = top
+
+if extra:
+    lines = extra
+else:
+    readline.set_completer_delims(' \t\n\r/')
+    readline.set_completer(completer)
+    readline.parse_and_bind("tab: complete")
+    lines = inputiter()
+
+for line in lines:
+    if not line.strip():
+        continue
+    words = [word for (wordstart,word) in shquote.quotesplit(line)]
+    cmd = words[0].lower()
+    #log('execute: %r %r\n' % (cmd, parm))
+    try:
+        if cmd == 'ls':
+            for parm in (words[1:] or ['.']):
+                do_ls(parm, pwd.resolve(parm))
+        elif cmd == 'cd':
+            for parm in words[1:]:
+                pwd = pwd.resolve(parm)
+        elif cmd == 'pwd':
+            print pwd.fullname()
+        elif cmd == 'cat':
+            for parm in words[1:]:
+                write_to_file(pwd.resolve(parm).open(), sys.stdout)
+        elif cmd == 'get':
+            if len(words) not in [2,3]:
+                raise Exception('Usage: get <filename> [localname]')
+            rname = words[1]
+            (dir,base) = os.path.split(rname)
+            lname = len(words)>2 and words[2] or base
+            inf = pwd.resolve(rname).open()
+            log('Saving %r\n' % lname)
+            write_to_file(inf, open(lname, 'wb'))
+        elif cmd == 'mget':
+            for parm in words[1:]:
+                (dir,base) = os.path.split(parm)
+                for n in pwd.resolve(dir).subs():
+                    if fnmatch.fnmatch(n.name, base):
+                        try:
+                            log('Saving %r\n' % n.name)
+                            inf = n.open()
+                            outf = open(n.name, 'wb')
+                            write_to_file(inf, outf)
+                            outf.close()
+                        except Exception, e:
+                            log('  error: %s\n' % e)
+        elif cmd == 'help' or cmd == '?':
+            log('Commands: ls cd pwd cat get mget help quit\n')
+        elif cmd == 'quit' or cmd == 'exit' or cmd == 'bye':
+            break
+        else:
+            raise Exception('no such command %r' % cmd)
+    except Exception, e:
+        log('error: %s\n' % e)
+        #raise
+#!/usr/bin/env python
+import sys, mmap
+from bup import options, _hashsplit
+from bup.helpers import *
+
+optspec = """
+bup random [-S seed] <numbytes>
+--
+S,seed=   optional random number seed (default 1)
+f,force   print random data to stdout even if it's a tty
+"""
+o = options.Options('bup random', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if len(extra) != 1:
+    o.fatal("exactly one argument expected")
+
+total = parse_num(extra[0])
+
+if opt.force or (not os.isatty(1) and
+                 not atoi(os.environ.get('BUP_FORCE_TTY')) & 1):
+    _hashsplit.write_random(sys.stdout.fileno(), total, opt.seed or 0)
+else:
+    log('error: not writing binary data to a terminal. Use -f to force.\n')
+    sys.exit(1)
+#!/usr/bin/env python
+import sys, os, glob
+from bup import options
+
+optspec = """
+bup help <command>
+"""
+o = options.Options('bup help', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if len(extra) == 0:
+    # the wrapper program provides the default usage string
+    os.execvp(os.environ['BUP_MAIN_EXE'], ['bup'])
+elif len(extra) == 1:
+    docname = (extra[0]=='bup' and 'bup' or ('bup-%s' % extra[0]))
+    exe = sys.argv[0]
+    (exepath, exefile) = os.path.split(exe)
+    manpath = os.path.join(exepath, '../Documentation/' + docname + '.[1-9]')
+    g = glob.glob(manpath)
+    if g:
+        os.execvp('man', ['man', '-l', g[0]])
+    else:
+        os.execvp('man', ['man', docname])
+else:
+    o.fatal("exactly one command name expected")
+#!/usr/bin/env python
+import sys, os, stat, errno, fuse, re, time, tempfile
+from bup import options, git, vfs
+from bup.helpers import *
+
+
+class Stat(fuse.Stat):
+    def __init__(self):
+        self.st_mode = 0
+        self.st_ino = 0
+        self.st_dev = 0
+        self.st_nlink = 0
+        self.st_uid = 0
+        self.st_gid = 0
+        self.st_size = 0
+        self.st_atime = 0
+        self.st_mtime = 0
+        self.st_ctime = 0
+        self.st_blocks = 0
+        self.st_blksize = 0
+        self.st_rdev = 0
+
+
+cache = {}
+def cache_get(top, path):
+    parts = path.split('/')
+    cache[('',)] = top
+    c = None
+    max = len(parts)
+    #log('cache: %r\n' % cache.keys())
+    for i in range(max):
+        pre = parts[:max-i]
+        #log('cache trying: %r\n' % pre)
+        c = cache.get(tuple(pre))
+        if c:
+            rest = parts[max-i:]
+            for r in rest:
+                #log('resolving %r from %r\n' % (r, c.fullname()))
+                c = c.lresolve(r)
+                key = tuple(pre + [r])
+                #log('saving: %r\n' % (key,))
+                cache[key] = c
+            break
+    assert(c)
+    return c
+        
+    
 
-case "$1" in
-  start)
-       # No-op
-       ;;
-  restart|reload|force-reload)
-       echo "Error: argument '$1' not supported" >&2
-       exit 3
-       ;;
-  stop|"")
-       do_stop
-       ;;
-  *)
-       echo "Usage: umountnfs.sh [start|stop]" >&2
-       exit 3
-       ;;
-esac
-
-:
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          umountroot
-# Required-Start:    umountfs
-# Required-Stop:     umountfs
-# Default-Start:     6
-# Default-Stop:
-# Short-Description: Mount the root filesystem read-only.
-### END INIT INFO
-
-PATH=/sbin:/bin
-. /lib/init/vars.sh
-
-. /lib/lsb/init-functions
-
-remount_ro () {
-       local MTPT=$1
-       [ "$VERBOSE" = no ] || log_action_begin_msg "Mounting $MTPT filesystem read-only"
-       MOUNT_FORCE_OPT=
-       [ "$(uname -s)" = "GNU/kFreeBSD" ] && MOUNT_FORCE_OPT=-f
-       # This:
-       #     mount -n -o remount,ro /
-       # will act on a bind mount of / if there is one.
-       # See #339023 and the comment in checkroot.sh
-       mount    $MOUNT_FORCE_OPT -n -o remount,ro -t dummytype dummydev $MTPT 2>/dev/null \
-       || mount $MOUNT_FORCE_OPT -n -o remount,ro              dummydev $MTPT 2>/dev/null \
-       || mount $MOUNT_FORCE_OPT -n -o remount,ro                       $MTPT
-       ES=$?
-       [ "$VERBOSE" = no ] || log_action_end_msg $ES
-}
+class BupFs(fuse.Fuse):
+    def __init__(self, top):
+        fuse.Fuse.__init__(self)
+        self.top = top
+    
+    def getattr(self, path):
+        log('--getattr(%r)\n' % path)
+        try:
+            node = cache_get(self.top, path)
+            st = Stat()
+            st.st_mode = node.mode
+            st.st_nlink = node.nlinks()
+            st.st_size = node.size()
+            st.st_mtime = node.mtime
+            st.st_ctime = node.ctime
+            st.st_atime = node.atime
+            return st
+        except vfs.NoSuchFile:
+            return -errno.ENOENT
+
+    def readdir(self, path, offset):
+        log('--readdir(%r)\n' % path)
+        node = cache_get(self.top, path)
+        yield fuse.Direntry('.')
+        yield fuse.Direntry('..')
+        for sub in node.subs():
+            yield fuse.Direntry(sub.name)
+
+    def readlink(self, path):
+        log('--readlink(%r)\n' % path)
+        node = cache_get(self.top, path)
+        return node.readlink()
+
+    def open(self, path, flags):
+        log('--open(%r)\n' % path)
+        node = cache_get(self.top, path)
+        accmode = os.O_RDONLY | os.O_WRONLY | os.O_RDWR
+        if (flags & accmode) != os.O_RDONLY:
+            return -errno.EACCES
+        node.open()
+
+    def release(self, path, flags):
+        log('--release(%r)\n' % path)
+
+    def read(self, path, size, offset):
+        log('--read(%r)\n' % path)
+        n = cache_get(self.top, path)
+        o = n.open()
+        o.seek(offset)
+        return o.read(size)
+
+
+if not hasattr(fuse, '__version__'):
+    raise RuntimeError, "your fuse module is too old for fuse.__version__"
+fuse.fuse_python_api = (0, 2)
+
+
+optspec = """
+bup fuse [-d] [-f] <mountpoint>
+--
+d,debug   increase debug level
+f,foreground  run in foreground
+"""
+o = options.Options('bup fuse', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if len(extra) != 1:
+    o.fatal("exactly one argument expected")
+
+git.check_repo_or_die()
+top = vfs.RefList(None)
+f = BupFs(top)
+f.fuse_args.mountpoint = extra[0]
+if opt.debug:
+    f.fuse_args.add('debug')
+if opt.foreground:
+    f.fuse_args.setmod('foreground')
+print f.multithreaded
+f.multithreaded = False
+
+f.main()
+#!/usr/bin/env python
+from bup import git, options, client
+from bup.helpers import *
+
+optspec = """
+[BUP_DIR=...] bup init [-r host:path]
+--
+r,remote=  remote repository path
+"""
+o = options.Options('bup init', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if extra:
+    o.fatal("no arguments expected")
+
+
+if opt.remote:
+    git.init_repo()  # local repo
+    git.check_repo_or_die()
+    cli = client.Client(opt.remote, create=True)
+    cli.close()
+else:
+    git.init_repo()
+#!/usr/bin/env python
+import sys, math, struct, glob
+from bup import options, git
+from bup.helpers import *
+
+PAGE_SIZE=4096
+SHA_PER_PAGE=PAGE_SIZE/200.
+
+
+def merge(idxlist, bits, table):
+    count = 0
+    for e in git.idxmerge(idxlist):
+        count += 1
+        prefix = git.extract_bits(e, bits)
+        table[prefix] = count
+        yield e
+
+
+def do_midx(outdir, outfilename, infilenames):
+    if not outfilename:
+        assert(outdir)
+        sum = Sha1('\0'.join(infilenames)).hexdigest()
+        outfilename = '%s/midx-%s.midx' % (outdir, sum)
+    
+    inp = []
+    total = 0
+    for name in infilenames:
+        ix = git.PackIdx(name)
+        inp.append(ix)
+        total += len(ix)
+
+    log('Merging %d indexes (%d objects).\n' % (len(infilenames), total))
+    if (not opt.force and (total < 1024 and len(infilenames) < 3)) \
+       or (opt.force and not total):
+        log('midx: nothing to do.\n')
+        return
+
+    pages = int(total/SHA_PER_PAGE) or 1
+    bits = int(math.ceil(math.log(pages, 2)))
+    entries = 2**bits
+    log('Table size: %d (%d bits)\n' % (entries*4, bits))
+    
+    table = [0]*entries
+
+    try:
+        os.unlink(outfilename)
+    except OSError:
+        pass
+    f = open(outfilename + '.tmp', 'w+')
+    f.write('MIDX\0\0\0\2')
+    f.write(struct.pack('!I', bits))
+    assert(f.tell() == 12)
+    f.write('\0'*4*entries)
+    
+    for e in merge(inp, bits, table):
+        f.write(e)
+        
+    f.write('\0'.join(os.path.basename(p) for p in infilenames))
+
+    f.seek(12)
+    f.write(struct.pack('!%dI' % entries, *table))
+    f.close()
+    os.rename(outfilename + '.tmp', outfilename)
+
+    # this is just for testing
+    if 0:
+        p = git.PackMidx(outfilename)
+        assert(len(p.idxnames) == len(infilenames))
+        print p.idxnames
+        assert(len(p) == total)
+        pi = iter(p)
+        for i in merge(inp, total, bits, table):
+            assert(i == pi.next())
+            assert(p.exists(i))
+
+    print outfilename
+
+optspec = """
+bup midx [options...] <idxnames...>
+--
+o,output=  output midx filename (default: auto-generated)
+a,auto     automatically create .midx from any unindexed .idx files
+f,force    automatically create .midx from *all* .idx files
+"""
+o = options.Options('bup midx', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if extra and (opt.auto or opt.force):
+    o.fatal("you can't use -f/-a and also provide filenames")
+
+git.check_repo_or_die()
+
+if extra:
+    do_midx(git.repo('objects/pack'), opt.output, extra)
+elif opt.auto or opt.force:
+    paths = [git.repo('objects/pack')]
+    paths += glob.glob(git.repo('index-cache/*/.'))
+    for path in paths:
+        log('midx: scanning %s\n' % path)
+        if opt.force:
+            do_midx(path, opt.output, glob.glob('%s/*.idx' % path))
+        elif opt.auto:
+            m = git.PackIdxList(path)
+            needed = {}
+            for pack in m.packs:  # only .idx files without a .midx are open
+                if pack.name.endswith('.idx'):
+                    needed[pack.name] = 1
+            del m
+            do_midx(path, opt.output, needed.keys())
+        log('\n')
+else:
+    o.fatal("you must use -f or -a or provide input filenames")
+#!/usr/bin/env python
+import sys, os, random
+from bup import options
+from bup.helpers import *
+
+
+def randblock(n):
+    l = []
+    for i in xrange(n):
+        l.append(chr(random.randrange(0,256)))
+    return ''.join(l)
+
+
+optspec = """
+bup damage [-n count] [-s maxsize] [-S seed] <filenames...>
+--
+   WARNING: THIS COMMAND IS EXTREMELY DANGEROUS
+n,num=   number of blocks to damage
+s,size=  maximum size of each damaged block
+percent= maximum size of each damaged block (as a percent of entire file)
+equal    spread damage evenly throughout the file
+S,seed=  random number seed (for repeatable tests)
+"""
+o = options.Options('bup damage', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if not extra:
+    o.fatal('filenames expected')
+
+if opt.seed != None:
+    random.seed(opt.seed)
+
+for name in extra:
+    log('Damaging "%s"...\n' % name)
+    f = open(name, 'r+b')
+    st = os.fstat(f.fileno())
+    size = st.st_size
+    if opt.percent or opt.size:
+        ms1 = int(float(opt.percent or 0)/100.0*size) or size
+        ms2 = opt.size or size
+        maxsize = min(ms1, ms2)
+    else:
+        maxsize = 1
+    chunks = opt.num or 10
+    chunksize = size/chunks
+    for r in range(chunks):
+        sz = random.randrange(1, maxsize+1)
+        if sz > size:
+            sz = size
+        if opt.equal:
+            ofs = r*chunksize
+        else:
+            ofs = random.randrange(0, size - sz + 1)
+        log('  %6d bytes at %d\n' % (sz, ofs))
+        f.seek(ofs)
+        f.write(randblock(sz))
+    f.close()
+#!/usr/bin/env python
+import sys, struct, mmap
+from bup import options, git
+from bup.helpers import *
+
+suspended_w = None
+
+
+def init_dir(conn, arg):
+    git.init_repo(arg)
+    log('bup server: bupdir initialized: %r\n' % git.repodir)
+    conn.ok()
+
+
+def set_dir(conn, arg):
+    git.check_repo_or_die(arg)
+    log('bup server: bupdir is %r\n' % git.repodir)
+    conn.ok()
 
-do_stop () {
-       # These directories must exist on the root filesystem as they are
-       # targets for system mountpoints.  We've just unmounted all other
-       # filesystems, so either they are mounted now (in which case the
-       # mount point exists) or we can make the mountpoint.
-       for dir in /proc /sys /var/run /var/lock; do
-           mkdir -p $dir || true
-       done
-       exec 9<&0 < /proc/mounts
-
-       REG_MTPTS=""
-       TMPFS_MTPTS=""
-       while read DEV MTPT FSTYPE REST
-       do
-               case "$MTPT" in
-                 /proc|/dev|/.dev|/dev/pts|/dev/shm|/proc/*|/sys|/var/run|/var/lock)
-                       continue
-                       ;;
-               esac
-               case "$FSTYPE" in 
-                 proc|procfs|linprocfs|devfs|sysfs|usbfs|usbdevfs|devpts|tmpfs)
-                       continue
-                       ;;
-                 *)
-                       remount_ro $MTPT
-                       ;;
-               esac
-       done
-
-       exec 0<&9 9<&-
+    
+def list_indexes(conn, junk):
+    git.check_repo_or_die()
+    for f in os.listdir(git.repo('objects/pack')):
+        if f.endswith('.idx'):
+            conn.write('%s\n' % f)
+    conn.ok()
+
+
+def send_index(conn, name):
+    git.check_repo_or_die()
+    assert(name.find('/') < 0)
+    assert(name.endswith('.idx'))
+    idx = git.PackIdx(git.repo('objects/pack/%s' % name))
+    conn.write(struct.pack('!I', len(idx.map)))
+    conn.write(idx.map)
+    conn.ok()
+
+
+def receive_objects(conn, junk):
+    global suspended_w
+    git.check_repo_or_die()
+    suggested = {}
+    if suspended_w:
+        w = suspended_w
+        suspended_w = None
+    else:
+        w = git.PackWriter()
+    while 1:
+        ns = conn.read(4)
+        if not ns:
+            w.abort()
+            raise Exception('object read: expected length header, got EOF\n')
+        n = struct.unpack('!I', ns)[0]
+        #log('expecting %d bytes\n' % n)
+        if not n:
+            log('bup server: received %d object%s.\n' 
+                % (w.count, w.count!=1 and "s" or ''))
+            fullpath = w.close()
+            if fullpath:
+                (dir, name) = os.path.split(fullpath)
+                conn.write('%s.idx\n' % name)
+            conn.ok()
+            return
+        elif n == 0xffffffff:
+            log('bup server: receive-objects suspended.\n')
+            suspended_w = w
+            conn.ok()
+            return
+            
+        buf = conn.read(n)  # object sizes in bup are reasonably small
+        #log('read %d bytes\n' % n)
+        if len(buf) < n:
+            w.abort()
+            raise Exception('object read: expected %d bytes, got %d\n'
+                            % (n, len(buf)))
+        (type, content) = git._decode_packobj(buf)
+        sha = git.calc_hash(type, content)
+        oldpack = w.exists(sha)
+        # FIXME: we only suggest a single index per cycle, because the client
+        # is currently dumb to download more than one per cycle anyway.
+        # Actually we should fix the client, but this is a minor optimization
+        # on the server side.
+        if not suggested and \
+          oldpack and (oldpack == True or oldpack.endswith('.midx')):
+            # FIXME: we shouldn't really have to know about midx files
+            # at this layer.  But exists() on a midx doesn't return the
+            # packname (since it doesn't know)... probably we should just
+            # fix that deficiency of midx files eventually, although it'll
+            # make the files bigger.  This method is certainly not very
+            # efficient.
+            w.objcache.refresh(skip_midx = True)
+            oldpack = w.objcache.exists(sha)
+            log('new suggestion: %r\n' % oldpack)
+            assert(oldpack)
+            assert(oldpack != True)
+            assert(not oldpack.endswith('.midx'))
+            w.objcache.refresh(skip_midx = False)
+        if not suggested and oldpack:
+            assert(oldpack.endswith('.idx'))
+            (dir,name) = os.path.split(oldpack)
+            if not (name in suggested):
+                log("bup server: suggesting index %s\n" % name)
+                conn.write('index %s\n' % name)
+                suggested[name] = 1
+        else:
+            w._raw_write([buf])
+    # NOTREACHED
+
+
+def read_ref(conn, refname):
+    git.check_repo_or_die()
+    r = git.read_ref(refname)
+    conn.write('%s\n' % (r or '').encode('hex'))
+    conn.ok()
+
+
+def update_ref(conn, refname):
+    git.check_repo_or_die()
+    newval = conn.readline().strip()
+    oldval = conn.readline().strip()
+    git.update_ref(refname, newval.decode('hex'), oldval.decode('hex'))
+    conn.ok()
+
+
+def cat(conn, id):
+    git.check_repo_or_die()
+    try:
+        for blob in git.cat(id):
+            conn.write(struct.pack('!I', len(blob)))
+            conn.write(blob)
+    except KeyError, e:
+        log('server: error: %s\n' % e)
+        conn.write('\0\0\0\0')
+        conn.error(e)
+    else:
+        conn.write('\0\0\0\0')
+        conn.ok()
+
+
+optspec = """
+bup server
+"""
+o = options.Options('bup server', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if extra:
+    o.fatal('no arguments expected')
+
+log('bup server: reading from stdin.\n')
+
+commands = {
+    'init-dir': init_dir,
+    'set-dir': set_dir,
+    'list-indexes': list_indexes,
+    'send-index': send_index,
+    'receive-objects': receive_objects,
+    'read-ref': read_ref,
+    'update-ref': update_ref,
+    'cat': cat,
 }
 
-case "$1" in
-  start)
-       # No-op
-       ;;
-  restart|reload|force-reload)
-       echo "Error: argument '$1' not supported" >&2
-       exit 3
-       ;;
-  stop)
-       do_stop
-       ;;
-  *)
-       echo "Usage: $0 start|stop" >&2
-       exit 3
-       ;;
-esac
-
-:
-#! /bin/sh
-#
-# skeleton     example file to build /etc/init.d/ scripts.
-#              This file should be used to construct scripts for /etc/init.d.
-#
-#              Written by Miquel van Smoorenburg <miquels@cistron.nl>.
-#              Modified for Debian 
-#              by Ian Murdock <imurdock@gnu.ai.mit.edu>.
+# FIXME: this protocol is totally lame and not at all future-proof.
+# (Especially since we abort completely as soon as *anything* bad happens)
+conn = Conn(sys.stdin, sys.stdout)
+lr = linereader(conn)
+for _line in lr:
+    line = _line.strip()
+    if not line:
+        continue
+    log('bup server: command: %r\n' % line)
+    words = line.split(' ', 1)
+    cmd = words[0]
+    rest = len(words)>1 and words[1] or ''
+    if cmd == 'quit':
+        break
+    else:
+        cmd = commands.get(cmd)
+        if cmd:
+            cmd(conn, rest)
+        else:
+            raise Exception('unknown server command: %r\n' % line)
+
+log('bup server: done\n')
+#!/usr/bin/env python
+import sys, time, struct
+from bup import hashsplit, git, options, client
+from bup.helpers import *
+from subprocess import PIPE
+
+
+optspec = """
+bup join [-r host:path] [refs or hashes...]
+--
+r,remote=  remote repository path
+"""
+o = options.Options('bup join', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+git.check_repo_or_die()
+
+if not extra:
+    extra = linereader(sys.stdin)
+
+ret = 0
+
+if opt.remote:
+    cli = client.Client(opt.remote)
+    cat = cli.cat
+else:
+    cp = git.CatPipe()
+    cat = cp.join
+
+for id in extra:
+    try:
+        for blob in cat(id):
+            sys.stdout.write(blob)
+    except KeyError, e:
+        sys.stdout.flush()
+        log('error: %s\n' % e)
+        ret = 1
+
+sys.exit(ret)
+#!/usr/bin/env python
+import sys, re, errno, stat, time, math
+from bup import hashsplit, git, options, index, client
+from bup.helpers import *
+
+
+optspec = """
+bup save [-tc] [-n name] <filenames...>
+--
+r,remote=  remote repository path
+t,tree     output a tree id
+c,commit   output a commit id
+n,name=    name of backup set to update (if any)
+v,verbose  increase log output (can be used more than once)
+q,quiet    don't show progress meter
+smaller=   only back up files smaller than n bytes
+"""
+o = options.Options('bup save', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+git.check_repo_or_die()
+if not (opt.tree or opt.commit or opt.name):
+    o.fatal("use one or more of -t, -c, -n")
+if not extra:
+    o.fatal("no filenames given")
+
+opt.progress = (istty and not opt.quiet)
+opt.smaller = parse_num(opt.smaller or 0)
+
+is_reverse = os.environ.get('BUP_SERVER_REVERSE')
+if is_reverse and opt.remote:
+    o.fatal("don't use -r in reverse mode; it's automatic")
+
+refname = opt.name and 'refs/heads/%s' % opt.name or None
+if opt.remote or is_reverse:
+    cli = client.Client(opt.remote)
+    oldref = refname and cli.read_ref(refname) or None
+    w = cli.new_packwriter()
+else:
+    cli = None
+    oldref = refname and git.read_ref(refname) or None
+    w = git.PackWriter()
+
+handle_ctrl_c()
+
+
+def eatslash(dir):
+    if dir.endswith('/'):
+        return dir[:-1]
+    else:
+        return dir
+
+
+parts = ['']
+shalists = [[]]
+
+def _push(part):
+    assert(part)
+    parts.append(part)
+    shalists.append([])
+
+def _pop(force_tree):
+    assert(len(parts) >= 1)
+    part = parts.pop()
+    shalist = shalists.pop()
+    tree = force_tree or w.new_tree(shalist)
+    if shalists:
+        shalists[-1].append(('40000', part, tree))
+    else:  # this was the toplevel, so put it back for sanity
+        shalists.append(shalist)
+    return tree
+
+lastremain = None
+def progress_report(n):
+    global count, subcount, lastremain
+    subcount += n
+    cc = count + subcount
+    pct = total and (cc*100.0/total) or 0
+    now = time.time()
+    elapsed = now - tstart
+    kps = elapsed and int(cc/1024./elapsed)
+    kps_frac = 10 ** int(math.log(kps+1, 10) - 1)
+    kps = int(kps/kps_frac)*kps_frac
+    if cc:
+        remain = elapsed*1.0/cc * (total-cc)
+    else:
+        remain = 0.0
+    if (lastremain and (remain > lastremain)
+          and ((remain - lastremain)/lastremain < 0.05)):
+        remain = lastremain
+    else:
+        lastremain = remain
+    hours = int(remain/60/60)
+    mins = int(remain/60 - hours*60)
+    secs = int(remain - hours*60*60 - mins*60)
+    if elapsed < 30:
+        remainstr = ''
+        kpsstr = ''
+    else:
+        kpsstr = '%dk/s' % kps
+        if hours:
+            remainstr = '%dh%dm' % (hours, mins)
+        elif mins:
+            remainstr = '%dm%d' % (mins, secs)
+        else:
+            remainstr = '%ds' % secs
+    progress('Saving: %.2f%% (%d/%dk, %d/%d files) %s %s\r'
+             % (pct, cc/1024, total/1024, fcount, ftotal,
+                remainstr, kpsstr))
+
+
+r = index.Reader(git.repo('bupindex'))
+
+def already_saved(ent):
+    return ent.is_valid() and w.exists(ent.sha) and ent.sha
+
+def wantrecurse_pre(ent):
+    return not already_saved(ent)
+
+def wantrecurse_during(ent):
+    return not already_saved(ent) or ent.sha_missing()
+
+total = ftotal = 0
+if opt.progress:
+    for (transname,ent) in r.filter(extra, wantrecurse=wantrecurse_pre):
+        if not (ftotal % 10024):
+            progress('Reading index: %d\r' % ftotal)
+        exists = ent.exists()
+        hashvalid = already_saved(ent)
+        ent.set_sha_missing(not hashvalid)
+        if not opt.smaller or ent.size < opt.smaller:
+            if exists and not hashvalid:
+                total += ent.size
+        ftotal += 1
+    progress('Reading index: %d, done.\n' % ftotal)
+    hashsplit.progress_callback = progress_report
+
+tstart = time.time()
+count = subcount = fcount = 0
+lastskip_name = None
+lastdir = ''
+for (transname,ent) in r.filter(extra, wantrecurse=wantrecurse_during):
+    (dir, file) = os.path.split(ent.name)
+    exists = (ent.flags & index.IX_EXISTS)
+    hashvalid = already_saved(ent)
+    wasmissing = ent.sha_missing()
+    oldsize = ent.size
+    if opt.verbose:
+        if not exists:
+            status = 'D'
+        elif not hashvalid:
+            if ent.sha == index.EMPTY_SHA:
+                status = 'A'
+            else:
+                status = 'M'
+        else:
+            status = ' '
+        if opt.verbose >= 2:
+            log('%s %-70s\n' % (status, ent.name))
+        elif not stat.S_ISDIR(ent.mode) and lastdir != dir:
+            if not lastdir.startswith(dir):
+                log('%s %-70s\n' % (status, os.path.join(dir, '')))
+            lastdir = dir
+
+    if opt.progress:
+        progress_report(0)
+    fcount += 1
+    
+    if not exists:
+        continue
+    if opt.smaller and ent.size >= opt.smaller:
+        if exists and not hashvalid:
+            add_error('skipping large file "%s"' % ent.name)
+            lastskip_name = ent.name
+        continue
+
+    assert(dir.startswith('/'))
+    dirp = dir.split('/')
+    while parts > dirp:
+        _pop(force_tree = None)
+    if dir != '/':
+        for part in dirp[len(parts):]:
+            _push(part)
+
+    if not file:
+        # no filename portion means this is a subdir.  But
+        # sub/parentdirectories already handled in the pop/push() part above.
+        oldtree = already_saved(ent) # may be None
+        newtree = _pop(force_tree = oldtree)
+        if not oldtree:
+            if lastskip_name and lastskip_name.startswith(ent.name):
+                ent.invalidate()
+            else:
+                ent.validate(040000, newtree)
+            ent.repack()
+        if exists and wasmissing:
+            count += oldsize
+        continue
+
+    # it's not a directory
+    id = None
+    if hashvalid:
+        mode = '%o' % ent.gitmode
+        id = ent.sha
+        shalists[-1].append((mode, 
+                             git.mangle_name(file, ent.mode, ent.gitmode),
+                             id))
+    else:
+        if stat.S_ISREG(ent.mode):
+            try:
+                f = hashsplit.open_noatime(ent.name)
+            except IOError, e:
+                add_error(e)
+                lastskip_name = ent.name
+            except OSError, e:
+                add_error(e)
+                lastskip_name = ent.name
+            else:
+                (mode, id) = hashsplit.split_to_blob_or_tree(w, [f])
+        else:
+            if stat.S_ISDIR(ent.mode):
+                assert(0)  # handled above
+            elif stat.S_ISLNK(ent.mode):
+                try:
+                    rl = os.readlink(ent.name)
+                except OSError, e:
+                    add_error(e)
+                    lastskip_name = ent.name
+                except IOError, e:
+                    add_error(e)
+                    lastskip_name = ent.name
+                else:
+                    (mode, id) = ('120000', w.new_blob(rl))
+            else:
+                add_error(Exception('skipping special file "%s"' % ent.name))
+                lastskip_name = ent.name
+        if id:
+            ent.validate(int(mode, 8), id)
+            ent.repack()
+            shalists[-1].append((mode,
+                                 git.mangle_name(file, ent.mode, ent.gitmode),
+                                 id))
+    if exists and wasmissing:
+        count += oldsize
+        subcount = 0
+
+
+if opt.progress:
+    pct = total and count*100.0/total or 100
+    progress('Saving: %.2f%% (%d/%dk, %d/%d files), done.    \n'
+             % (pct, count/1024, total/1024, fcount, ftotal))
+
+while len(parts) > 1:
+    _pop(force_tree = None)
+assert(len(shalists) == 1)
+tree = w.new_tree(shalists[-1])
+if opt.tree:
+    print tree.encode('hex')
+if opt.commit or opt.name:
+    msg = 'bup save\n\nGenerated by command:\n%r' % sys.argv
+    ref = opt.name and ('refs/heads/%s' % opt.name) or None
+    commit = w.new_commit(oldref, tree, msg)
+    if opt.commit:
+        print commit.encode('hex')
+
+w.close()  # must close before we can update the ref
+        
+if opt.name:
+    if cli:
+        cli.update_ref(refname, commit, oldref)
+    else:
+        git.update_ref(refname, commit, oldref)
+
+if cli:
+    cli.close()
+
+if saved_errors:
+    log('WARNING: %d errors encountered while saving.\n' % len(saved_errors))
+    sys.exit(1)
+#!/usr/bin/env python
+import sys, time
+from bup import options
+
+optspec = """
+bup tick
+"""
+o = options.Options('bup tick', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if extra:
+    o.fatal("no arguments expected")
+
+t = time.time()
+tleft = 1 - (t - int(t))
+time.sleep(tleft)
+#!/usr/bin/env python
+import os, sys, stat, time
+from bup import options, git, index, drecurse
+from bup.helpers import *
+
+
+def merge_indexes(out, r1, r2):
+    for e in index.MergeIter([r1, r2]):
+        # FIXME: shouldn't we remove deleted entries eventually?  When?
+        out.add_ixentry(e)
+
+
+class IterHelper:
+    def __init__(self, l):
+        self.i = iter(l)
+        self.cur = None
+        self.next()
+
+    def next(self):
+        try:
+            self.cur = self.i.next()
+        except StopIteration:
+            self.cur = None
+        return self.cur
+
+
+def check_index(reader):
+    try:
+        log('check: checking forward iteration...\n')
+        e = None
+        d = {}
+        for e in reader.forward_iter():
+            if e.children_n:
+                if opt.verbose:
+                    log('%08x+%-4d %r\n' % (e.children_ofs, e.children_n,
+                                            e.name))
+                assert(e.children_ofs)
+                assert(e.name.endswith('/'))
+                assert(not d.get(e.children_ofs))
+                d[e.children_ofs] = 1
+            if e.flags & index.IX_HASHVALID:
+                assert(e.sha != index.EMPTY_SHA)
+                assert(e.gitmode)
+        assert(not e or e.name == '/')  # last entry is *always* /
+        log('check: checking normal iteration...\n')
+        last = None
+        for e in reader:
+            if last:
+                assert(last > e.name)
+            last = e.name
+    except:
+        log('index error! at %r\n' % e)
+        raise
+    log('check: passed.\n')
+
+
+def update_index(top):
+    ri = index.Reader(indexfile)
+    wi = index.Writer(indexfile)
+    rig = IterHelper(ri.iter(name=top))
+    tstart = int(time.time())
+
+    hashgen = None
+    if opt.fake_valid:
+        def hashgen(name):
+            return (0100644, index.FAKE_SHA)
+
+    total = 0
+    for (path,pst) in drecurse.recursive_dirlist([top], xdev=opt.xdev):
+        if opt.verbose>=2 or (opt.verbose==1 and stat.S_ISDIR(pst.st_mode)):
+            sys.stdout.write('%s\n' % path)
+            sys.stdout.flush()
+            progress('Indexing: %d\r' % total)
+        elif not (total % 128):
+            progress('Indexing: %d\r' % total)
+        total += 1
+        while rig.cur and rig.cur.name > path:  # deleted paths
+            if rig.cur.exists():
+                rig.cur.set_deleted()
+                rig.cur.repack()
+            rig.next()
+        if rig.cur and rig.cur.name == path:    # paths that already existed
+            if pst:
+                rig.cur.from_stat(pst, tstart)
+            if not (rig.cur.flags & index.IX_HASHVALID):
+                if hashgen:
+                    (rig.cur.gitmode, rig.cur.sha) = hashgen(path)
+                    rig.cur.flags |= index.IX_HASHVALID
+            if opt.fake_invalid:
+                rig.cur.invalidate()
+            rig.cur.repack()
+            rig.next()
+        else:  # new paths
+            wi.add(path, pst, hashgen = hashgen)
+    progress('Indexing: %d, done.\n' % total)
+    
+    if ri.exists():
+        ri.save()
+        wi.flush()
+        if wi.count:
+            wr = wi.new_reader()
+            if opt.check:
+                log('check: before merging: oldfile\n')
+                check_index(ri)
+                log('check: before merging: newfile\n')
+                check_index(wr)
+            mi = index.Writer(indexfile)
+            merge_indexes(mi, ri, wr)
+            ri.close()
+            mi.close()
+            wr.close()
+        wi.abort()
+    else:
+        wi.close()
+
+
+optspec = """
+bup index <-p|m|u> [options...] <filenames...>
+--
+p,print    print the index entries for the given names (also works with -u)
+m,modified print only added/deleted/modified files (implies -p)
+s,status   print each filename with a status char (A/M/D) (implies -p)
+H,hash     print the hash for each object next to its name (implies -p)
+l,long     print more information about each file
+u,update   (recursively) update the index entries for the given filenames
+x,xdev,one-file-system  don't cross filesystem boundaries
+fake-valid mark all index entries as up-to-date even if they aren't
+fake-invalid mark all index entries as invalid
+check      carefully check index file integrity
+f,indexfile=  the name of the index file (default 'index')
+v,verbose  increase log output (can be used more than once)
+"""
+o = options.Options('bup index', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if not (opt.modified or opt['print'] or opt.status or opt.update or opt.check):
+    o.fatal('supply one or more of -p, -s, -m, -u, or --check')
+if (opt.fake_valid or opt.fake_invalid) and not opt.update:
+    o.fatal('--fake-{in,}valid are meaningless without -u')
+if opt.fake_valid and opt.fake_invalid:
+    o.fatal('--fake-valid is incompatible with --fake-invalid')
+
+git.check_repo_or_die()
+indexfile = opt.indexfile or git.repo('bupindex')
+
+handle_ctrl_c()
+
+if opt.check:
+    log('check: starting initial check.\n')
+    check_index(index.Reader(indexfile))
+
+paths = index.reduce_paths(extra)
+
+if opt.update:
+    if not paths:
+        o.fatal('update (-u) requested but no paths given')
+    for (rp,path) in paths:
+        update_index(rp)
+
+if opt['print'] or opt.status or opt.modified:
+    for (name, ent) in index.Reader(indexfile).filter(extra or ['']):
+        if (opt.modified 
+            and (ent.is_valid() or ent.is_deleted() or not ent.mode)):
+            continue
+        line = ''
+        if opt.status:
+            if ent.is_deleted():
+                line += 'D '
+            elif not ent.is_valid():
+                if ent.sha == index.EMPTY_SHA:
+                    line += 'A '
+                else:
+                    line += 'M '
+            else:
+                line += '  '
+        if opt.hash:
+            line += ent.sha.encode('hex') + ' '
+        if opt.long:
+            line += "%7s %7s " % (oct(ent.mode), oct(ent.gitmode))
+        print line + (name or './')
+
+if opt.check and (opt['print'] or opt.status or opt.modified or opt.update):
+    log('check: starting final check.\n')
+    check_index(index.Reader(indexfile))
+
+if saved_errors:
+    log('WARNING: %d errors encountered.\n' % len(saved_errors))
+    sys.exit(1)
+#!/usr/bin/env python
+import sys, os, struct
+from bup import options, helpers
+
+optspec = """
+bup rbackup-server
+--
+    This command is not intended to be run manually.
+"""
+o = options.Options('bup rbackup-server', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+if extra:
+    o.fatal('no arguments expected')
+
+# get the subcommand's argv.
+# Normally we could just pass this on the command line, but since we'll often
+# be getting called on the other end of an ssh pipe, which tends to mangle
+# argv (by sending it via the shell), this way is much safer.
+buf = sys.stdin.read(4)
+sz = struct.unpack('!I', buf)[0]
+assert(sz > 0)
+assert(sz < 1000000)
+buf = sys.stdin.read(sz)
+assert(len(buf) == sz)
+argv = buf.split('\0')
+
+# stdin/stdout are supposedly connected to 'bup server' that the caller
+# started for us (often on the other end of an ssh tunnel), so we don't want
+# to misuse them.  Move them out of the way, then replace stdout with
+# a pointer to stderr in case our subcommand wants to do something with it.
 #
-# Version:     @(#)skeleton  1.9  26-Feb-2001  miquels@cistron.nl
+# It might be nice to do the same with stdin, but my experiments showed that
+# ssh seems to make its child's stderr a readable-but-never-reads-anything
+# socket.  They really should have used shutdown(SHUT_WR) on the other end
+# of it, but probably didn't.  Anyway, it's too messy, so let's just make sure
+# anyone reading from stdin is disappointed.
 #
+# (You can't just leave stdin/stdout "not open" by closing the file
+# descriptors.  Then the next file that opens is automatically assigned 0 or 1,
+# and people *trying* to read/write stdin/stdout get screwed.)
+os.dup2(0, 3)
+os.dup2(1, 4)
+os.dup2(2, 1)
+fd = os.open('/dev/null', os.O_RDONLY)
+os.dup2(fd, 0)
+os.close(fd)
+
+os.environ['BUP_SERVER_REVERSE'] = helpers.hostname()
+os.execvp(argv[0], argv)
+sys.exit(99)
+#!/usr/bin/env python
+import sys, os, glob, subprocess, time
+from bup import options, git
+from bup.helpers import *
+
+par2_ok = 0
+nullf = open('/dev/null')
+
+def debug(s):
+    if opt.verbose:
+        log(s)
+
+def run(argv):
+    # at least in python 2.5, using "stdout=2" or "stdout=sys.stderr" below
+    # doesn't actually work, because subprocess closes fd #2 right before
+    # execing for some reason.  So we work around it by duplicating the fd
+    # first.
+    fd = os.dup(2)  # copy stderr
+    try:
+        p = subprocess.Popen(argv, stdout=fd, close_fds=False)
+        return p.wait()
+    finally:
+        os.close(fd)
+
+def par2_setup():
+    global par2_ok
+    rv = 1
+    try:
+        p = subprocess.Popen(['par2', '--help'],
+                             stdout=nullf, stderr=nullf, stdin=nullf)
+        rv = p.wait()
+    except OSError:
+        log('fsck: warning: par2 not found; disabling recovery features.\n')
+    else:
+        par2_ok = 1
+
+def parv(lvl):
+    if opt.verbose >= lvl:
+        if istty:
+            return []
+        else:
+            return ['-q']
+    else:
+        return ['-qq']
+
+def par2_generate(base):
+    return run(['par2', 'create', '-n1', '-c200'] + parv(2)
+               + ['--', base, base+'.pack', base+'.idx'])
+
+def par2_verify(base):
+    return run(['par2', 'verify'] + parv(3) + ['--', base])
+
+def par2_repair(base):
+    return run(['par2', 'repair'] + parv(2) + ['--', base])
+
+def quick_verify(base):
+    f = open(base + '.pack', 'rb')
+    f.seek(-20, 2)
+    wantsum = f.read(20)
+    assert(len(wantsum) == 20)
+    f.seek(0)
+    sum = Sha1()
+    for b in chunkyreader(f, os.fstat(f.fileno()).st_size - 20):
+        sum.update(b)
+    if sum.digest() != wantsum:
+        raise ValueError('expected %r, got %r' % (wantsum.encode('hex'),
+                                                  sum.hexdigest()))
+        
 
-PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
-DAEMON=/usr/sbin/uniconfd
-NAME=uniconfd
-DESC="UniConf daemon"
-
-test -x $DAEMON || exit 0
-
-# Include uniconf defaults if available
-if [ -f /etc/default/uniconfd ] ; then
-       . /etc/default/uniconfd
-fi
-
-DAEMON_OPTS="$UNICONFD_OPTS $UNICONFD_MOUNTS"
-
-case "$1" in
-  start)
-       echo -n "Starting $DESC: "
-       start-stop-daemon --start --quiet --pidfile /var/run/$NAME.pid \
-               --make-pidfile --background \
-               --exec $DAEMON -- -f $DAEMON_OPTS
-       if [ "$?" != "0" ]; then ERR=$?; echo; exit $ERR; fi
-       echo "$NAME."
-       ;;
-  stop)
-       echo -n "Stopping $DESC: "
-       start-stop-daemon --stop --quiet --pidfile /var/run/$NAME.pid \
-               --exec $DAEMON
-       if [ "$?" != "0" ]; then ERR=$?; echo; exit $ERR; fi
-       echo "$NAME."
-       ;;
-  #reload)
-       #
-       #       If the daemon can reload its config files on the fly
-       #       for example by sending it SIGHUP, do it here.
-       #
-       #       If the daemon responds to changes in its config file
-       #       directly anyway, make this a do-nothing entry.
-       #
-       # echo "Reloading $DESC configuration files."
-       # start-stop-daemon --stop --signal 1 --quiet --pidfile \
-       #       /var/run/$NAME.pid --exec $DAEMON
-  #;;
-  restart|force-reload)
-       #
-       #       If the "reload" option is implemented, move the "force-reload"
-       #       option to the "reload" entry above. If not, "force-reload" is
-       #       just the same as "restart".
-       #
-       echo -n "Restarting $DESC: "
-       start-stop-daemon --stop --quiet --pidfile \
-               /var/run/$NAME.pid --exec $DAEMON || exit $?
-       sleep 1
-       start-stop-daemon --start --quiet --pidfile \
-               /var/run/$NAME.pid --exec $DAEMON -- $DAEMON_OPTS
-       if [ "$?" != "0" ]; then ERR=$?; echo; exit $ERR; fi
-       echo "$NAME."
-       ;;
-  *)
-       N=/etc/init.d/$NAME
-       # echo "Usage: $N {start|stop|restart|reload|force-reload}" >&2
-       echo "Usage: $N {start|stop|restart|force-reload}" >&2
-       exit 1
-       ;;
-esac
-
-exit 0
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          urandom
-# Required-Start:    $local_fs
-# Required-Stop:     $local_fs
-# Default-Start:     S
-# Default-Stop:      0 6
-# Short-Description: Save and restore random seed between restarts.
-# Description        This script saves the random seed between restarts.
-#                    It is called from the boot, halt and reboot scripts.
-### END INIT INFO
-
-[ -c /dev/urandom ] || exit 0
-
-PATH=/usr/sbin:/usr/bin:/sbin:/bin
-SAVEDFILE=/var/lib/urandom/random-seed
-POOLSIZE=512
-[ -f /proc/sys/kernel/random/poolsize ] && POOLSIZE="$(cat /proc/sys/kernel/random/poolsize)"
-. /lib/init/vars.sh
-
-. /lib/lsb/init-functions
-
-case "$1" in
-  start|"")
-       [ "$VERBOSE" = no ] || log_action_begin_msg "Initializing random number generator"
-       # Load and then save $POOLSIZE bytes,
-       # which is the size of the entropy pool
-       if [ -f "$SAVEDFILE" ]
-       then
-               # Handle locally increased pool size
-               SAVEDSIZE="$(find "$SAVEDFILE" -printf "%s")"
-               if [ "$SAVEDSIZE" -gt "$POOLSIZE" ]
-               then
-                       [ -w /proc/sys/kernel/random/poolsize ] && echo $POOLSIZE > /proc/sys/kernel/random/poolsize
-                       POOLSIZE=$SAVEDSIZE
-               fi
-               cat "$SAVEDFILE" >/dev/urandom
-       fi
-       rm -f $SAVEDFILE
-       umask 077
-       dd if=/dev/urandom of=$SAVEDFILE bs=$POOLSIZE count=1 >/dev/null 2>&1
-       ES=$?
-       umask 022
-       [ "$VERBOSE" = no ] || log_action_end_msg $ES
-       ;;
-  stop)
-       # Carry a random seed from shut-down to start-up;
-       # see documentation in linux/drivers/char/random.c
-       [ "$VERBOSE" = no ] || log_action_begin_msg "Saving random seed"
-       umask 077
-       dd if=/dev/urandom of=$SAVEDFILE bs=$POOLSIZE count=1 >/dev/null 2>&1
-       ES=$?
-       [ "$VERBOSE" = no ] || log_action_end_msg $ES
-       ;;
-  restart|reload|force-reload)
-       echo "Error: argument '$1' not supported" >&2
-       exit 3
-       ;;
-  *)
-       echo "Usage: urandom start|stop" >&2
-       exit 3
-       ;;
-esac
-
-:
-#!/bin/sh
-
-test -x /usr/sbin/vbetool || exit 0
-set -e
-
-. /lib/lsb/init-functions
-
-test -f /etc/default/rcS && . /etc/default/rcS
-test -f /etc/default/acpi-support && . /etc/default/acpi-support
-test -f /usr/share/acpi-support/device-funcs && . /usr/share/acpi-support/device-funcs
-
-case "$1" in
- start)
-       if laptop-detect > /dev/null; then
-               LAPTOP=true;
-       fi
-
-       if [ x$LAPTOP != xtrue ]; then
-               exit 0;
-       fi
-
-        DeviceConfig
-       log_begin_msg "Saving VESA state..."
-       if [ "$SAVE_VBE_STATE" = "true" ]; then
-           if [ "$VERBOSE" = no ]; then 
-               if ! vbetool vbestate save > $VBESTATE 2>/dev/null; then
-                   log_end_msg $?
-                   exit 1
-               fi
-           else
-               if ! vbetool vbestate save > $VBESTATE ; then
-                   log_end_msg $?
-                   exit 1
-               fi
-           fi
-           log_end_msg 0
-        fi
-        ;;
- *)
-        exit 0
-        ;;
-esac
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          waitnfs
-# Required-Start:    $network $local_fs
-# Required-Stop:
-# Default-Start:     S
-# Default-Stop:
-# Short-Description: Wait for critical network file systems to be mounted
-# Description:       Network file systems are mounted in the background when
-#                    interfaces are brought up; this script waits for
-#                    those among them which are critical for booting to be
-#                    mounted before carrying on.
-#                    Specifically, it will wait for file systems mounted
-#                    on /usr, /usr/*, /var, /var/* 
-#                    This script WILL NOT wait on other network file which are
-#                    mounted elsewhere!
-### END INIT INFO
-
-[ -f /etc/default/rcS ] && . /etc/default/rcS
-. /lib/lsb/init-functions
-
-do_start() {
-       [ -f /etc/fstab ] || return
-       #
-       # Read through fstab line by line, building a list of networked
-       # file systems mounted on /usr* or /var*
-       # Wait up to a fixed period of time for these file systems to mount
-       #
-
-       exec 9<&0 </etc/fstab
-
-       waitnfs=
-       while read DEV MTPT FSTYPE OPTS REST
-       do
-               case "$DEV" in
-                 ""|\#*)
-                       continue
-                       ;;
-               esac
-               case "$OPTS" in
-                 noauto|*,noauto|noauto,*|*,noauto,*)
-                       continue
-                       ;;
-               esac
-               case "$FSTYPE" in
-                 nfs|nfs4|smbfs|cifs|coda|ncp|ncpfs|ocfs2|gfs)
-                       ;;
-                 *)
-                       continue
-                       ;;
-               esac
-               case "$MTPT" in
-                 /usr/local|/usr/local/*)
-                       ;;
-                 /usr|/usr/*)
-                       waitnfs="$waitnfs $MTPT"
-                       ;;
-                 /var|/var/*)
-                       waitnfs="$waitnfs $MTPT"
-                       ;;
-               esac
-       done
-
-       exec 0<&9 9<&-
-
-       # Try mounting all networked filesystems here, just before waiting for
-       # them; background this call so as not to block startup sequence
-       /lib/init/mountall-net-fs &
-
-       # Wait for each path, the timeout is for all of them as that's
-       # really the maximum time we have to wait anyway
-       TIMEOUT=900
-       for mountpt in $waitnfs; do
-               log_action_begin_msg "Waiting for $mountpt"
-
-               while ! mountpoint -q $mountpt; do
-                       sleep 0.1
-
-                       TIMEOUT=$(( $TIMEOUT - 1 ))
-                       if [ $TIMEOUT -le 0 ]; then
-                               log_action_end_msg 1
-                               break
-                       fi
-               done
-
-               if [ $TIMEOUT -gt 0 ]; then
-                       log_action_end_msg 0
-               fi
-       done
-}
-
-case "$1" in
-    start)
-        do_start
-        ;;
-    restart|reload|force-reload)
-        echo "Error: argument '$1' not supported" >&2
-        exit 3
-        ;;
-    stop)
-        ;;
-    *)
-        echo "Usage: $0 start|stop" >&2
-        exit 3
-        ;;
-esac
-
-: exit 0
-#!/bin/sh
-
-### BEGIN INIT INFO
-# Provides:          winbind
-# Required-Start:    $network $local_fs $remote_fs
-# Required-Stop:     $network $local_fs $remote_fs
-# Default-Start:     2 3 4 5
-# Default-Stop:      0 1 6
-# Short-Description: start Winbind daemon
-### END INIT INFO
-
-
-PATH=/sbin:/bin:/usr/sbin:/usr/bin
-
-[ -r /etc/default/winbind ] && . /etc/default/winbind
-
-DAEMON=/usr/sbin/winbindd
-PIDDIR=/var/run/samba
-
-# clear conflicting settings from the environment
-unset TMPDIR
-
-# See if the daemon is there
-test -x $DAEMON || exit 0
-
-. /lib/lsb/init-functions
-
-case "$1" in
-       start)
-               log_daemon_msg "Starting the Winbind daemon" "winbind"
-
-               mkdir -p /var/run/samba/winbindd_privileged || return 1
-               chgrp winbindd_priv $PIDDIR/winbindd_privileged/ || return 1
-               chmod 0750 $PIDDIR/winbindd_privileged/ || return 1
-               start-stop-daemon --start --quiet --oknodo --exec $DAEMON -- $WINBINDD_OPTS
-
-               log_end_msg $?
-               ;;
-
-       stop)
-               log_daemon_msg "Stopping the Winbind daemon" "winbind"
-               start-stop-daemon --stop --quiet --oknodo --exec $DAEMON
-               log_end_msg $?
-               ;;
-
-       restart|force-reload)
-               $0 stop && sleep 2 && $0 start
-               ;;
-
-       *)
-               echo "Usage: /etc/init.d/winbind {start|stop|restart|force-reload}"
-               exit 1
-               ;;
-esac
-#!/bin/sh
-
-### BEGIN INIT INFO
-# Provides:            wpa-ifupdown
-# Required-Start:      $network
-# Required-Stop:       $network
-# Should-Start:
-# Should-Stop:
-# Default-Start:
-# Default-Stop:                0 6
-# Short-Description:   Stop wpa_supplicant processes started via ifupdown
-# Description:         Run ifdown on interfaces authenticated via
-#                      wpa_supplicant. Sendsigs terminates wpa_supplicant
-#                      processes before networking is stopped causing each
-#                      network interface authenticated via a wpa_supplicant
-#                      daemon to be terminated abrubtly.
-### END INIT INFO
-
-PATH=/usr/sbin:/usr/bin:/sbin:/bin
-
-test -d /var/run || exit 0
-
-test -x /sbin/ifdown || exit 0
-
-. /lib/lsb/init-functions
-
-stop_wpa_action () {
-       test -x /sbin/wpa_action || return
-       unset IFACES
-       IFACES=$(find /var/run -maxdepth 1 -type f -name 'wpa_action.*.pid' -printf '%P\n' | cut -d'.' -f2)
-       if test -n "$IFACES"; then
-               log_daemon_msg "Stopping wpa_action roaming interfaces"
-               for iface in $IFACES; do
-                       log_progress_msg "$iface"
-                       # wpa_action executes /sbin/ifdown
-                       wpa_action "$iface" stop >/dev/null 2>&1
-               done
-               log_end_msg 0
-       fi
-}
-
-stop_wpa_supplicant () {
-       unset IFACES
-       IFACES=$(find /var/run -maxdepth 1 -type f -name 'wpa_supplicant.*.pid' -printf '%P\n' | cut -d'.' -f2)
-       if test -n "$IFACES"; then
-               log_daemon_msg "Stopping wpa_supplicant interfaces"
-               for iface in $IFACES; do
-                       log_progress_msg "$iface"
-                       ifdown $iface >/dev/null 2>&1
-               done
-               log_end_msg 0
-       fi
-}
-
-case "$1" in
-       start|restart|force-reload)
-               # No-op
-               ;;
-       stop)
-               stop_wpa_action
-               stop_wpa_supplicant
-               ;;
-       *)
-               echo "Usage: $0 {start|stop|restart|force-reload}" >&2
-               exit 3
-               ;;
-esac
-
-exit 0
-#!/bin/sh
-# /etc/init.d/x11-common: set up the X server and ICE socket directories
-### BEGIN INIT INFO
-# Provides:          x11-common
-# Required-Start:    $local_fs $remote_fs
-# Required-Stop:     $local_fs $remote_fs
-# Should-Start:      $named
-# Should-Stop:       $named
-# Default-Start:     S
-# Default-Stop:
-### END INIT INFO
-
-set -e
-
-PATH=/bin:/usr/bin:/sbin:/usr/sbin
-SOCKET_DIR=/tmp/.X11-unix
-ICE_DIR=/tmp/.ICE-unix
-
-. /lib/lsb/init-functions
-if [ -f /etc/default/rcS ]; then
-  . /etc/default/rcS
-fi
-
-do_restorecon () {
-  # Restore file security context (SELinux).
-  if which restorecon >/dev/null 2>&1; then
-    restorecon "$1"
-  fi
-}
-
-set_up_socket_dir () {
-  if [ "$VERBOSE" != no ]; then
-    log_begin_msg "Setting up X server socket directory $SOCKET_DIR..."
-  fi
-  if [ -e $SOCKET_DIR ] && [ ! -d $SOCKET_DIR ]; then
-    mv $SOCKET_DIR $SOCKET_DIR.$$
-  fi
-  mkdir -p $SOCKET_DIR
-  chown 0:0 $SOCKET_DIR
-  chmod 1777 $SOCKET_DIR
-  do_restorecon $SOCKET_DIR
-  [ "$VERBOSE" != no ] && log_end_msg 0 || return 0
-}
-
-set_up_ice_dir () {
-  if [ "$VERBOSE" != no ]; then
-    log_begin_msg "Setting up ICE socket directory $ICE_DIR..."
-  fi
-  if [ -e $ICE_DIR ] && [ ! -d $ICE_DIR ]; then
-    mv $ICE_DIR $ICE_DIR.$$
-  fi
-  mkdir -p $ICE_DIR
-  chown 0:0 $ICE_DIR
-  chmod 1777 $ICE_DIR
-  do_restorecon $ICE_DIR
-  [ "$VERBOSE" != no ] && log_end_msg 0 || return 0
-}
-
-do_status () {
-    if [ -d $ICE_DIR ] && [ -d $SOCKET_DIR ]; then
-      return 0
-    else
-      return 4
-    fi
-}
-
-case "$1" in
-  start)
-    set_up_socket_dir
-    set_up_ice_dir
-  ;;
-
-  restart|reload|force-reload)
-    /etc/init.d/x11-common start
-  ;;
-
-  stop)
-   :
-  ;;
-
-  status)
-    do_status
-  ;;
-  *)
-    log_success_msg "Usage: /etc/init.d/x11-common {start|stop|status|restart|reload|force-reload}"
-    exit 1
-    ;;
-esac
-
-exit 0
-
-# vim:set ai et sts=2 sw=2 tw=0:
+def git_verify(base):
+    if opt.quick:
+        try:
+            quick_verify(base)
+        except Exception, e:
+            debug('error: %s\n' % e)
+            return 1
+        return 0
+    else:
+        return run(['git', 'verify-pack', '--', base])
+    
+    
+def do_pack(base, last):
+    code = 0
+    if par2_ok and par2_exists and (opt.repair or not opt.generate):
+        vresult = par2_verify(base)
+        if vresult != 0:
+            if opt.repair:
+                rresult = par2_repair(base)
+                if rresult != 0:
+                    print '%s par2 repair: failed (%d)' % (last, rresult)
+                    code = rresult
+                else:
+                    print '%s par2 repair: succeeded (0)' % last
+                    code = 100
+            else:
+                print '%s par2 verify: failed (%d)' % (last, vresult)
+                code = vresult
+        else:
+            print '%s ok' % last
+    elif not opt.generate or (par2_ok and not par2_exists):
+        gresult = git_verify(base)
+        if gresult != 0:
+            print '%s git verify: failed (%d)' % (last, gresult)
+            code = gresult
+        else:
+            if par2_ok and opt.generate:
+                presult = par2_generate(base)
+                if presult != 0:
+                    print '%s par2 create: failed (%d)' % (last, presult)
+                    code = presult
+                else:
+                    print '%s ok' % last
+            else:
+                print '%s ok' % last
+    else:
+        assert(opt.generate and (not par2_ok or par2_exists))
+        debug('    skipped: par2 file already generated.\n')
+    return code
+
+
+optspec = """
+bup fsck [options...] [filenames...]
+--
+r,repair    attempt to repair errors using par2 (dangerous!)
+g,generate  generate auto-repair information using par2
+v,verbose   increase verbosity (can be used more than once)
+quick       just check pack sha1sum, don't use git verify-pack
+j,jobs=     run 'n' jobs in parallel
+par2-ok     immediately return 0 if par2 is ok, 1 if not
+disable-par2  ignore par2 even if it is available
+"""
+o = options.Options('bup fsck', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+par2_setup()
+if opt.par2_ok:
+    if par2_ok:
+        sys.exit(0)  # 'true' in sh
+    else:
+        sys.exit(1)
+if opt.disable_par2:
+    par2_ok = 0
+
+git.check_repo_or_die()
+
+if not extra:
+    debug('fsck: No filenames given: checking all packs.\n')
+    extra = glob.glob(git.repo('objects/pack/*.pack'))
+
+code = 0
+count = 0
+outstanding = {}
+for name in extra:
+    if name.endswith('.pack'):
+        base = name[:-5]
+    elif name.endswith('.idx'):
+        base = name[:-4]
+    elif name.endswith('.par2'):
+        base = name[:-5]
+    elif os.path.exists(name + '.pack'):
+        base = name
+    else:
+        raise Exception('%s is not a pack file!' % name)
+    (dir,last) = os.path.split(base)
+    par2_exists = os.path.exists(base + '.par2')
+    if par2_exists and os.stat(base + '.par2').st_size == 0:
+        par2_exists = 0
+    sys.stdout.flush()
+    debug('fsck: checking %s (%s)\n' 
+          % (last, par2_ok and par2_exists and 'par2' or 'git'))
+    if not opt.verbose:
+        progress('fsck (%d/%d)\r' % (count, len(extra)))
+    
+    if not opt.jobs:
+        nc = do_pack(base, last)
+        code = code or nc
+        count += 1
+    else:
+        while len(outstanding) >= opt.jobs:
+            (pid,nc) = os.wait()
+            nc >>= 8
+            if pid in outstanding:
+                del outstanding[pid]
+                code = code or nc
+                count += 1
+        pid = os.fork()
+        if pid:  # parent
+            outstanding[pid] = 1
+        else: # child
+            try:
+                sys.exit(do_pack(base, last))
+            except Exception, e:
+                log('exception: %r\n' % e)
+                sys.exit(99)
+                
+while len(outstanding):
+    (pid,nc) = os.wait()
+    nc >>= 8
+    if pid in outstanding:
+        del outstanding[pid]
+        code = code or nc
+        count += 1
+    if not opt.verbose:
+        progress('fsck (%d/%d)\r' % (count, len(extra)))
+
+if not opt.verbose and istty:
+    log('fsck done.           \n')
+sys.exit(code)
+#!/usr/bin/env python
+import sys, os, struct, getopt, subprocess, signal
+from bup import options, ssh
+from bup.helpers import *
+
+optspec = """
+bup rbackup <hostname> index ...
+bup rbackup <hostname> save ...
+bup rbackup <hostname> split ...
+"""
+o = options.Options('bup rbackup', optspec, optfunc=getopt.getopt)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+if len(extra) < 2:
+    o.fatal('arguments expected')
+
+class SigException(Exception):
+    def __init__(self, signum):
+        self.signum = signum
+        Exception.__init__(self, 'signal %d received' % signum)
+def handler(signum, frame):
+    raise SigException(signum)
+
+signal.signal(signal.SIGTERM, handler)
+signal.signal(signal.SIGINT, handler)
+
+sp = None
+p = None
+ret = 99
+
+try:
+    hostname = extra[0]
+    argv = extra[1:]
+    p = ssh.connect(hostname, 'rbackup-server')
+
+    argvs = '\0'.join(['bup'] + argv)
+    p.stdin.write(struct.pack('!I', len(argvs)) + argvs)
+    p.stdin.flush()
+
+    main_exe = os.environ.get('BUP_MAIN_EXE') or sys.argv[0]
+    sp = subprocess.Popen([main_exe, 'server'], stdin=p.stdout, stdout=p.stdin)
+
+    p.stdin.close()
+    p.stdout.close()
+
+finally:
+    while 1:
+        # if we get a signal while waiting, we have to keep waiting, just
+        # in case our child doesn't die.
+        try:
+            ret = p.wait()
+            sp.wait()
+            break
+        except SigException, e:
+            log('\nbup rbackup: %s\n' % e)
+            os.kill(p.pid, e.signum)
+            ret = 84
+sys.exit(ret)
+#!/usr/bin/env python
+import sys, os, re
+from bup import options
+
+optspec = """
+bup newliner
+"""
+o = options.Options('bup newliner', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if extra:
+    o.fatal("no arguments expected")
+
+r = re.compile(r'([\r\n])')
+lastlen = 0
+all = ''
+while 1:
+    l = r.split(all, 1)
+    if len(l) <= 1:
+        try:
+            b = os.read(sys.stdin.fileno(), 4096)
+        except KeyboardInterrupt:
+            break
+        if not b:
+            break
+        all += b
+    else:
+        assert(len(l) == 3)
+        (line, splitchar, all) = l
+        #splitchar = '\n'
+        sys.stdout.write('%-*s%s' % (lastlen, line, splitchar))
+        if splitchar == '\r':
+            lastlen = len(line)
+        else:
+            lastlen = 0
+        sys.stdout.flush()
+
+if lastlen or all:
+    sys.stdout.write('%-*s\n' % (lastlen, all))
+#!/usr/bin/env python
+import sys
+from bup import options, git, _hashsplit
+from bup.helpers import *
+
+
+optspec = """
+bup margin
+"""
+o = options.Options('bup margin', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if extra:
+    o.fatal("no arguments expected")
+
+git.check_repo_or_die()
+#git.ignore_midx = 1
+
+mi = git.PackIdxList(git.repo('objects/pack'))
+last = '\0'*20
+longmatch = 0
+for i in mi:
+    if i == last:
+        continue
+    #assert(str(i) >= last)
+    pm = _hashsplit.bitmatch(last, i)
+    longmatch = max(longmatch, pm)
+    last = i
+print longmatch
index 2d0bdf9e6f516ccf2bccf18c0b2013f8c165154b..f6f0e0c3c84b69d48ad44583ae8e0527449ada02 100644 (file)
-#! /bin/sh -e
-
-# Check for daemon presence
-test -x /usr/sbin/acpid || exit 0
-
-# Check for ACPI support on kernel side
-[ -d /proc/acpi ] || exit 0
-
-# Include acpid defaults if available
-OPTIONS=""
-if [ -f /etc/default/acpid ] ; then
-       . /etc/default/acpid
-fi
-
-# Get lsb functions
-. /lib/lsb/init-functions
-. /etc/default/rcS
-
-if [ "x$VERBOSE" = "xno" ]; then
-        MODPROBE_OPTIONS="$MODPROBE_OPTIONS -Q"
-        export MODPROBE_OPTIONS
-fi
-
-# As the name says. If the kernel supports modules, it'll try to load
-# the ones listed in "MODULES".
-load_modules() {
-        PRINTK=`cat /proc/sys/kernel/printk`
-        [ "$VERBOSE" = no ] && echo "0 0 0 0" > /proc/sys/kernel/printk
+#!/usr/bin/env python
+from bup import options, drecurse
+from bup.helpers import *
+
+optspec = """
+bup drecurse <path>
+--
+x,xdev,one-file-system   don't cross filesystem boundaries
+q,quiet  don't actually print filenames
+profile  run under the python profiler
+"""
+o = options.Options('bup drecurse', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if len(extra) != 1:
+    o.fatal("exactly one filename expected")
+
+it = drecurse.recursive_dirlist(extra, opt.xdev)
+if opt.profile:
+    import cProfile
+    def do_it():
+        for i in it:
+            pass
+    cProfile.run('do_it()')
+else:
+    if opt.quiet:
+        for i in it:
+            pass
+    else:
+        for (name,st) in it:
+            print name
+
+if saved_errors:
+    log('WARNING: %d errors encountered.\n' % len(saved_errors))
+    sys.exit(1)
+#!/usr/bin/env python
+import sys, time, struct
+from bup import hashsplit, git, options, client
+from bup.helpers import *
+from subprocess import PIPE
+
+
+optspec = """
+bup split [-tcb] [-n name] [--bench] [filenames...]
+--
+r,remote=  remote repository path
+b,blobs    output a series of blob ids
+t,tree     output a tree id
+c,commit   output a commit id
+n,name=    name of backup set to update (if any)
+N,noop     don't actually save the data anywhere
+q,quiet    don't print progress messages
+v,verbose  increase log output (can be used more than once)
+copy       just copy input to output, hashsplitting along the way
+bench      print benchmark timings to stderr
+max-pack-size=  maximum bytes in a single pack
+max-pack-objects=  maximum number of objects in a single pack
+fanout=  maximum number of blobs in a single tree
+"""
+o = options.Options('bup split', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+git.check_repo_or_die()
+if not (opt.blobs or opt.tree or opt.commit or opt.name or
+        opt.noop or opt.copy):
+    o.fatal("use one or more of -b, -t, -c, -n, -N, --copy")
+if (opt.noop or opt.copy) and (opt.blobs or opt.tree or 
+                               opt.commit or opt.name):
+    o.fatal('-N is incompatible with -b, -t, -c, -n')
+
+if opt.verbose >= 2:
+    git.verbose = opt.verbose - 1
+    opt.bench = 1
+if opt.max_pack_size:
+    hashsplit.max_pack_size = parse_num(opt.max_pack_size)
+if opt.max_pack_objects:
+    hashsplit.max_pack_objects = parse_num(opt.max_pack_objects)
+if opt.fanout:
+    hashsplit.fanout = parse_num(opt.fanout)
+if opt.blobs:
+    hashsplit.fanout = 0
+
+is_reverse = os.environ.get('BUP_SERVER_REVERSE')
+if is_reverse and opt.remote:
+    o.fatal("don't use -r in reverse mode; it's automatic")
+start_time = time.time()
+
+refname = opt.name and 'refs/heads/%s' % opt.name or None
+if opt.noop or opt.copy:
+    cli = w = oldref = None
+elif opt.remote or is_reverse:
+    cli = client.Client(opt.remote)
+    oldref = refname and cli.read_ref(refname) or None
+    w = cli.new_packwriter()
+else:
+    cli = None
+    oldref = refname and git.read_ref(refname) or None
+    w = git.PackWriter()
+
+files = extra and (open(fn) for fn in extra) or [sys.stdin]
+if w:
+    shalist = hashsplit.split_to_shalist(w, files)
+    tree = w.new_tree(shalist)
+else:
+    last = 0
+    for (blob, bits) in hashsplit.hashsplit_iter(files):
+        hashsplit.total_split += len(blob)
+        if opt.copy:
+            sys.stdout.write(str(blob))
+        megs = hashsplit.total_split/1024/1024
+        if not opt.quiet and last != megs:
+            progress('%d Mbytes read\r' % megs)
+            last = megs
+    progress('%d Mbytes read, done.\n' % megs)
+
+if opt.verbose:
+    log('\n')
+if opt.blobs:
+    for (mode,name,bin) in shalist:
+        print bin.encode('hex')
+if opt.tree:
+    print tree.encode('hex')
+if opt.commit or opt.name:
+    msg = 'bup split\n\nGenerated by command:\n%r' % sys.argv
+    ref = opt.name and ('refs/heads/%s' % opt.name) or None
+    commit = w.new_commit(oldref, tree, msg)
+    if opt.commit:
+        print commit.encode('hex')
+
+if w:
+    w.cjon is changing some random bytes here and theref
         
-        LIST=`/sbin/lsmod|awk '!/Module/ {print $1}'`
-
-       # Get list of available modules
-        LOC="/lib/modules/`uname -r`/kernel/drivers/acpi"
-        LOC2="/lib/modules/`uname -r`/kernel/ubuntu/acpi"
-        if [ -d $LOC ]; then
-         MODAVAIL=`( find $LOC -type f -name "*.o" -printf "basename %f .o\n"; \
-               find $LOC -type f -name "*.ko" -printf "basename %f .ko\n" ) | /bin/sh`
-       else
-         MODAVAIL=""
-       fi
-
-        if [ -d $LOC2 ]; then
-         MODAVAIL="$MODAVAIL `( find $LOC2 -type f -name "*.o" -printf "basename %f .o\n"; \
-               find $LOC2 -type f -name "*.ko" -printf "basename %f .ko\n" ) | /bin/sh`"
-       fi
-
-        if [ "$MODULES" = "all" ]; then
-               MODULES="$MODAVAIL"
-        fi
-
-       if [ -n "$MODULES" ]; then
-               log_begin_msg "Loading ACPI modules..."
-               STATUS=0
-               for mod in $MODULES; do
-                       echo $MODAVAIL | grep -q -w "$mod" || continue
-                       if echo $LIST | grep -q -w "$mod"; then
-                               [ "$VERBOSE" != no ] && log_success_msg "Module already loaded: $mod"
-                       else
-                               if modprobe -b $mod 2>/dev/null; then
-                                       [ "$VERBOSE" != no ] && log_success_msg "Loaded module: $mod"
-                               else
-                                       if [ "$VERBOSE" != no ]; then
-                                               log_warning_msg "Unable to load module: $mod"
-                                       fi
-                               fi
-                       fi              
-               done
-               log_end_msg $STATUS
-       fi
-        echo "$PRINTK" > /proc/sys/kernel/printk
-}
-
-case "$1" in
-  start)
-    [ -f /proc/modules ] && load_modules
-    log_begin_msg "Starting ACPI services..."
-    start-stop-daemon --start --quiet --oknodo --exec /usr/sbin/acpid -- -c /etc/acpi/events $OPTIONS
-    log_end_msg $?
-    ;;
-  stop)
-    log_begin_msg "Stopping ACPI services..."
-    start-stop-daemon --stop --quiet --oknodo --retry 2 --exec /usr/sbin/acpid
-    log_end_msg $?
-    ;;
-  restart)
-    $0 stop
-    sleep 1
-    $0 start
-    ;;
-  reload|force-reload) 
-    log_begin_msg "Reloading ACPI services..."
-    start-stop-daemon --stop --signal 1 --exec /usr/sbin/acpid
-    log_end_msg $?
-    ;;
-  *)
-    log_success_msg "Usage: /etc/init.d/acpid {start|stop|restart|reload|force-reload}"
-    exit 1
-esac
-
-exit 0
-#!/bin/bash
-# INIT script to check whether we're on batteries, and so start with laptop 
-# mode etc enabled.
-
-# BUGS: unless we start *really* late, we have no way of throttling 
-# xscreensaver, since it won't be there to command.
-. /usr/share/acpi-support/power-funcs
-
-test -f /lib/lsb/init-functions || exit 1
-. /lib/lsb/init-functions
-
-test -d /var/lib/acpi-support || exit 0
-
-shopt -s nullglob
-
-case "$1" in
-  start)
-    log_begin_msg "Checking battery state..."
-    /etc/acpi/power.sh
-    # Source everything in /etc/acpi/start.d/
-    for SCRIPT in /etc/acpi/start.d/*.sh; do
-       . $SCRIPT
-    done
-    log_end_msg 0
-    ;;
-  stop)
-    log_begin_msg "Disabling power management..."
-    /etc/acpi/power.sh stop
-    log_end_msg 0
-    ;;
-  *)
-  ;;
-esac
-        
-chicken
-
-#!/bin/sh
-#
-# alsa-utils initscript
-#
-### BEGIN INIT INFO
-# Provides:          alsa-utils
-# Required-Start:    $remote_fs
-# Required-Stop:     $remote_fs
-# Default-Start:     S
-# Default-Stop:      0 6
-# Short-Description: Restore and store ALSA driver settings
-# Description:       This script stores and restores mixer levels on
-#                    shutdown and bootup.On sysv-rc systems: to
-#                    disable storing of mixer levels on shutdown,
-#                    remove /etc/rc[06].d/K50alsa-utils.  To disable
-#                    restoring of mixer levels on bootup, rename the
-#                    "S50alsa-utils" symbolic link in /etc/rcS.d/ to
-#                    "K50alsa-utils".
-### END INIT INFO
-
-# Don't use set -e; check exit status instead
-
-# Exit silently if package is no longer installed
-[ -x /sbin/alsactl ] || exit 0
-
-PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
-MYNAME=/etc/init.d/alsa-utils
-
-. /lib/lsb/init-functions
-
-# $1 EXITSTATUS
-# [$2 MESSAGE]
-log_action_end_msg_and_exit()
-{
-       log_action_end_msg "$1" ${2:+"$2"}
-       exit $1
-}
-
-# $1 PROGRAM
-executable()
-{
-       # If which is not available then we must be running before
-       # /usr is mounted on a system that has which in /usr/bin/.
-       # Conclude that $1 is not executable.
-       [ -x /bin/which ] || [ -x /usr/bin/which ] || return 1
-       which "$1" >/dev/null 2>&1
-}
-
-# Wait for filesystems to show up
-while [ ! -d /usr/bin -o ! -d /var/lib/alsa ]; do
-       sleep 0.2
-done
-
-executable amixer || { echo "${MYNAME}: Error: No amixer program available." >&2 ; exit 1 ; }
-
-bugout() { echo "${MYNAME}: Programming error" >&2 ; exit 123 ; }
-
-# $1 <card ID> | "all"
-restore_levels()
-{
-       [ -f /var/lib/alsa/asound.state ] || return 1
-       CARD="$1"
-       [ "$1" = all ] && CARD=""
-       # Assume that if alsactl prints a message on stderr
-       # then it failed somehow.  This works around the fact
-       # that alsactl doesn't return nonzero status when it
-       # can't restore settings for the card
-       if MSG="$(alsactl restore $CARD 2>&1 >/dev/null)" && [ ! "$MSG" ] ; then
-               return 0
-       else
-               # Retry with the "force" option.  This restores more levels
-               # but it results in much longer error messages.
-               alsactl -F restore $CARD >/dev/null 2>&1
-               [ -z "$CARD" ] && log_action_cont_msg "warning: 'alsactl restore' failed with error message '$MSG'"
-               return 1
-       fi
-}
-
-# $1 <card ID> | "all"
-store_levels()
-{
-       CARD="$1"
-       [ "$1" = all ] && CARD=""
-       if MSG="$(alsactl store $CARD 2>&1)" ; then
-               sleep 1
-               return 0
-       else
-               [ -z "$CARD" ] && log_action_cont_msg "warning: 'alsactl store' failed with error message '$MSG'"
-               return 1
-       fi
-}
-
-echo_card_indices()
-{
-       if [ -f /proc/asound/cards ] ; then
-               sed -n -e's/^[[:space:]]*\([0-7]\)[[:space:]].*/\1/p' /proc/asound/cards
-       fi
-}
-
-filter_amixer_output()
-{
-       sed \
-               -e '/Unable to find simple control/d' \
-               -e '/Unknown playback setup/d' \
-               -e '/^$/d'
-}
-
-# The following functions try to set many controls.
-# No card has all the controls and so some of the attempts are bound to fail.
-# Because of this, the functions can't return useful status values.
-
-# $1 <control>
-# $2 <level>
-# $CARDOPT
-unmute_and_set_level()
-{
-       { [ "$2" ] && [ "$CARDOPT" ] ; } || bugout
-       amixer $CARDOPT -q set "$1" "$2" unmute 2>&1 | filter_amixer_output || :
-       return 0
-}
-
-# $1 <control>
-# $CARDOPT
-mute_and_zero_level()
-{
-       { [ "$1" ] && [ "$CARDOPT" ] ; } || bugout
-       amixer $CARDOPT -q set "$1" "0%" mute 2>&1 | filter_amixer_output || :
-       return 0
-}
-
-# $1 <control>
-# $2 "on" | "off"
-# $CARDOPT
-switch_control()
-{
-       { [ "$2" ] && [ "$CARDOPT" ] ; } || bugout
-       amixer $CARDOPT -q set "$1" "$2" 2>&1 | filter_amixer_output || :
-       return 0
-}
-
-# $1 <card ID>
-sanify_levels_on_card()
-{
-       CARDOPT="-c $1"
-
-       unmute_and_set_level "Front" "80%"
-       unmute_and_set_level "Master" "80%"
-       unmute_and_set_level "Master Mono" "80%"   # See Bug#406047
-       unmute_and_set_level "Master Digital" "80%"   # E.g., cs4237B
-       unmute_and_set_level "Playback" "80%"
-       unmute_and_set_level "Headphone" "70%"
-       unmute_and_set_level "PCM" "80%"
-       unmute_and_set_level "PCM,1" "80%"   # E.g., ess1969
-       unmute_and_set_level "DAC" "80%"     # E.g., envy24, cs46xx
-       unmute_and_set_level "DAC,0" "80%"   # E.g., envy24
-       unmute_and_set_level "DAC,1" "80%"   # E.g., envy24
-       unmute_and_set_level "Synth" "80%"
-       unmute_and_set_level "CD" "80%"
-
-       mute_and_zero_level "Mic"
-       mute_and_zero_level "IEC958"         # Ubuntu #19648
-
-       # Intel P4P800-MX  (Ubuntu bug #5813)
-       switch_control "Master Playback Switch" on
-       switch_control "Master Surround" on
-
-       # Trident/YMFPCI/emu10k1:
-       unmute_and_set_level "Wave" "80%"
-       unmute_and_set_level "Music" "80%"
-       unmute_and_set_level "AC97" "80%"
-
-       # DRC:
-       unmute_and_set_level "Dynamic Range Compression" "80%"
-
-       # Required for HDA Intel (hda-intel):
-       unmute_and_set_level "Front" "80%"
-
-       # Required for SB Live 7.1/24-bit (ca0106):
-       unmute_and_set_level "Analog Front" "80%"
-
-       # Required at least for Via 823x hardware on DFI K8M800-MLVF Motherboard with kernels 2.6.10-3/4 (see ubuntu #7286):
-       switch_control "IEC958 Capture Monitor" off
-
-       # Required for hardware allowing toggles for AC97 through IEC958,
-       #  valid values are 0, 1, 2, 3. Needs to be set to 0 for PCM1.
-       unmute_and_set_level "IEC958 Playback AC97-SPSA" "0"
-
-       # Required for newer Via hardware (see Ubuntu #31784)
-       unmute_and_set_level "VIA DXS,0" "80%"
-       unmute_and_set_level "VIA DXS,1" "80%"
-       unmute_and_set_level "VIA DXS,2" "80%"
-       unmute_and_set_level "VIA DXS,3" "80%"
-
-       # Required on some notebooks with ICH4:
-       switch_control "Headphone Jack Sense" off
-       switch_control "Line Jack Sense" off
-
-       # Some machines need one or more of these to be on;
-       # others need one or more of these to be off:
-       #
-       # switch_control "External Amplifier" on
-       switch_control "Audigy Analog/Digital Output Jack" on
-       switch_control "SB Live Analog/Digital Output Jack" on
-       
-       # D1984 -- Thinkpad T61/X61
-       switch_control "Speaker" on
-       switch_control "Headphone" on
-
-       # HDA-Intel w/ "Digital" capture mixer (See Ubuntu #193823)
-       unmute_and_set_level "Digital" "80%"
-
-       return 0
-}
-
-# $1 <card ID> | "all"
-sanify_levels()
-{
-       TTSDML_RETURNSTATUS=0
-       case "$1" in
-         all)
-               for CARD in $(echo_card_indices) ; do
-                       sanify_levels_on_card "$CARD" || TTSDML_RETURNSTATUS=1
-               done
-               ;;
-         *)
-               sanify_levels_on_card "$1" || TTSDML_RETURNSTATUS=1
-               ;;
-       esac
-       return $TTSDML_RETURNSTATUS
-}
-
-# $1 <card ID>
-preinit_levels_on_card()
-{
-       CARDOPT="-c $1"
-
-       # Silly dance to activate internal speakers by default on PowerMac
-       # Snapper and Tumbler
-       id=`cat /proc/asound/card$1/id 2>/dev/null`
-       if [ "$id" = "Snapper" -o "$id" = "Tumbler" ]; then
-               switch_control "Auto Mute" off
-               switch_control "PC Speaker" off
-               switch_control "Auto Mute" on
-       fi
-}
-
-# $1 <card ID> | "all"
-preinit_levels()
-{
-       TTSDML_RETURNSTATUS=0
-       case "$1" in
-         all)
-               for CARD in $(echo_card_indices) ; do
-                       preinit_levels_on_card "$CARD" || TTSDML_RETURNSTATUS=1
-               done
-               ;;
-         *)
-               preinit_levels_on_card "$1" || TTSDML_RETURNSTATUS=1
-               ;;
-       esac
-       return $TTSDML_RETURNSTATUS
-}
-
-# $1 <card ID>
-mute_and_zero_levels_on_card()
-{
-       CARDOPT="-c $1"
-       for CTL in \
-               Master \
-               PCM \
-               Synth \
-               CD \
-               Line \
-               Mic \
-               "PCM,1" \
-               Wave \
-               Music \
-               AC97 \
-               "Master Digital" \
-               DAC \
-               "DAC,0" \
-               "DAC,1" \
-               Headphone \
-               Playback \
-               Speaker
-       do
-               mute_and_zero_level "$CTL"
-       done
-#      for CTL in \
-#              "Audigy Analog/Digital Output Jack" \
-#              "SB Live Analog/Digital Output Jack"
-#      do
-#              switch_control "$CTL" off
-#      done
-       return 0
-}
-
-# $1 <card ID> | "all"
-mute_and_zero_levels()
-{
-       TTZML_RETURNSTATUS=0
-       case "$1" in
-         all)
-               for CARD in $(echo_card_indices) ; do
-                       mute_and_zero_levels_on_card "$CARD" || TTZML_RETURNSTATUS=1
-               done
-               ;;
-         *)
-               mute_and_zero_levels_on_card "$1" || TTZML_RETURNSTATUS=1
-               ;;
-       esac
-       return $TTZML_RETURNSTATUS
-}
-
-
-# $1 <card ID> | "all"
-card_OK()
-{
-       [ "$1" ] || bugout
-       if [ "$1" = all ] ; then
-               [ -d /proc/asound ]
-               return $?
-       else
-               [ -d "/proc/asound/card$1" ] || [ -d "/proc/asound/$1" ]
-               return $?
-       fi
-}
-
-# If a card identifier is provided in $2 then regard it as an error
-# if that card is not present; otherwise don't regard it as an error.
-
-case "$1" in
-  start)
-       EXITSTATUS=0
-       TARGET_CARD="$2"
-       case "$TARGET_CARD" in
-         ""|all) TARGET_CARD=all ; log_action_begin_msg "Setting up ALSA" ;;
-       esac
-       if ! card_OK "$TARGET_CARD"; then
-               [ "$TARGET_CARD" = "all" ] && log_action_end_msg "$( [ ! "$2" ] ; echo $? ; )" "none loaded"
-               exit $?
-       fi
-       preinit_levels "$TARGET_CARD" || EXITSTATUS=1
-       if ! restore_levels "$TARGET_CARD" ; then
-               sanify_levels "$TARGET_CARD" || EXITSTATUS=1
-               restore_levels "$TARGET_CARD" >/dev/null 2>&1 || :
-       fi
-       [ "$TARGET_CARD" = "all" ] && log_action_end_msg_and_exit "$EXITSTATUS"
-       exit $EXITSTATUS
-       ;;
-  stop)
-       EXITSTATUS=0
-       TARGET_CARD="$2"
-       case "$TARGET_CARD" in
-         ""|all) TARGET_CARD=all ; log_action_begin_msg "Shutting down ALSA" ;;
-         *) log_action_begin_msg "Shutting down ALSA card ${TARGET_CARD}" ;;
-       esac
-       card_OK "$TARGET_CARD" || log_action_end_msg_and_exit "$( [ ! "$2" ] ; echo $? ; )" "none loaded"
-       store_levels "$TARGET_CARD" || EXITSTATUS=1
-       mute_and_zero_levels "$TARGET_CARD" || EXITSTATUS=1
-       log_action_end_msg_and_exit "$EXITSTATUS"
-       ;;
-  restart|force-reload)
-       EXITSTATUS=0
-       $0 stop || EXITSTATUS=1
-       $0 start || EXITSTATUS=1
-       exit $EXITSTATUS
-       ;;
-  reset)
-       TARGET_CARD="$2"
-       case "$TARGET_CARD" in
-         ""|all) TARGET_CARD=all ; log_action_begin_msg "Resetting ALSA" ;;
-         *) log_action_begin_msg "Resetting ALSA card ${TARGET_CARD}" ;;
-       esac
-       card_OK "$TARGET_CARD" || log_action_end_msg_and_exit "$( [ ! "$2" ] ; echo $? ; )" "none loaded"
-       preinit_levels "$TARGET_CARD"
-       sanify_levels "$TARGET_CARD"
-       log_action_end_msg_and_exit "$?"
-       ;;
-  *)
-       echo "Usage: $MYNAME {start [CARD]|stop [CARD]|restart [CARD]|reset [CARD]}" >&2
-       exit 3
-       ;;
-esac
-
-#!/bin/bash -e
-#
-# apache2              This init.d script is used to start apache2.
-#                      It basically just calls apache2ctl.
-
-ENV="env -i LANG=C PATH=/usr/local/bin:/usr/bin:/bin"
-
-#edit /etc/default/apache2 to change this.
-NO_START=0
-
-set -e
-if [ -x /usr/sbin/apache2 ] ; then
-       HAVE_APACHE2=1
-else
-       exit 0
-fi
-
-. /lib/lsb/init-functions
-
-test -f /etc/default/rcS && . /etc/default/rcS
-test -f /etc/default/apache2 && . /etc/default/apache2
-if [ "$NO_START" != "0" -a "$1" != "stop" ]; then 
-        [ "$VERBOSE" != "no" ] && log_warning_msg "Not starting apache2 - edit /etc/default/apache2 and change NO_START to be 0.";
-        exit 0;
-fi
-
-APACHE2="$ENV /usr/sbin/apache2"
-APACHE2CTL="$ENV /usr/sbin/apache2ctl"
-
-apache_stop() {
-       PID=""
-       PIDFILE=""
-       AP_CONF=/etc/apache2/apache2.conf
-
-       # apache2 allows more than PidFile entry in the config but only the
-       # last found in the config is used; we attempt to follow includes
-       # here, but only first-level includes are supported, not nested ones
-
-       for i in $AP_CONF `awk '$1 ~ /^\s*[Ii]nclude$/ && $2 ~ /^\// {print $2}' $AP_CONF`; do
-               PIDFILE=`grep -i ^PidFile $i | tail -n 1 | awk '{print $2}'`
-               if [ -e "$PIDFILE" ]; then
-                       PID=`cat $PIDFILE`
-               fi
-       done
-       
-       errors=`$APACHE2 -t 2>&1`
-       if [ $? = 0 ]; then
-               # if the config is ok than we just stop normaly
-
-               if [ -n "$PID" ]
-               then
-                       $APACHE2CTL stop
-
-                       CNT=0
-                       while [ 1 ]
-                       do
-                               CNT=$(expr $CNT + 1)
-               
-                               [ ! -d /proc/$PID ] && break
-
-                               if [ $CNT -gt 60 ]
-                               then
-                                       if [ "$VERBOSE" != "no" ]; then
-                                               echo " ... failed!"
-                                               echo "Apache2 failed to honor the stop command, please investigate the situation by hand."
-                                       fi
-                                       return 1
-                               fi
-
-                               sleep 1
-                       done
-               else
-                       if [ "$VERBOSE" != "no" ]; then
-                               echo -n " ... no pidfile found! not running?"
-                       fi
-               fi
-
-       else
-               [ "$VERBOSE" != "no" ] && echo "$errors"
-
-               # if we are here something is broken and we need to try
-               # to exit as nice and clean as possible
-
-               # if pidof is null for some reasons the script exits automagically
-               # classified as good/unknown feature
-               PIDS=`pidof apache2` || true
-
-               REALPID=0
-               # if there is a pid we need to verify that belongs to apache2
-               # for real
-               for i in $PIDS; do
-                       if [ "$i" = "$PID" ]; then
-                               # in this case the pid stored in the
-                               # pidfile matches one of the pidof apache
-                               # so a simple kill will make it
-                               REALPID=1
-                       fi
-               done
-
-               if [ $REALPID = 1 ]; then
-                       # in this case everything is nice and dandy
-                       # and we kill apache2
-                       kill $PID
-               else
-                       # this is the worst situation... just kill all of them
-                       #for i in $PIDS; do
-                       #       kill $i
-                       #done
-                       # Except, we can't do that, because it's very, very bad
-                       if [ "$PIDS" ] && [ "$VERBOSE" != "no" ]; then
-                                echo " ... failed!"
-                               echo "You may still have some apache2 processes running.  There are"
-                               echo "processes named 'apache2' which do not match your pid file,"
-                               echo "and in the name of safety, we've left them alone.  Please review"
-                               echo "the situation by hand."
-                        fi
-                        return 1
-               fi
-       fi
-}
-
-# Stupid hack to keep lintian happy. (Warrk! Stupidhack!).
-case $1 in
-       start)
-               [ -f /etc/apache2/httpd.conf ] || touch /etc/apache2/httpd.conf
-               # ssl_scache shouldn't be here if we're just starting up.
-               [ -f /var/run/apache2/ssl_scache ] && rm -f /var/run/apache2/*ssl_scache*
-               # /var/run and /var/lock could be on a tmpfs
-               [ ! -d /var/run/apache2 ] && mkdir /var/run/apache2
-               [ ! -d /var/lock/apache2 ] && mkdir /var/lock/apache2
-               # Make sure /var/lock/apache2 has the correct permissions
-               chown www-data /var/lock/apache2
-
-               log_begin_msg "Starting apache 2.0 web server..."
-               if $APACHE2CTL startssl; then
-                        log_end_msg 0
-                else
-                        log_end_msg 1
-                fi
-       ;;
-       stop)
-               log_begin_msg "Stopping apache 2.0 web server..."
-               if apache_stop; then
-                        log_end_msg 0
-                else
-                        log_end_msg 1
-                fi
-       ;;
-       reload)
-               log_begin_msg "Reloading apache 2.0 configuration..."
-               if $APACHE2CTL graceful $2 ; then
-                        log_end_msg 0
-                else
-                        log_end_msg 1
-                fi
-       ;;
-       restart | force-reload)
-               log_begin_msg "Forcing reload of apache 2.0 web server..."
-               if ! apache_stop; then
-                        log_end_msg 1
-                fi
-               if $APACHE2CTL startssl; then
-                        log_end_msg 0
-                else
-                        log_end_msg 1
-                fi
-       ;;
-       status)
-               exit 4
-       ;;
-       *)
-               echo "Usage: /etc/init.d/apache2 start|stop|restart|reload|force-reload" >&2
-               exit 2
-       ;;
-esac
-#! /bin/sh -e
-#### BEGIN INIT INFO
-# Provides:          atd
-# Required-Start:    $syslog $time $local_fs $remote_fs
-# Required-Stop:     $syslog $time $local_fs $remote_fs
-# Default-Start:     2 3 4 5
-# Default-Stop:      S 0 1 6
-# Short-Description: Deferred execution scheduler
-# Description:       Debian init script for the atd deferred executions
-#                    scheduler
-### END INIT INFO
-#
-# Author:      Ryan Murray <rmurray@debian.org>
-#
-set -e
-
-PATH=/bin:/usr/bin:/sbin:/usr/sbin
-DAEMON=/usr/sbin/atd
-
-test -x $DAEMON || exit 0
-
-. /lib/lsb/init-functions
-
-case "$1" in
-    start)
-       log_daemon_msg "Starting deferred execution scheduler" "atd"
-       start_daemon $DAEMON
-       log_end_msg $?
-    ;;
-  stop)
-       log_daemon_msg "Stopping deferred execution scheduler" "atd"
-       killproc $DAEMON
-       log_end_msg $?
-    ;;
-  force-reload|restart)
-    $0 stop
-    $0 start
-    ;;
-  *)
-    echo "Usage: /etc/init.d/atd {start|stop|restart|force-reload}"
-    exit 1
-    ;;
-esac
-
-exit 0
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          binfmt-support
-# Required-Start:    $local_fs $remote_fs
-# Required-Stop:     $local_fs $remote_fs
-# Default-Start:     2 3 4 5
-# Default-Stop:      0 1 6
-# Short-Description: Support for extra binary formats
-# Description:       Enable support for extra binary formats using the Linux
-#                    kernel's binfmt_misc facility.
-### END INIT INFO
-
-PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
-NAME=binfmt-support
-DESC="additional executable binary formats"
-
-test -x /usr/sbin/update-binfmts || exit 0
-
-. /lib/lsb/init-functions
-. /etc/default/rcS
-
-set -e
-CODE=0
-
-case "$1" in
-  start)
-    log_daemon_msg "Enabling $DESC" "$NAME"
-    update-binfmts --enable || CODE=$?
-    log_end_msg $CODE
-    exit $CODE
-    ;;
-
-  stop)
-    log_daemon_msg "Disabling $DESC" "$NAME"
-    update-binfmts --disable || CODE=$?
-    log_end_msg $CODE
-    exit $CODE
-    ;;
-
-  restart|force-reload)
-    $0 stop
-    $0 start
-    ;;
-
-  *)
-    N=/etc/init.d/$NAME
-    echo "Usage: $N {start|stop|restart|force-reload}" >&2
-    exit 1
-    ;;
-esac
-
-exit 0
-#!/bin/sh
-#
-# bootclean
-#
-# Clean /tmp
-#
-# DO NOT RUN AFTER S:55bootmisc.sh and do not run this script directly
-# in runlevel S. Instead write an initscript to call it.
-#
-
-. /lib/init/vars.sh
-
-. /lib/lsb/init-functions
-
-# Should be called outside verbose message block
-mkflagfile()
-{
-       # Prevent symlink attack  (See #264234.)
-       [ -L "$1" ] && log_warning_msg "bootclean: Deleting symbolic link '$1'."
-       rm -f "$1" || { log_failure_msg "bootclean: Failure deleting '$1'." ; return 1 ; }
-       # No user processes should be running, so no one should be able to introduce
-       # a symlink here.  As an extra precaution, set noclobber.
-       set -o noclobber
-       :> "$1" || { log_failure_msg "bootclean: Failure creating '$1'." ; return 1 ; }
-       return 0
-}
-
-clean_tmp() {
-       cd /tmp || { log_failure_msg "bootclean: Could not cd to /tmp." ; return 1 ; }
-
-       #
-       # Only clean out /tmp if it is world-writable. This ensures
-       # it really is a/the temp directory we're cleaning.
-       #
-       [ "$(find . -maxdepth 0 -perm -002)" = "." ] || return 0
-
-       if [ ! "$TMPTIME" ]
-       then
-               log_warning_msg "Using default TMPTIME 0."
-               TMPTIME=0
-       fi
-
-       [ "$VERBOSE" = no ] || log_action_begin_msg "Cleaning /tmp"
-
-       #
-       # Remove regardless of TMPTIME setting
-       #
-       rm -f .X*-lock
-
-       #
-       # Don't clean remaining files if TMPTIME is negative or 'infinite'
-       #
-       case "$TMPTIME" in
-         -*|infinite|infinity)
-               [ "$VERBOSE" = no ] || log_action_end_msg 0 "skipped"
-               return 0
-               ;;
-       esac
-
-       #
-       # Wipe /tmp, excluding system files, but including lost+found
-       #
-       # If TMPTIME is set to 0, we do not use any ctime expression
-       # at all, so we can also delete files with timestamps
-       # in the future!
-       #
-       if [ "$TMPTIME" = 0 ] 
-       then
-               TEXPR=""
-               DEXPR=""
-       else
-               TEXPR="-mtime +$TMPTIME -ctime +$TMPTIME -atime +$TMPTIME"
-               DEXPR="-mtime +$TMPTIME -ctime +$TMPTIME"
-       fi
-
-       EXCEPT='! -name .
-               ! ( -path ./lost+found -uid 0 )
-               ! ( -path ./quota.user -uid 0 )
-               ! ( -path ./aquota.user -uid 0 )
-               ! ( -path ./quota.group -uid 0 )
-               ! ( -path ./aquota.group -uid 0 )
-               ! ( -path ./.journal -uid 0 )
-               ! ( -path ./.clean -uid 0 )
-               ! ( -path './...security*' -uid 0 )'
-
-       mkflagfile /tmp/.clean || return 1
-
-       report_err()
-       {
-               if [ "$VERBOSE" = no ]
-               then
-                       log_failure_msg "bootclean: Failure cleaning /tmp."
-               else
-                       log_action_end_msg 1 "bootclean: Failure cleaning /tmp"
-               fi
-       }
-
-       #
-       # First remove all old files...
-       # (Use xargs here so that only one additional process gets created)
-       #
-       find . -depth -xdev $TEXPR $EXCEPT ! -type d \
-               -print0 | xargs -0r rm -f -- \
-               || { report_err ; return 1 ; }
-
-       #
-       # ...and then all empty directories
-       # (Don't use xargs here because dirs must be removed one by one from
-       # the bottom up)
-       #
-       find . -depth -xdev $DEXPR $EXCEPT -type d -empty \
-               -exec rmdir \{\} \; \
-               || { report_err ; return 1 ; }
-
-       [ "$VERBOSE" = no ] || log_action_end_msg 0
-       return 0
-}
-
-which find >/dev/null 2>&1 || exit 1
-which xargs >/dev/null 2>&1 || exit 1
-
-# If there are flag files that have not been created by root
-# then remove them
-for D in /tmp
-do
-       if [ -f $D/.clean ]
-       then
-               which stat >/dev/null 2>&1 && cleanuid="$(stat -c %u $D/.clean)"
-               # Poor's man stat %u, since stat (and /usr) might not be
-               # available in some bootup stages
-               [ "$cleanuid" ] || cleanuid="$(find $D/.clean -printf %U)"
-               [ "$cleanuid" ] || { log_failure_msg "bootclean: Could not stat '$D/.clean'." ; exit 1 ; }
-               if [ "$cleanuid" -ne 0 ]
-               then
-                       rm -f $D/.clean || { log_failure_msg "bootclean: Could not delete '$D/.clean'." ; exit 1 ; }
-               fi
-       fi
-done
-
-[ -f /tmp/.clean ] && exit 0
-
-ES=0
-[ -d /tmp ] && ! [ -f /tmp/.clean ] && { clean_tmp || ES=1 ; }
-exit $ES
-
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          bootlogd
-# Required-Start:    mountdevsubfs
-# Required-Stop:
-# Default-Start:     S
-# Default-Stop:
-# Short-Description: Start or stop bootlogd.
-# Description:       Starts or stops the bootlogd log program
-#                    which logs boot messages.
-### END INIT INFO
-
-PATH=/sbin:/bin
-DAEMON=/sbin/bootlogd
-[ -x "$DAEMON" ] || exit 0
-NAME=bootlogd
-DESC="boot logger"
-BOOTLOGD_OPTS="-r -c"
-[ -r /etc/default/bootlogd ] && . /etc/default/bootlogd
-. /lib/init/vars.sh
-
-. /lib/lsb/init-functions
-
-# Because bootlogd is broken on some systems, we take the special measure
-# of requiring it to be enabled by setting an environment variable.
-case "$BOOTLOGD_ENABLE" in
-  [Nn]*)
-       exit 0
-       ;;
-esac
-
-# Previously this script was symlinked as "stop-bootlogd" which, when run
-# with the "start" argument, should stop bootlogd.  Now stop-bootlogd is
-# a distinct script, but for backward compatibility this script continues
-# to implement the old behavior.
-SCRIPTNAME=${0##*/}
-SCRIPTNAME=${SCRIPTNAME#[SK]??}
-ACTION="$1"
-case "$0" in
-  *stop-bootlog*)
-       [ "$ACTION" = start ] && ACTION=stop
-       ;;
-esac
-
-case "$ACTION" in
-  start)
-       # PATH is set above
-       log_daemon_msg "Starting $DESC" "$NAME"
-       if [ -d /proc/1/. ]
-       then
-               umask 027
-               start-stop-daemon --start --quiet --exec $DAEMON -- \
-                       $BOOTLOGD_OPTS
-               ES=$?
-       else
-               $DAEMON $BOOTLOGD_OPTS
-               ES=$?
-       fi
-       log_end_msg $ES
-       ;;
-  stop)
-       PATH=/sbin:/bin:/usr/sbin:/usr/bin
-       log_daemon_msg "Stopping $DESC" "$NAME"
-       start-stop-daemon --stop --quiet --exec $DAEMON
-       ES=$?
-       sleep 1
-       log_end_msg $ES
-       if [ -f /var/log/boot ] && [ -f /var/log/boot~ ]
-       then
-               [ "$VERBOSE" = no ] || log_action_begin_msg "Moving boot log file"
-               # bootlogd writes to boot, making backup at boot~
-               cd /var/log && {
-                       chgrp adm boot || :
-                       savelog -q -p -c 5 boot \
-                       && mv boot.0 boot \
-                       && mv boot~ boot.0
-               }
-               ES=$?
-               [ "$VERBOSE" = no ] || log_action_end_msg $ES
-       fi
-       ;;
-  restart|force-reload)
-       /etc/init.d/bootlogd stop
-       /etc/init.d/bootlogd start
-       ;;
-  *)
-       echo "Usage: $SCRIPTNAME {start|stop|restart|force-reload}" >&2
-       exit 3
-       ;;
-esac
-
-:
-#!/bin/sh
-### BEGIN INIT INFO
-# Provides:          bootmisc
-# Required-Start:    $local_fs hostname $remote_fs
-# Required-Stop:     $local_fs
-# Default-Start:     S
-# Default-Stop:
-# Short-Description: Miscellaneous things to be done during bootup.
-# Description:
-### END INIT INFO
-
-PATH=/usr/sbin:/usr/bin:/sbin:/bin
-[ "$DELAYLOGIN" ] || DELAYLOGIN=yes
-. /lib/init/vars.sh
-
-do_start () {
-       #
-       # If login delaying is enabled then create the flag file
-       # which prevents logins before startup is complete
-       #
-       case "$DELAYLOGIN" in
-         Y*|y*)
-               echo "System bootup in progress - please wait" > /var/lib/initscripts/nologin
-               ;;
-       esac
-
-       # Create /var/run/utmp so we can login.
-       : > /var/run/utmp
-       if grep -q ^utmp: /etc/group
-       then
-               chmod 664 /var/run/utmp
-               chgrp utmp /var/run/utmp
-       fi
-
-       # Set pseudo-terminal access permissions.
-       if [ ! -e /dev/.devfsd ] && [ -c /dev/ttyp0 ]
-       then
-               chmod -f 666 /dev/tty[p-za-e][0-9a-f]
-               chown -f root:tty /dev/tty[p-za-e][0-9a-f]
-       fi
-
-       # Update motd
-       uname -snrvm > /var/run/motd
-       [ -f /etc/motd.tail ] && cat /etc/motd.tail >> /var/run/motd
-
-       # Save kernel messages in /var/log/dmesg
-       if which dmesg >/dev/null 2>&1
-       then
-               savelog -q -p -c 5 /var/log/dmesg
-               dmesg -s 524288 > /var/log/dmesg
-               chgrp adm /var/log/dmesg || :
-       elif [ -c /dev/klog ]
-       then
-               savelog -q -p -c 5 /var/log/dmesg
-               dd if=/dev/klog of=/var/log/dmesg &
-               sleep 1
-               kill $!
-               [ -f /var/log/dmesg ] && { chgrp adm /var/log/dmesg || : ; }
-       fi
-
-       # Remove bootclean's flag files.
-       # Don't run bootclean again after this!
-       rm -f /tmp/.clean
-}
-
-case "$1" in
-  start|"")
-       do_start
-       ;;
-  restart|reload|force-reload)
-       echo "Error: argument '$1' not supported" >&2
-       exit 3
-       ;;
-  stop)
-       # No-op
-       ;;
-  *)
-       echo "Usage: bootmisc.sh [start|stop]" >&2
-       exit 3
-       ;;
-esac
-
-:
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          checkfs
-# Required-Start:    modutils checkroot
-# Required-Stop:
-# Should-Start:      lvm cryptdisks
-# Should-Stop:
-# Default-Start:     S
-# Default-Stop:
-# Short-Description: Check all filesystems.
-### END INIT INFO
-
-PATH=/sbin:/bin
-FSCK_LOGFILE=/var/log/fsck/checkfs
-[ "$FSCKFIX" ] || FSCKFIX=no
-. /lib/init/vars.sh
-. /lib/init/usplash-fsck-functions.sh
-
-. /lib/lsb/init-functions
-
-# Always output fsck progress
-stdin=`readlink /proc/self/fd/0`
-if [ "${stdin#/dev/null}" != "$stdin" ]; then
-    exec </dev/console >/dev/console 2>&1
-fi
-
-do_start () {
-       # See if we're on AC Power
-       # If not, we're not gonna run our check
-       if which on_ac_power >/dev/null 2>&1
-       then
-               on_ac_power >/dev/null 2>&1
-               if [ $? -eq 1 ]
-               then
-                       [ "$VERBOSE" = no ] || log_success_msg "Running on battery power, so skipping file system check."
-                       BAT=yes
-               fi
-       fi
-
-       #
-       # Check the rest of the file systems.
-       #
-       if [ ! -f /fastboot ] && [ ! "$BAT" ] && [ "$FSCKTYPES" != "none" ]
-       then
-               if [ -f /forcefsck ]
-               then
-                       force="-f"
-               else
-                       force=""
-               fi
-               if [ "$FSCKFIX" = yes ]
-               then
-                       fix="-y"
-               else
-                       fix="-a"
-               fi
-               spinner="-C"
-               case "$TERM" in
-                 dumb|network|unknown|"")
-                       spinner=""
-                       ;;
-               esac
-               [ "$(uname -m)" = s390 ] && spinner=""  # This should go away
-               FSCKTYPES_OPT=""
-               [ "$FSCKTYPES" ] && FSCKTYPES_OPT="-t $FSCKTYPES"
-               handle_failed_fsck() {
-                       log_failure_msg "File system check failed. 
-A log is being saved in ${FSCK_LOGFILE} if that location is writable. 
-Please repair the file system manually."
-                       log_warning_msg "A maintenance shell will now be started. 
-CONTROL-D will terminate this shell and resume system boot."
-                       # Start a single user shell on the console
-                       if ! sulogin $CONSOLE
-                       then
-                               log_failure_msg "Attempt to start maintenance shell failed. 
-Continuing with system boot in 5 seconds."
-                               sleep 5
-                       fi
-               }
-               if [ "$VERBOSE" = no ]
-               then
-                       log_action_begin_msg "Checking file systems"
-                        if pidof usplash; then
-                            PROGRESS_FILE=`mktemp` || exit 1
-                            set -m
-                            logsave -s $FSCK_LOGFILE fsck -C3 -R -A $fix $force $FSCKTYPES_OPT >/dev/console 2>&1 3>$PROGRESS_FILE &
-                            set +m
-                            usplash_progress "$PROGRESS_FILE"
-                            rm -f $PROGRESS_FILE
-                        else
-                            logsave -s $FSCK_LOGFILE fsck $spinner -R -A $fix $force $FSCKTYPES_OPT
-                            FSCKCODE=$?
-                        fi
-
-                       if [ "$FSCKCODE" -gt 1 ]
-                       then
-                               log_action_end_msg 1 "code $FSCKCODE"
-                               handle_failed_fsck
-                       else
-                               log_action_end_msg 0
-                       fi
-               else
-                       if [ "$FSCKTYPES" ]
-                       then
-                               log_action_msg "Will now check all file systems of types $FSCKTYPES"
-                       else
-                               log_action_msg "Will now check all file systems"
-                       fi
-                       logsave -s $FSCK_LOGFILE fsck $spinner -V -R -A $fix $force $FSCKTYPES_OPT
-                       FSCKCODE=$?
-                       if [ "$FSCKCODE" -gt 1 ]
-                       then
-                               handle_failed_fsck
-                       else
-                               log_success_msg "Done checking file systems. 
-A log is being saved in ${FSCK_LOGFILE} if that location is writable."
-                       fi
-               fi
-       fi
-       rm -f /fastboot /forcefsck
-}
-
-case "$1" in
-  start|"")
-       do_start
-       ;;
-  restart|reload|force-reload)
-       echo "Error: argument '$1' not supported" >&2
-       exit 3
-       ;;
-  stop)
-       # No-op
-       ;;
-  *)
-       echo "Usage: checkfs.sh [start|stop]" >&2
-       exit 3
-       ;;
-esac
-
-:
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          checkroot
-# Required-Start:    mountdevsubfs
-# Required-Stop:     
-# Should-Start:      keymap hwclockfirst
-# Should-stop:
-# Default-Start:     S
-# Default-Stop:
-# Short-Description: Check to root file system.
-### END INIT INFO
-
-PATH=/lib/init:/sbin:/bin
-FSCK_LOGFILE=/var/log/fsck/checkroot
-[ "$FSCKFIX" ] || FSCKFIX=no
-[ "$SULOGIN" ] || SULOGIN=no
-. /lib/init/vars.sh
-. /lib/init/usplash-fsck-functions.sh
-
-. /lib/lsb/init-functions
-
-# Always output fsck progress
-stdin=`readlink /proc/self/fd/0`
-if [ "${stdin#/dev/null}" != "$stdin" ]; then
-    exec </dev/console >/dev/console 2>&1
-fi
-
-do_start () {
-       #
-       # Set SULOGIN in /etc/default/rcS to yes if you want a sulogin to
-       # be spawned from this script *before anything else* with a timeout,
-       # like sysv does.
-       #
-       [ "$SULOGIN" = yes ] && sulogin -t 30 $CONSOLE
-
-       KERNEL="$(uname -s)"
-       MACHINE="$(uname -m)"
-
-       #
-       # Read /etc/fstab, looking for:
-       # 1) The root filesystem, resolving LABEL=*|UUID=* entries to the
-       #       device node,
-       # 2) Swap that is on a md device or a file that may be on a md 
-       #       device,
-       # 3) The mount parameters for a devfs filesystem.
-       #
-
-       exec 9<&0 </etc/fstab
-
-       fstabroot=/dev/root
-       rootdev=none
-       roottype=none
-       rootopts=defaults
-       rootmode=rw
-       rootcheck=no
-       swap_on_lv=no
-       swap_on_file=no
-       devfs=
-
-       while read DEV MTPT FSTYPE OPTS DUMP PASS JUNK
-       do
-               case "$DEV" in
-                 ""|\#*)
-                       continue;
-                       ;;
-                 /dev/mapper/*)
-                       [ "$FSTYPE" = "swap" ] && swap_on_lv=yes
-                       ;;
-                 /dev/*)
-                       ;;
-                 LABEL=*|UUID=*)
-                       if [ "$MTPT" = "/" ] && which findfs >/dev/null 2>&1
-                       then
-                               DEV="$(findfs "$DEV")"
-                       fi
-                       ;;
-                 /*)
-                       [ "$FSTYPE" = "swap" ] && swap_on_file=yes
-                       ;;
-                 *)
-                       # Devfs definition ?
-                       if [ "$FSTYPE" = "devfs" ] && [ "$MTPT" = "/dev" ] && mountpoint -q /dev
-                       then
-                               devfs="-t $FSTYPE $DEV $MTPT"
-                       fi
-                       ;;
-               esac
-               [ "$MTPT" != "/" ] && continue
-               rootdev="$DEV"
-               fstabroot="$DEV"
-               rootopts="$OPTS"
-               roottype="$FSTYPE"
-               ( [ "$PASS" != 0 ] && [ "$PASS" != "" ]   ) && rootcheck=yes
-               ( [ "$FSTYPE" = "nfs" ] || [ "$FSTYPE" = "nfs4" ] ) && rootcheck=no
-               case "$OPTS" in
-                 ro|ro,*|*,ro|*,ro,*)
-                       rootmode=ro
-                       ;;
-               esac
-       done
-
-       exec 0<&9 9<&-
-
-       #
-       # Activate the swap device(s) in /etc/fstab. This needs to be done
-       # before fsck, since fsck can be quite memory-hungry.
-       #
-       ENABLE_SWAP=no
-       case "$KERNEL" in
-         Linux)
-               if [ "$swap_on_lv" = yes ]
-               then
-                       [ "$VERBOSE" = no ] || log_warning_msg "Not activating swap on logical volume."
-               elif [ "$swap_on_file" = yes ]
-               then
-                       [ "$VERBOSE" = no ] || log_warning_msg "Not activating swap on swapfile."
-               else
-                       ENABLE_SWAP=yes
-               fi
-               ;;
-         *)
-               ENABLE_SWAP=yes
-               ;;
-       esac
-       if [ "$ENABLE_SWAP" = yes ]
-       then
-               if [ "$VERBOSE" = no ]
-               then
-                       log_action_begin_msg "Activating swap"
-                       swapon -a -e >/dev/null 2>&1
-                       log_action_end_msg $?
-               else
-                       log_action_msg "Will now activate swap"
-                       swapon -a -v
-                       ES=$?
-                       if [ "$ES" = 0 ]
-                       then
-                               log_success_msg "Done activating swap."
-                       else
-                               log_failure_msg "Swap activation failed with error code ${ES}."
-                       fi
-               fi
-       fi
-
-       #
-       # Does the root device in /etc/fstab match with the actual device ?
-       # If not we try to use the /dev/root alias device, and if that
-       # fails we create a temporary node in /dev/shm.
-       #
-       if [ "$rootcheck" = yes ]
-       then
-               ddev="$(mountpoint -qx $rootdev)"
-               rdev="$(mountpoint -d /)"
-               if [ "$ddev" != "$rdev" ] && [ "$ddev" != "4:0" ]
-               then
-                       if [ "$(mountpoint -qx /dev/root)" = "4:0" ]
-                       then
-                               rootdev=/dev/root
-                       else
-                               if \
-                                       rm -f /dev/shm/root \
-                                       && mknod -m 600 /dev/shm/root b ${rdev%:*} ${rdev#*:} \
-                                       && [ -e /dev/shm/root ]
-                               then
-                                       rootdev=/dev/shm/root
-                               else
-                                       rootfatal=yes
-                               fi
-                       fi
-               fi
-       fi
-
-       #
-       # Bother, said Pooh.
-       #
-       if [ "$rootfatal" = yes ]
-       then
-               log_failure_msg "The device node $rootdev for the root filesystem is missing or incorrect 
-or there is no entry for the root filesystem listed in /etc/fstab. 
-The system is also unable to create a temporary node in /dev/shm. 
-This means you have to fix the problem manually."
-               log_warning_msg "A maintenance shell will now be started. 
-CONTROL-D will terminate this shell and restart the system."
-               # Start a single user shell on the console
-               if ! sulogin $CONSOLE
-               then
-                       log_failure_msg "Attempt to start maintenance shell failed. 
-Will restart in 5 seconds."
-                       sleep 5
-               fi
-               [ "$VERBOSE" = no ] || log_action_msg "Will now restart"
-               reboot -f
-       fi
-
-       # See if we're on AC Power
-       # If not, we're not gonna run our check
-       if which on_ac_power >/dev/null 2>&1 && [ "$rootcheck" = yes ]
-       then
-               if [ -d /proc/acpi ]; then
-                       modprobe ac >/dev/null 2>&1
-               fi
-               on_ac_power >/dev/null 2>&1
-               if [ "$?" -eq 1 ]
-               then
-                       log_warning_msg "On battery power, so skipping file system check."
-                       rootcheck=no
-               fi
-       fi
-
-       #
-       # See if we want to check the root file system.
-       #
-       FSCKCODE=0
-       if [ -f /fastboot ]
-       then
-               [ "$rootcheck" = yes ] && log_warning_msg "Fast boot enabled, so skipping file system check."
-               rootcheck=no
-       fi
-
-       if [ "$rootcheck" = yes ]
-       then
-               #
-               # Ensure that root is quiescent and read-only before fsck'ing.
-               #
-               # mount -n -o remount,ro / would be the correct syntax but
-               # mount can get confused when there is a "bind" mount defined
-               # in fstab that bind-mounts "/" somewhere else.
-               #
-               # So we use mount -n -o remount,ro $rootdev / but that can
-               # fail on older kernels on sparc64/alpha architectures due
-               # to a bug in sys_mount().
-               #
-               # As a compromise we try both.
-               #
-               if \
-                       ! mount    -n -o remount,ro              $rootdev /              \
-                       && ! mount -n -o remount,ro -t dummytype $rootdev /  2>/dev/null \
-                       && ! mount -n -o remount,ro                       /  2>/dev/null
-               then
-                       log_failure_msg "Cannot check root file system because it is not mounted read-only."
-                       rootcheck=no
-               fi
-       fi
-
-       #
-       # The actual checking is done here.
-       #
-       if [ "$rootcheck" = yes ]
-       then
-               if [ -f /forcefsck ]
-               then
-                       force="-f"
-               else
-                       force=""
-               fi
-
-               if [ "$FSCKFIX" = yes ]
-               then
-                       fix="-y"
-               else
-                       fix="-a"
-               fi
-
-               spinner="-C"
-               case "$TERM" in
-                 dumb|network|unknown|"")
-                       spinner="" ;;
-               esac
-               # This Linux/s390 special case should go away.
-               if [ "${KERNEL}:${MACHINE}" = Linux:s390 ]
-               then
-monkey                 spinner=""
-               fi
-               
-               if [ "$VERBOSE" = no ]
-               then
-                       log_action_begin_msg "Checking root file system"
-                        if [ "$roottype" = "ext2" -o "$roottype" = "ext3" ] && pidof usplash; then
-                            PROGRESS_FILE=`mktemp -p /var/run` || PROGRESS_FILE=/var/run/checkroot_fsck
-                            set -m
-                            logsave -s $FSCK_LOGFILE fsck -C3 $force $fix -t $roottype $rootdev >/dev/console 2>&1 3>$PROGRESS_FILE &
-                            set +m
-                            usplash_progress "$PROGRESS_FILE"
-                            rm -f $PROGRESS_FILE
-                        else
-                            logsave -s $FSCK_LOGFILE fsck $spinner $force $fix -t $roottype $rootdev
-                            FSCKCODE=$?
-                        fi
-                       if [ "$FSCKCODE" = 0 ]
-                       then
-                               log_action_end_msg 0
-                       else
-                               log_action_end_msg 1 "code $FSCKCODE"
-                       fi
-               else
-                       log_action_msg "Will now check root file system"
-                       logsave -s $FSCK_LOGFILE fsck $spinner $force $fix -V -t $roottype $rootdev
-                       FSCKCODE=$?
-                       if [ "$FSCKCODE" = 0 ]
-                       then
-                               log_success_msg "Done checking root file system. 
-A log will be saved in ${FSCK_LOGFILE} if that location is writable."
-                       else
-                               log_failure_msg "Root file system check failed with error code ${FSCKCODE}. 
-A log is being saved in ${FSCK_LOGFILE} if that location is writable."
-                       fi
-               fi
-       fi
-
-       #
-       # If there was a failure, drop into single-user mode.
-       #
-       # NOTE: "failure" is defined as exiting with a return code of
-       # 4 or larger. A return code of 1 indicates that file system
-       # errors were corrected but that the boot may proceed. A return
-       # code of 2 or 3 indicates that the system should immediately reboot.
-       #
-       if [ "$FSCKCODE" -gt 3 ]
-       then
-               # Surprise! Re-directing from a HERE document (as in "cat << EOF")
-               # does not work because the root is currently read-only.
-               log_failure_msg "An automatic file system check (fsck) of the root filesystem failed. 
-A manual fsck must be performed, then the system restarted. 
-The fsck should be performed in maintenance mode with the 
-root filesystem mounted in read-only mode."
-               log_warning_msg "The root filesystem is currently mounted in read-only mode. 
-A maintenance shell will now be started. 
-After performing system maintenance, press CONTROL-D 
-to terminate the maintenance shell and restart the system."
-               # Start a single user shell on the console
-               if ! sulogin $CONSOLE
-               then
-                       log_failure_msg "Attempt to start maintenance shell failed. 
-Will restart in 5 seconds."
-                       sleep 5
-               fi
-               [ "$VERBOSE" = no ] || log_action_msg "Will now restart"
-               reboot -f
-       elif [ "$FSCKCODE" -gt 1 ]
-       then
-               log_failure_msg "The file system check corrected errors on the root partition 
-but requested that the system be restarted."
-               log_warning_msg "The system will be restarted in 5 seconds."
-               sleep 5
-               [ "$VERBOSE" = no ] || log_action_msg "Will now restart"
-               reboot -f
-       fi
-
-       #
-       # Remount root to final mode (rw or ro).
-       #
-       # See the comments above at the previous "mount -o remount"
-       # for an explanation why we try this twice.
-       #
-       if ! mount -n -o remount,$rootopts,$rootmode $fstabroot / 2>/dev/null
-       then
-               mount -n -o remount,$rootopts,$rootmode /
-       fi
-
-       #
-       # We only create/modify /etc/mtab if the location where it is
-       # stored is writable. If /etc/mtab is a symlink into /proc/
-       # then it is not writable.
-       #
-       INIT_MTAB_FILE=no
-       MTAB_PATH="$(readlink -f /etc/mtab || :)"
-       case "$MTAB_PATH" in
-         /proc/*)
-               ;;
-         /*)
-               if touch "$MTAB_PATH" >/dev/null 2>&1
-               then
-                       :> "$MTAB_PATH"
-                       rm -f ${MTAB_PATH}~
-                       INIT_MTAB_FILE=yes
-               fi
-               ;;
-         "")
-               [ -L /etc/mtab ] && MTAB_PATH="$(readlink /etc/mtab)"
-               if [ "$MTAB_PATH" ]
-               then
-                       log_failure_msg "Cannot initialize ${MTAB_PATH}."
-               else
-                       log_failure_msg "Cannot initialize /etc/mtab."
-               fi
-               ;;
-         *)
-               log_failure_msg "Illegal mtab location '${MTAB_PATH}'."
-               ;;
-       esac
-
-       if [ "$INIT_MTAB_FILE" = yes ]
-       then
-               [ "$roottype" != none ] &&
-                       mount -f -o $rootopts -t $roottype $fstabroot /
-               [ "$devfs" ] && mount -f $devfs
-       fi
-
-       #
-       # Remove /dev/shm/root if we created it.
-       #
-       rm -f /dev/shm/root
-}
-
-case "$1" in
-  start|"")
-       do_start
-       ;;
-  restart|reload|force-reload)
-       echo "Error: argument '$1' not supported" >&2
-       exit 3
-       ;;
-  stop)
-       # No-op
-       ;;
-  *)
-       echo "Usage: checkroot.sh [start|stop]" >&2
-       exit 3
-       ;;
-esac
-
-:
-#! /bin/sh
-#
-# This file was automatically customized by debmake on Fri,  6 Nov 1998 23:00:08 -0600
-#
-# Written by Miquel van Smoorenburg <miquels@drinkel.ow.org>.
-# Modified for Debian GNU/Linux by Ian Murdock <imurdock@gnu.ai.mit.edu>.
-# Modified for Debian by Christoph Lameter <clameter@debian.org>
-# Modified for chrony by John Hasler <jhasler@debian.org> 10 Nov 1998
-
-PATH=/bin:/usr/bin:/sbin:/usr/sbin
-DAEMON=/usr/sbin/chronyd
-FLAGS="defaults"
-NAME="chronyd"
-DESC="time daemon"
-
-test -f $DAEMON || exit 0
-
-case "$1" in
-  start)
-    start-stop-daemon --start --verbose --exec $DAEMON
-    ;;
-  stop)
-    start-stop-daemon --stop --verbose --oknodo --exec $DAEMON
-    ;;
-  restart|force-reload)
-        #
-        #       If the "reload" option is implemented, move the "force-reload"
-        #       option to the "reload" entry above. If not, "force-reload" is
-        #       just the same as "restart".
-        #                                                                                   
-        echo -n "Restarting $DESC: "
-        start-stop-daemon --stop --quiet --exec $DAEMON
-        sleep 1
-        start-stop-daemon --start --quiet --exec $DAEMON -- -r
-        echo "$NAME."
-        ;;
-  *)
-    echo "Usage: /etc/init.d/chrony {start|stop|restart|force-reload}"
-    exit 1
-    ;;
-esac
-
-exit 0
-#!/bin/sh
-### BEGIN INIT INFO
-# Provides:          console-screen
-# Required-Start:    $local_fs $remote_fs
-# Required-Stop:     $local_fs $remote_fs
-# Default-Start:     S 2 3 4 5
-# Default-Stop:      0 1 6
-# Should-Start:      $syslog
-# Should-Stop: 
-# Description: Set console screen modes and fonts
-# Short-Description:   Prepare console
-### END INIT INFO
-
-#
-# This is the boot script for the `console-tools' package.
-#
-# It loads parameters from /etc/console-tools/config, maybe loads
-# default screen-font, screen font-map, and application charset-map,
-# and maybe start "vcstime"
-#
-# (c) 1997 Yann Dirson
-
-# If setupcon is present, then we've been superseded by console-setup.
-if type setupcon >/dev/null 2>&1; then
-    exit 0
-fi
-
-# check if usplash is runing and skip this, we'll get run again later
-if pidof usplash > /dev/null; then
-    exit 0
-fi
-
-if [ -r /etc/console-tools/config ] ; then
-    . /etc/console-tools/config
-fi
-
-if [ -d /etc/console-tools/config.d ]; then
-    for i in `run-parts --list /etc/console-tools/config.d `; do
-       . $i
-    done
-fi
-
-. /lib/lsb/init-functions
-
-PATH=/sbin:/bin:/usr/sbin:/usr/bin
-SETFONT="/usr/bin/consolechars"
-SETFONT_OPT=""
-CHARSET="/usr/bin/charset"
-VCSTIME="/usr/sbin/vcstime"
-
-# Different device name for 2.6 kernels and devfs
-if [ `uname -r | cut -f 2 -d .` = 6 ] && [ -e /dev/.devfsd ]; then
-    VCSTIME_OPT="-2 /dev/vcsa0"
-else
-    VCSTIME_OPT=""
-fi
-
-
-
-# set DEVICE_PREFIX depending on devfs/udev
-if [ -d /dev/vc ]; then
-    DEVICE_PREFIX="/dev/vc/"
-else
-    DEVICE_PREFIX="/dev/tty"
-fi
-
-reset_vga_palette ()
-{
-       if [ -f /proc/fb ]; then
-           # They have a framebuffer device.
-           # That means we have work to do...
-           echo -n "\e]R"
-       fi
-}
-
-setup ()
-{
-    # be sure the main program is installed
-    [ -x "${SETFONT}" ] || return 0
-
-    VT="no"
-    # If we can't access the console, quit
-    CONSOLE_TYPE=`fgconsole 2>/dev/null` || return 0
-
-    if [ ! $CONSOLE_TYPE = "serial" ]  ; then
-       readlink /proc/self/fd/0 | grep -q -e /dev/vc -e '/dev/tty[^p]' -e /dev/console
-       if [ $? -eq 0 ] ; then
-           VT="yes"
-           reset_vga_palette
-       fi
-    fi
-
-    [ $VT = "no" ] && return 0
-
-    # start vcstime
-    if [ "${DO_VCSTIME}" = "yes" -a -x ${VCSTIME} ] ; then
-       [ "$VERBOSE" != "no" ] && log_action_begin_msg "Starting clock on text console"
-       ${VCSTIME} ${VCSTIME_OPT} &
-        [ "$VERBOSE" != "no" ] && log_action_end_msg 0
-    fi
-
-
-    # Global default font+sfm
-    if [ "${SCREEN_FONT}" ]
-       then
-       [ "$VERBOSE" != "no" ] && log_action_begin_msg "Setting up general console font"
-       SCREEN_FONT="-f ${SCREEN_FONT}"
-
-       # maybe use an external SFM
-       [ "${SCREEN_FONT_MAP}" ] && SCREEN_FONT_MAP="-u ${SCREEN_FONT_MAP}"
-
-       # Try to be cleverer and run for all consoles, but this is run
-       # _before_ getty and so only one console running. So,
-       # Set for the first 6 VCs (as they are allocated in /etc/inittab)
-       NUM_CONSOLES=`fgconsole --next-available`
-       NUM_CONSOLES=$(($NUM_CONSOLES - 1))
-       [ ${NUM_CONSOLES} -eq 1 ] && NUM_CONSOLES=6
-       i=1
-       while [ $i -le $NUM_CONSOLES ]
-           do
-           if ! ${SETFONT} --tty=${DEVICE_PREFIX}$i ${SETFONT_OPT} ${SCREEN_FONT} ${SCREEN_FONT_MAP} ; then
-             [ "$VERBOSE" != "no" ] && log_action_end_msg 1
-             break
-           elif [ "$i" -eq "$NUM_CONSOLES" ]; then
-             [ "$VERBOSE" != "no" ] && log_action_end_msg 0
-           fi
-           i=$(($i + 1))
-       done
-    fi
-
-
-    # Per-VC font+sfm
-    VCS="`set | grep '^SCREEN_FONT_vc[0-9]*=' | sed -e 's/^SCREEN_FONT_vc//' -e 's/=.*//'`"
-    if [ "${VCS}" ]
-       then
-       [ "$VERBOSE" != "no" ] && log_action_begin_msg "Setting up per-VC fonts"
-       for vc in ${VCS}
-         do
-           # extract FONTNAME info from variable setting
-         eval font=\$SCREEN_FONT_vc$vc
-         # eventually find an associated SFM
-         eval sfm=\${SCREEN_FONT_MAP_vc${vc}}
-         [ "$sfm" ] && sfm="-u $sfm"
-
-         ${SETFONT} --tty=${DEVICE_PREFIX}$vc ${SETFONT_OPT} -f $font $sfm
-       done
-       [ "$VERBOSE" != "no" ] && log_action_end_msg 0
-    fi
-
-
-    # Global ACM
-    [ "${APP_CHARSET_MAP}" ] && ${CHARSET} G0 ${APP_CHARSET_MAP}
-
-
-    # Per-VC ACMs
-    VCS="`set | grep '^APP_CHARSET_MAP_vc[0-9]*=' | sed -e 's/^APP_CHARSET_MAP_vc//' -e 's/=.*//'`"
-    if [ "${VCS}" ]
-       then
-       [ "$VERBOSE" != "no" ] && log_action_begin_msg "Setting up per-VC ACM\'s"
-       for vc in ${VCS}
-         do
-           # extract FONTNAME info from variable setting
-         eval acm=\$APP_CHARSET_MAP_vc$vc
-         ${CHARSET} --tty="${DEVICE_PREFIX}$vc" G0 "$acm"
-       done
-       [ "$VERBOSE" != "no" ] && log_action_end_msg 0
-    fi
-
-
-    # Go to UTF-8 mode as necessary
-    # 
-    ENV_FILE=''
-    [ -r /etc/environment ] && ENV_FILE="/etc/environment"
-    [ -r /etc/default/locale ] && ENV_FILE="/etc/default/locale"
-    [ "$ENV_FILE" ] && CHARMAP=$(set -a && . "$ENV_FILE" && locale charmap)
-    if test "$CHARMAP" = "UTF-8" 
-    then
-        unicode_start 2> /dev/null || true
-    else
-        unicode_stop 2> /dev/null|| true
-    fi
-
-    # screensaver stuff
-    setterm_args=""
-    if [ "$BLANK_TIME" ]; then
-        setterm_args="$setterm_args -blank $BLANK_TIME"
-    fi
-    if [ "$BLANK_DPMS" ]; then
-        setterm_args="$setterm_args -powersave $BLANK_DPMS"
-    fi
-    if [ "$POWERDOWN_TIME" ]; then
-        setterm_args="$setterm_args -powerdown $POWERDOWN_TIME"
-    fi
-    if [ "$setterm_args" ]; then
-        setterm $setterm_args 
-    fi
-
-    # Keyboard rate and delay
-    KBDRATE_ARGS=""
-    if [ -n "$KEYBOARD_RATE" ]; then
-        KBDRATE_ARGS="-r $KEYBOARD_RATE"
-    fi
-    if [ -n "$KEYBOARD_DELAY" ]; then
-        KBDRATE_ARGS="$KBDRATE_ARGS -d $KEYBOARD_DELAY"
-    fi
-    if [ -n "$KBDRATE_ARGS" ]; then
-       [ "$VERBOSE" != "no" ] && log_action_begin_msg "Setting keyboard rate and delay"
-        kbdrate -s $KBDRATE_ARGS
-       [ "$VERBOSE" != "no" ] && log_action_end_msg 0
-    fi
-
-    # Inform gpm if present, of potential changes.
-    if [ -f /var/run/gpm.pid ]; then
-       kill -WINCH `cat /var/run/gpm.pid` 2> /dev/null
-    fi
-
-    # Allow user to remap keys on the console
-    if [ -r /etc/console-tools/remap ]
-       then
-       dumpkeys < ${DEVICE_PREFIX}1 | sed -f /etc/console-tools/remap | loadkeys --quiet
-    fi
-    # Set LEDS here
-    if [ "$LEDS" != "" ]
-       then
-       i=1
-       while [ $i -le $NUM_CONSOLES ]
-         do
-          setleds -D $LEDS < $DEVICE_PREFIX$i
-         i=$(($i + 1))
-       done
-    fi
-}
-
-case "$1" in
-    start|reload|restart|force-reload)
-       log_action_msg "Setting console screen modes and fonts"
-       setup
-       ;;
-    stop)
-       ;;
-    *)
-       setup
-       ;;
-esac
-#!/bin/sh
-# Start/stop the cron daemon.
-#
-### BEGIN INIT INFO
-# Provides:          cron
-# Required-Start:    $syslog $time
-# Required-Stop:     $syslog $time
-# Default-Start:     2 3 4 5
-# Default-Stop:      0 1 6
-# Short-Description: Regular background program processing daemon
-# Description:       cron is a standard UNIX program that runs user-specified 
-#                    programs at periodic scheduled times. vixie cron adds a 
-#                    number of features to the basic UNIX cron, including better
-#                    security and more powerful configuration options.
-### END INIT INFO
-
-
-test -f /usr/sbin/cron || exit 0
-
-#LSBNAMES='-l'  # Uncomment for LSB name support in /etc/cron.d/
-
-. /lib/lsb/init-functions
-
-case "$1" in
-start) log_daemon_msg "Starting periodic command scheduler" "crond"
-        start-stop-daemon --start --quiet --pidfile /var/run/crond.pid --name cron --startas /usr/sbin/cron -- $LSBNAMES
-        log_end_msg $?
-       ;;
-stop)  log_daemon_msg "Stopping periodic command scheduler" "crond"
-        start-stop-daemon --stop --quiet --pidfile /var/run/crond.pid --name cron
-        log_end_msg $?
-        ;;
-restart) log_daemon_msg "Restarting periodic command scheduler" "crond" 
-        start-stop-daemon --stop --retry 5 --quiet --pidfile /var/run/crond.pid --name cron
-        start-stop-daemon --start --quiet --pidfile /var/run/crond.pid --name cron --startas /usr/sbin/cron -- $LSBNAMES
-        log_end_msg $?
-        ;;
-reload|force-reload) log_daemon_msg "Reloading configuration files for periodic command scheduler" "crond"
-       # cron reloads automatically
-        log_end_msg 0
-        ;;
-*)     log_action_msg "Usage: /etc/init.d/cron {start|stop|restart|reload|force-reload}"
-        exit 2
-        ;;
-esac
-exit 0
-#!/bin/sh
-### BEGIN INIT INFO
-# Provides:          dbus
-# Required-Start:    $remote_fs $syslog
-# Required-Stop:     $remote_fs $syslog
-# Default-Start:     2 3 4 5
-# Default-Stop:      1
-# Short-Description: D-Bus systemwide message bus
-# Description:       D-Bus is a simple interprocess messaging system, used
-#                    for sending messages between applications.
-### END INIT INFO
-# -*- coding: utf-8 -*-
-# Debian init.d script for D-BUS
-# Copyright Â© 2003 Colin Walters <walters@debian.org>
-# Copyright Â© 2005 Sjoerd Simons <sjoerd@debian.org>
-
-set -e
-
-DAEMON=/usr/bin/dbus-daemon
-UUIDGEN=/usr/bin/dbus-uuidgen
-UUIDGEN_OPTS=--ensure
-NAME=dbus
-DAEMONUSER=messagebus
-PIDDIR=/var/run/dbus
-PIDFILE=$PIDDIR/pid
-DESC="system message bus"
-EVENTDIR=/etc/dbus-1/event.d
-
-test -x $DAEMON || exit 0
-
-. /lib/lsb/init-functions
-
-# Source defaults file; edit that file to configure this script.
-PARAMS=""
-if [ -e /etc/default/dbus ]; then
-  . /etc/default/dbus
-fi
-
-if [ -n "$ENABLED" ]; then
-    log_warning_msg "The ENABLED option in /etc/default/$NAME has been deprecated."
-    log_warning_msg "Please remove this setting from the configuration file."
-    log_warning_msg "To disable the service use a runlevel editor like sysv-rc-conf or bum instead."
-fi
-
-create_machineid() {
-  # Create machine-id file
-  if [ -x $UUIDGEN ]; then
-    $UUIDGEN $UUIDGEN_OPTS
-  fi
-}
-
-dependent_services()
-{
-  # Do nothing if we are called by init
-  [ ! -z $runlevel ] && return 
-
-  # Determine current runlevel
-  r=$(/sbin/runlevel) || true
-  r=${r#*\ }
-
-  # Do nothing if we can't determine the runlevel (e.g. inside chroots)
-  [ "$r" = "unknown" ] && return
-
-  if [ "$1" = "stop" ] ; then
-    param="--reverse"
-    action="stop"
-  else
-    param=""
-    action="start"
-  fi
-
-  # Get the list of services active in this runlevel
-  if [ -d /etc/rc${r}.d/ ] ; then # sysv-rc
-    services=$(grep -s -l "^# Required-Start:.*dbus" /etc/rc${r}.d/S??* | sort $param)
-  elif [ -f /etc/runlevel.conf ] ; then # file-rc
-    list=$(grep -s -l "^# Required-Start:.*dbus" /etc/init.d/* || true)
-    services=$( for i in $list ; do
-      grep -E "^[[:digit:]]{2}[[:space:]]+([0-9,S]+|[-])[[:space:]]+.*$r.*[[:space:]]+$i$" /etc/runlevel.conf
-    done  | sort $param | awk '{print $4}' )
-  else
-    services=""
-    log_warning_msg "Unable to determine dependent services: unknown init system"
-  fi
-
-  # Start the services in the correct order
-  for i in $services ; do
-    service=$(basename $i)
-    service=${service#S??}
-    invoke-rc.d $service $action || true
-  done
-
-}
-
-
-start_it_up()
-{
-  if [ ! -d $PIDDIR ]; then
-    mkdir -p $PIDDIR
-    chown $DAEMONUSER $PIDDIR
-    chgrp $DAEMONUSER $PIDDIR
-  fi
-
-  if ! mountpoint -q /proc/ ; then
-    log_failure_msg "Can't start $DESC - /proc is not mounted"
-    return
-  fi
-
-  if [ -e $PIDFILE ]; then
-    PIDDIR=/proc/$(cat $PIDFILE)
-    if [ -d ${PIDDIR} -a  "$(readlink -f ${PIDDIR}/exe)" = "${DAEMON}" ]; then 
-      log_success_msg "$DESC already started; not starting."
-      return
-    else
-      log_success_msg "Removing stale PID file $PIDFILE."
-      rm -f $PIDFILE
-    fi
-  fi
-
-  create_machineid
-
-  log_daemon_msg "Starting $DESC" "$NAME"
-  start-stop-daemon --start --quiet --pidfile $PIDFILE \
-    --user $DAEMONUSER --exec $DAEMON -- --system $PARAMS
-  log_end_msg $?
-  if [ -d $EVENTDIR ]; then
-      run-parts --arg=start $EVENTDIR || true
-  fi
-  dependent_services start
-}
-
-shut_it_down()
-{
-  dependent_services stop
-  if [ -d $EVENTDIR ]; then
-      run-parts --reverse --arg=stop $EVENTDIR || true
-  fi
-  log_daemon_msg "Stopping $DESC" "$NAME"
-  start-stop-daemon --stop --retry 5 --quiet --oknodo --pidfile $PIDFILE \
-    --user $DAEMONUSER
-  # We no longer include these arguments so that start-stop-daemon
-  # can do its job even given that we may have been upgraded.
-  # We rely on the pidfile being sanely managed
-  # --exec $DAEMON -- --system $PARAMS
-  log_end_msg $?
-  rm -f $PIDFILE
-}
-
-reload_it()
-{
-  create_machineid
-  log_action_begin_msg "Reloading $DESC config"
-  dbus-send --print-reply --system --type=method_call \
-            --dest=org.freedesktop.DBus \
-            / org.freedesktop.DBus.ReloadConfig > /dev/null
-  # hopefully this is enough time for dbus to reload it's config file.
-  log_action_end_msg $?
-}
-
-case "$1" in
-  start)
-    start_it_up
-  ;;
-  stop)
-    shut_it_down
-  ;;
-  reload|force-reload)
-    reload_it
-  ;;
-  restart)
-    shut_it_down
-    start_it_up
-  ;;
-  *)
-    echo "Usage: /etc/init.d/$NAME {start|stop|reload|restart|force-reload}" >&2
-    exit 2
-  ;;
-esac
-
-#! /bin/sh
-
-# $Id: dns-clean,v 1.1.1.1 2004/05/07 03:12:59 john Exp $
-
-# dns-clean by John Hasler 1999-2003
-# Any possessor of a copy of this program may treat it as if it
-# were in the public domain.  I waive all rights.
-
-# This script should be run at bootup to clean up any mess left by 0dns-up.
-# It should be run before ppp is started.
-# It should never be run while ppp is up.
-
-### BEGIN INIT INFO
-# Provides:          dns-clean
-# Required-Start:    $local_fs
-# Required-Stop:     $local_fs
-# Default-Start:     S
-# Default-Stop:
-# Short-Description: Cleans up any mess left by 0dns-up
-# Description: 0dns-up often leaves behind some cruft. This Script is meant
-#              to clean up any such mess.
-### END INIT INFO
-
-PATH=/sbin:/bin:/usr/sbin:/usr/bin
-
-test -f /usr/sbin/pppconfig || exit 0
-# We might have a tmpfs /var/run.
-mkdir /var/run/pppconfig >/dev/null 2>&1 || true
-test -f /etc/ppp/ip-down.d/0dns-down || exit 0
-
-. /lib/lsb/init-functions
-. /etc/default/rcS
-
-case "$1" in
-  start)
-       [ "$VERBOSE" != no ] && log_begin_msg "Restoring resolver state..."
-       /etc/ppp/ip-down.d/0dns-down "0dns-clean"
-       [ "$VERBOSE" != no ] && log_end_msg $?
-       ;;
-  stop|restart|force-reload)
-       ;;
-  *)
-        ;;
-esac
-
-exit 0
-
-happikins
-
-#! /bin/sh
-#
-# evms          Enterprise Volume Management System
-#
-#              Written by Miquel van Smoorenburg <miquels@cistron.nl>.
-#              Modified for Debian GNU/Linux
-#              by Ian Murdock <imurdock@gnu.ai.mit.edu>.
-#               Modified for evms package
-#               by Matt Zimmerman <mdz@debian.org>
-#
-
-### BEGIN INIT INFO
-# Provides:          evms
-# Default-Start:     2 3 4 5
-# Default-Stop:      0 1 6
-# Required-Start:    
-# Required-Stop:     
-# Short-Description: Activates EVMS volumes
-# Description:       Activates any EVMS volumes that are left unactivated
-#                    by the initramfs for some reason (or if the user does
-#                    not use initramfs). This possibly includes setting up
-#                    RAID, LVM, snapshots, BBR etc., but does not start a
-#                    service.
-### END INIT INFO
-
-PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
-NAME=evms
-DESC="Enterprise Volume Management System"
-
-test -x /sbin/evms_activate || exit 0
-
-. /lib/lsb/init-functions
-. /etc/default/rcS
-
-set -e
-
-case "$1" in
-  start|reload|restart|force-reload)
-       log_begin_msg "Starting $DESC..."
-       status=0
-       if [ "$VERBOSE" != no ]; then
-               evms_activate || status=$?
-       else
-               # Messages are still written to the log
-               evms_activate >/dev/null 2>&1 || status=$?
-       fi
-       log_end_msg $status
-       ;;
-  stop)
-       ;;
-  status)
-       echo "no daemons started by this script"
-        log_end_msg 0
-       ;;
-  *)
-       N=/etc/init.d/$NAME
-       log_success_msg "Usage: $N {start|stop|restart|reload|force-reload|status}"
-       exit 1
-       ;;
-esac
-
-exit 0
-#! /bin/sh
-#
-# Originally based on:
-# Version:     @(#)skeleton  1.8  03-Mar-1998  miquels@cistron.nl
-#
-# Modified for gdm, Steve Haslam <steve@arise.dmeon.co.uk> 14mar99
-# modified to remove --exec, as it does not work on upgrades. 18jan2000
-# modified to use --name, to detect stale PID files 18mar2000
-# sleep until gdm dies, then restart it 16jul2000
-# get along with other display managers (Branden Robinson, Ryan Murray) 05sep2001
-
-set -e
-
-# To start gdm even if it is not the default display manager, change
-# HEED_DEFAULT_DISPLAY_MANAGER to "false."
-HEED_DEFAULT_DISPLAY_MANAGER=true
-DEFAULT_DISPLAY_MANAGER_FILE=/etc/X11/default-display-manager
-PATH=/sbin:/bin:/usr/sbin:/usr/bin
-DAEMON=/usr/sbin/gdm
-PIDFILE=/var/run/gdm.pid
-UPGRADEFILE=/var/run/gdm.upgrade
-
-if [ -e $UPGRADEFILE -a "$1" != "restart" -a "$1" != "force-reload" ]; then
-       SSD_ARG="--startas $DAEMON"
-       rm -f $UPGRADEFILE
-else
-       SSD_ARG="--exec $DAEMON"
-fi
-
-# Allow cdd to override the config
-if [ -f /etc/gdm/gdm-cdd.conf ]; then
-       CONFIG_FILE="--config=/etc/gdm/gdm-cdd.conf"
-fi
-
-test -x $DAEMON || exit 0
-
-if [ -r /etc/environment ]; then
-  if LANG=$(pam_getenv -l LANG); then
-    export LANG
-  fi
-  if LANGUAGE=$(pam_getenv -l LANGUAGE); then
-    export LANGUAGE
-  fi
-
-fi
-
-. /lib/lsb/init-functions
-
-case "$1" in
-  start)
-       if [ -e "$DEFAULT_DISPLAY_MANAGER_FILE" -a "$HEED_DEFAULT_DISPLAY_MANAGER" = "true" -a "$(cat $DEFAULT_DISPLAY_MANAGER_FILE 2>/dev/null)" != "$DAEMON" ]; then
-               log_warning_msg "Not starting GNOME Display Manager (gdm); it is not the default display manager."
-       else
-               # if usplash is runing, make sure to stop it now, yes "start" kills it.
-               if pidof usplash > /dev/null; then
-                       /etc/init.d/usplash start
-               fi
-               log_begin_msg "Starting GNOME Display Manager..."
-               start-stop-daemon --start --quiet --oknodo --pidfile $PIDFILE --name gdm $SSD_ARG -- $CONFIG_FILE >/dev/null 2>&1 || log_end_msg 1
-               log_end_msg 0
-       fi
-  ;;
-  stop)
-       log_begin_msg "Stopping GNOME Display Manager..."
-       start-stop-daemon --stop  --quiet --oknodo --pidfile $PIDFILE --name gdm $SSD_ARG --retry 30 >/dev/null 2>&1
-       log_end_msg 0
-  ;;
-  reload)
-       log_begin_msg "Reloading GNOME Display Manager configuration..."
-       log_warning_msg "Changes will take effect when all current X sessions have ended."
-       start-stop-daemon --stop --signal USR1 --quiet --pidfile \
-               $PIDFILE --name gdm $SSD_ARG >/dev/null 2>&1
-       log_end_msg 0
-  ;;
-  restart|force-reload)
-       $0 stop || true
-       $0 start
-  ;;
-  *)
-       log_success_msg "Usage: /etc/init.d/gdm {start|stop|restart|reload|force-reload}"
-       exit 1
-  ;;
-esac
-
-exit 0
-#! /bin/sh -e
-#
-### BEGIN INIT INFO
-# Provides:          glibc
-# Required-Start:
-# Required-Stop:
-# Default-Start:     S
-# Default-Stop:
-### END INIT INFO
-#
-# 
-# This script detects deprecated kernel versions incompatible with
-# the current version of the glibc
-
-# glibc kernel version check: KERNEL_VERSION_CHECK
-linux_compare_versions () {
-    verA=$(($(echo "$1" | sed 's/\([0-9]*\)\.\([0-9]*\)\.\([0-9]*\).*/\1 \* 10000 + \2 \* 100 + \3/')))
-    verB=$(($(echo "$3" | sed 's/\([0-9]*\)\.\([0-9]*\)\.\([0-9]*\).*/\1 \* 10000 + \2 \* 100 + \3/')))
-
-    test $verA -$2 $verB
-}
-
-kfreebsd_compare_versions () {
-    verA=$(($(echo "$1" | sed 's/\([0-9]*\)\.\([0-9]*\).*/\1 \* 100 + \2/')))
-    verB=$(($(echo "$3" | sed 's/\([0-9]*\)\.\([0-9]*\).*/\1 \* 100 + \2/')))
-
-    test $verA -$2 $verB
-}
-
-kernel26_help() {
-    echo ""
-    echo "The installation of a 2.6 kernel _could_ ask you to install a new libc"
-    echo "first, this is NOT a bug, and should *NOT* be reported. In that case,"
-    echo "please add etch sources to your /etc/apt/sources.list and run:"
-    echo "  apt-get install -t etch linux-image-2.6"
-    echo "Then reboot into this new kernel, and proceed with your upgrade"
-}
-
-exit_check () {
-    sleep 5
-    exit 1
-}
-
-    system=`uname -s`
-    if [ "$system" = "Linux" ]
-    then
-        # Test to make sure z < 255, in x.y.z-n form of kernel version
-        # Also make sure we don't trip on x.y.zFOO-n form
-        #kernel_rev=$(uname -r | tr -- - . | cut -d. -f3 | tr -d '[:alpha:]')
-        kernel_rev=$(uname -r | sed 's/\([0-9]*\.[0-9]*\.\)\([0-9]*\)\(.*\)/\2/')
-        if [ "$kernel_rev" -ge 255 ]
-        then
-            echo "WARNING: Your kernel version indicates a revision number"
-            echo "of 255 or greater.  Glibc has a number of built in"
-            echo "assumptions that this revision number is less than 255."
-            echo "If you\'ve built your own kernel, please make sure that any"
-            echo "custom version numbers are appended to the upstream"
-            echo "kernel number with a dash or some other delimiter."
-
-            exit_check
-        fi
-
-        # sanity checking for the appropriate kernel on each architecture.
-        realarch=`uname -m`
-        kernel_ver=`uname -r`
-
-        # convert "armv4l" and similar to just "arm", and "mips64" and similar
-        # to just "mips"
-        case $realarch in
-          arm*) realarch="arm";;
-          mips*) realarch="mips";;
-        esac
-
-
-        # From glibc 2.3.5-7 real-i386 is dropped.
-        if [ "$realarch" = i386 ]
-        then
-            echo "WARNING: This machine has real i386 class processor."
-            echo "Debian etch and later does not support such old hardware"
-            echo "any longer."
-            echo "The reason is that \"bswap\" instruction is not supported"
-            echo "on i386 class processors, and some core libraries have"
-            echo "such instruction.  You\'ll see illegal instruction error"
-            echo "when you upgrade your Debian system."
-            exit_check
-        fi
-
-        # arm boxes require __ARM_NR_set_tls in the kernel to function properly.
-        if [ "$realarch" = arm ]
-        then
-            if linux_compare_versions "$kernel_ver" lt 2.6.12
-            then
-                echo WARNING: This version of glibc requires that you be running
-                echo kernel version 2.6.12 or later.  Earlier kernels contained
-                echo bugs that may render the system unusable if a modern version
-                echo of glibc is installed.
-                kernel26_help
-                exit_check
-            fi 
-        fi
-
-        # Alpha and HPPA boxes require latest fixes in the kernel to function properly.
-        if [ "$realarch" = parisc -o "$realarch" = alpha ]
-        then
-            if linux_compare_versions "$kernel_ver" lt 2.6.9
-            then
-                echo WARNING: This version of glibc requires that you be running
-                echo kernel version 2.6.9 or later.  Earlier kernels contained
-                echo bugs that may render the system unusable if a modern version
-                echo of glibc is installed.
-                kernel26_help
-                exit_check
-            fi
-        fi
-
-        # sh4 boxes require kernel version 2.6.11 minimum
-        if [ "$realarch" = sh4 ]
-        then
-            if linux_compare_versions "$kernel_ver" lt 2.6.11
-            then
-                echo WARNING: This version of glibc requires that you be running
-                echo kernel version 2.6.11 or later.  Earlier kernels contained
-                echo bugs that may render the system unusable if a modern version
-                echo of glibc is installed.
-                kernel26_help
-                exit_check
-            fi 
-        fi
-
-        # The GNU libc requires 2.6 kernel (except on m68k) because we drop to
-        # support linuxthreads
-        if [ "$realarch" != m68k ]
-        then
-            if linux_compare_versions "$kernel_ver" lt 2.6.8
-            then
-                echo WARNING: POSIX threads library NPTL requires kernel version
-                echo 2.6.8 or later.  If you use a kernel 2.4, please upgrade it
-                echo before installing glibc.
-                kernel26_help
-                exit_check
-            fi
-        fi
-
-        # The GNU libc is now built with --with-kernel= >= 2.4.1 on m68k
-        if [ "$realarch" = m68k ]
-        then
-            if linux_compare_versions "$kernel_ver" lt 2.4.1
-            then
-                echo WARNING: This version of glibc requires that you be running
-                echo kernel version 2.4.1 or later.  Earlier kernels contained
-                echo bugs that may render the system unusable if a modern version
-                echo of glibc is installed.
-                kernel26_help
-                exit_check
-            fi
-        fi
-
-        # From glibc 2.6-3 SPARC V8 support is dropped.
-        if [ "$realarch" = sparc ]
-        then
-            # The process could be run using linux32, check for /proc.
-            if [ -f /proc/cpuinfo ]
-            then
-               case "$(sed '/^type/!d;s/^type.*: //g' /proc/cpuinfo)" in
-                   sun4u)
-                      # UltraSPARC CPU
-                      ;;
-                   sun4v)
-                      # Niagara CPU
-                      ;;
-                   *)
-                      echo "WARNING: This machine has a SPARC V8 or earlier class processor."
-                      echo "Debian lenny and later does not support such old hardware"
-                      echo "any longer."
-                      exit_check
-                      ;;
-               esac
-            fi
-        fi
-    elif [ $system = "GNU/kFreeBSD" ] ; then
-        kernel_ver=`uname -r`
-        if kfreebsd_compare_versions "$kernel_ver" lt 6.0
-        then
-            echo WARNING: This version of glibc uses UMTX_OP_WAIT and UMTX_OP_WAKE
-           echo syscalls that are not present in the current running kernel. They
-           echo have been added in kFreeBSD 6.0.  Your system should still work,
-           echo but it is recommended to upgrade to a more recent version.
-        fi
-    fi
-
-: exit 0
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          halt
-# Required-Start:    umountroot
-# Required-Stop:
-# Should-Start:      lvm raid2
-# Should-Stop:
-# Default-Start:     0
-# Default-Stop:
-# Short-Description: Execute the halt command.
-# Description:
-### END INIT INFO
-
-PATH=/usr/sbin:/usr/bin:/sbin:/bin
-[ -f /etc/default/halt ] && . /etc/default/halt
-
-. /lib/lsb/init-functions
-
-do_stop () {
-       if [ "$INIT_HALT" = "" ]
-       then
-               case "$HALT" in
-                 [Pp]*)
-                       INIT_HALT=POWEROFF
-                       ;;
-                 [Hh]*)
-                       INIT_HALT=HALT
-                       ;;
-                 *)
-                       INIT_HALT=POWEROFF
-                       ;;
-               esac
-       fi
-
-       # See if we need to cut the power.
-       if [ "$INIT_HALT" = "POWEROFF" ] && [ -x /etc/init.d/ups-monitor ]
-       then
-               /etc/init.d/ups-monitor poweroff
-       fi
-
-       # Don't shut down drives if we're using RAID.
-       hddown="-h"
-       if grep -qs '^md.*active' /proc/mdstat
-       then
-               hddown=""
-       fi
-
-       # If INIT_HALT=HALT don't poweroff.
-       poweroff="-p"
-       if [ "$INIT_HALT" = "HALT" ]
-       then
-               poweroff=""
-       fi
-
-       log_action_msg "Will now halt"
-       sleep 1
-       halt -d -f -i $poweroff $hddown
-}
-
-case "$1" in
-  start)
-       # No-op
-       ;;
-  restart|reload|force-reload)
-       echo "Error: argument '$1' not supported" >&2
-       exit 3
-       ;;
-  stop)
-       do_stop
-       ;;
-  *)
-       echo "Usage: $0 start|stop" >&2
-       exit 3
-       ;;
-esac
-
-:
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          hostname
-# Required-Start:
-# Required-Stop:
-# Default-Start:     S
-# Default-Stop:
-# Short-Description: Set hostname.
-# Description:
-### END INIT INFO
-
-PATH=/sbin:/bin
-
-. /lib/init/vars.sh
-. /lib/lsb/init-functions
-
-do_start () {
-       [ -f /etc/hostname ] && HOSTNAME="$(cat /etc/hostname)"
-
-       # Keep current name if /etc/hostname is missing.
-       [ -z "$HOSTNAME" ] && HOSTNAME="$(hostname)"
-
-       # And set it to 'localhost' if no setting was found
-       [ -z "$HOSTNAME" ] && HOSTNAME=localhost
-
-       [ "$VERBOSE" != no ] && log_action_begin_msg "Setting hostname to '$HOSTNAME'"
-       hostname "$HOSTNAME"
-       ES=$?
-       [ "$VERBOSE" != no ] && log_action_end_msg $ES
-}
-
-case "$1" in
-  start|"")
-       do_start
-       ;;
-  restart|reload|force-reload)
-       echo "Error: argument '$1' not supported" >&2
-       exit 3
-       ;;
-  stop)
-       # No-op
-       ;;
-  *)
-       echo "Usage: hostname.sh [start|stop]" >&2
-       exit 3
-       ;;
-esac
-#!/bin/sh
-# hwclock.sh   Set and adjust the CMOS clock, according to the UTC
-#              setting in /etc/default/rcS (see also rcS(5)).
-#
-# Version:     @(#)hwclock.sh  2.00  14-Dec-1998  miquels@cistron.nl
-#
-# Patches:
-#              2000-01-30 Henrique M. Holschuh <hmh@rcm.org.br>
-#               - Minor cosmetic changes in an attempt to help new
-#                 users notice something IS changing their clocks
-#                 during startup/shutdown.
-#               - Added comments to alert users of hwclock issues
-#                 and discourage tampering without proper doc reading.
-
-# WARNING:     Please read /usr/share/doc/util-linux/README.Debian.hwclock
-#              before changing this file. You risk serious clock
-#              misbehaviour otherwise.
-
-### BEGIN INIT INFO
-# Provides:          hwclockfirst
-# Required-Start:    mountdevsubfs
-# Required-Stop:     umountroot
-# Default-Start:     S
-# Default-Stop:      0 6
-### END INIT INFO
-
-FIRST=yes      # debian/rules sets this to 'yes' when creating hwclockfirst.sh
-
-# Set this to any options you might need to give to hwclock, such
-# as machine hardware clock type for Alphas.
-HWCLOCKPARS=
-
-hwclocksh()
-{
-    [ ! -x /sbin/hwclock ] && return 0
-    . /etc/default/rcS
-
-    . /lib/lsb/init-functions
-    verbose_log_action_msg() { [ "$VERBOSE" = no ] || log_action_msg "$@"; }
-
-    [ "$GMT" = "-u" ] && UTC="yes"
-    case "$UTC" in
-       no|"")  GMT="--localtime"
-               UTC=""
-               if [ "X$FIRST" = "Xyes" ] && [ ! -r /etc/localtime ]; then
-                   if [ -z "$TZ" ]; then
-                       log_action_msg "System clock was not updated at this time"
-                       return 1
-                   fi
-               fi
-               ;;
-       yes)    GMT="--utc"
-               UTC="--utc"
-               ;;
-       *)      log_action_msg "Unknown UTC setting: \"$UTC\""; return 1 ;;
-    esac
-
-    case "$BADYEAR" in
-       no|"")  BADYEAR="" ;;
-       yes)    BADYEAR="--badyear" ;;
-       *)      log_action_msg "unknown BADYEAR setting: \"$BADYEAR\""; return 1 ;;
-    esac
-
-    case "$1" in
-       start)
-           if [ -w /etc ] && [ ! -f /etc/adjtime ] && [ ! -e /etc/adjtime ]; then
-               echo "0.0 0 0.0" > /etc/adjtime
-           fi
-
-           if [ ! -w /etc/adjtime ]; then
-               NOADJ="--noadjfile"
-           else
-               NOADJ=""
-           fi
-
-           if [ "$FIRST" != yes ]; then
-               # Uncomment the hwclock --adjust line below if you want
-               # hwclock to try to correct systematic drift errors in the
-               # Hardware Clock.
-               #
-               # WARNING: If you uncomment this option, you must either make
-               # sure *nothing* changes the Hardware Clock other than
-               # hwclock --systohc, or you must delete /etc/adjtime
-               # every time someone else modifies the Hardware Clock.
-               #
-               # Common "vilains" are: ntp, MS Windows, the BIOS Setup
-               # program.
-               #
-               # WARNING: You must remember to invalidate (delete)
-               # /etc/adjtime if you ever need to set the system clock
-               # to a very different value and hwclock --adjust is being
-               # used.
-               #
-               # Please read /usr/share/doc/util-linux/README.Debian.hwclock
-               # before enabling hwclock --adjust.
-
-               #/sbin/hwclock --adjust $GMT $BADYEAR
-               :
-           fi
-
-           if [ "$HWCLOCKACCESS" != no ]; then
-               log_action_msg "Setting the system clock"
-
-               # Copies Hardware Clock time to System Clock using the correct
-               # timezone for hardware clocks in local time, and sets kernel
-               # timezone. DO NOT REMOVE.
-               if /sbin/hwclock --hctosys $GMT $HWCLOCKPARS $BADYEAR $NOADJ; then
-                   #   Announce the local time.
-                   verbose_log_action_msg "System Clock set to: `date $UTC`"
-               else
-                   log_warning_msg "Unable to set System Clock to: `date $UTC`"
-               fi
-           else
-               verbose_log_action_msg "Not setting System Clock"
-           fi
-           ;;
-       stop|restart|reload|force-reload)
-           #
-           # Updates the Hardware Clock with the System Clock time.
-           # This will *override* any changes made to the Hardware Clock.
-           #
-           # WARNING: If you disable this, any changes to the system
-           #          clock will not be carried across reboots.
-           #
-           if [ "$HWCLOCKACCESS" != no ]; then
-               log_action_msg "Saving the system clock"
-               if [ "$GMT" = "-u" ]; then
-                   GMT="--utc"
-               fi
-               if /sbin/hwclock --systohc $GMT $HWCLOCKPARS $BADYEAR; then
-                   verbose_log_action_msg "Hardware Clock updated to `date`"
-               fi
-           else
-               verbose_log_action_msg "Not saving System Clock"
-           fi
-           ;;
-       show)
-           if [ "$HWCLOCKACCESS" != no ]; then
-               /sbin/hwclock --show $GMT $HWCLOCKPARS $BADYEAR
-           fi
-           ;;
-       *)
-           log_success_msg "Usage: hwclock.sh {start|stop|reload|force-reload|show}"
-           log_success_msg "       start sets kernel (system) clock from hardware (RTC) clock"
-           log_success_msg "       stop and reload set hardware (RTC) clock from kernel (system) clock"
-           return 1
-           ;;
-    esac
-}
-
-hwclocksh "$@"
-#!/bin/sh
-# hwclock.sh   Set and adjust the CMOS clock, according to the UTC
-#              setting in /etc/default/rcS (see also rcS(5)).
-#
-# Version:     @(#)hwclock.sh  2.00  14-Dec-1998  miquels@cistron.nl
-#
-# Patches:
-#              2000-01-30 Henrique M. Holschuh <hmh@rcm.org.br>
-#               - Minor cosmetic changes in an attempt to help new
-#                 users notice something IS changing their clocks
-#                 during startup/shutdown.
-#               - Added comments to alert users of hwclock issues
-#                 and discourage tampering without proper doc reading.
-
-# WARNING:     Please read /usr/share/doc/util-linux/README.Debian.hwclock
-#              before changing this file. You risk serious clock
-#              misbehaviour otherwise.
-
-### BEGIN INIT INFO
-# Provides:          hwclock
-# Required-Start:    mountdevsubfs
-# Required-Stop:     $local_fs
-# Default-Start:     S
-# Default-Stop:      0 6
-### END INIT INFO
-
-FIRST=no       # debian/rules sets this to 'yes' when creating hwclockfirst.sh
-
-# Set this to any options you might need to give to hwclock, such
-# as machine hardware clock type for Alphas.
-HWCLOCKPARS=
-
-hwclocksh()
-{
-    [ ! -x /sbin/hwclock ] && return 0
-    . /etc/default/rcS
-
-    . /lib/lsb/init-functions
-    verbose_log_action_msg() { [ "$VERBOSE" = no ] || log_action_msg "$@"; }
-
-    [ "$GMT" = "-u" ] && UTC="yes"
-    case "$UTC" in
-       no|"")  GMT="--localtime"
-               UTC=""
-               if [ "X$FIRST" = "Xyes" ] && [ ! -r /etc/localtime ]; then
-                   if [ -z "$TZ" ]; then
-                       log_action_msg "System clock was not updated at this time"
-                       return 1
-                   fi
-               fi
-               ;;
-       yes)    GMT="--utc"
-               UTC="--utc"
-               ;;
-       *)      log_action_msg "Unknown UTC setting: \"$UTC\""; return 1 ;;
-    esac
-
-    case "$BADYEAR" in
-       no|"")  BADYEAR="" ;;
-       yes)    BADYEAR="--badyear" ;;
-       *)      log_action_msg "unknown BADYEAR setting: \"$BADYEAR\""; return 1 ;;
-    esac
-
-    case "$1" in
-       start)
-           if [ -w /etc ] && [ ! -f /etc/adjtime ] && [ ! -e /etc/adjtime ]; then
-               echo "0.0 0 0.0" > /etc/adjtime
-           fi
-
-           if [ ! -w /etc/adjtime ]; then
-               NOADJ="--noadjfile"
-           else
-               NOADJ=""
-           fi
-
-           if [ "$FIRST" != yes ]; then
-               # Uncomment the hwclock --adjust line below if you want
-               # hwclock to try to correct systematic drift errors in the
-               # Hardware Clock.
-               #
-               # WARNING: If you uncomment this option, you must either make
-               # sure *nothing* changes the Hardware Clock other than
-               # hwclock --systohc, or you must delete /etc/adjtime
-               # every time someone else modifies the Hardware Clock.
-               #
-               # Common "vilains" are: ntp, MS Windows, the BIOS Setup
-               # program.
-               #
-               # WARNING: You must remember to invalidate (delete)
-               # /etc/adjtime if you ever need to set the system clock
-               # to a very different value and hwclock --adjust is being
-               # used.
-               #
-               # Please read /usr/share/doc/util-linux/README.Debian.hwclock
-               # before enabling hwclock --adjust.
-
-               #/sbin/hwclock --adjust $GMT $BADYEAR
-               :
-           fi
-
-           if [ "$HWCLOCKACCESS" != no ]; then
-               log_action_msg "Setting the system clock"
-
-               # Copies Hardware Clock time to System Clock using the correct
-               # timezone for hardware clocks in local time, and sets kernel
-               # timezone. DO NOT REMOVE.
-               if /sbin/hwclock --hctosys $GMT $HWCLOCKPARS $BADYEAR $NOADJ; then
-                   #   Announce the local time.
-                   verbose_log_action_msg "System Clock set to: `date $UTC`"
-               else
-                   log_warning_msg "Unable to set System Clock to: `date $UTC`"
-               fi
-           else
-               verbose_log_action_msg "Not setting System Clock"
-           fi
-           ;;
-       stop|restart|reload|force-reload)
-           #
-           # Updates the Hardware Clock with the System Clock time.
-           # This will *override* any changes made to the Hardware Clock.
-           #
-           # WARNING: If you disable this, any changes to the system
-           #          clock will not be carried across reboots.
-           #
-           if [ "$HWCLOCKACCESS" != no ]; then
-               log_action_msg "Saving the system clock"
-               if [ "$GMT" = "-u" ]; then
-                   GMT="--utc"
-               fi
-               if /sbin/hwclock --systohc $GMT $HWCLOCKPARS $BADYEAR; then
-                   verbose_log_action_msg "Hardware Clock updated to `date`"
-               fi
-           else
-               verbose_log_action_msg "Not saving System Clock"
-           fi
-           ;;
-       show)
-           if [ "$HWCLOCKACCESS" != no ]; then
-               /sbin/hwclock --show $GMT $HWCLOCKPARS $BADYEAR
-           fi
-           ;;
-       *)
-           log_success_msg "Usage: hwclock.sh {start|stop|reload|force-reload|show}"
-           log_success_msg "       start sets kernel (system) clock from hardware (RTC) clock"
-           log_success_msg "       stop and reload set hardware (RTC) clock from kernel (system) clock"
-           return 1
-           ;;
-    esac
-}
-
-hwclocksh "$@"
-#!/bin/sh
-### BEGIN INIT INFO
-# Provides:             keymap
-# Required-Start:       mountdevsubfs
-# Required-Stop:     
-# Default-Start:        S
-# Default-Stop:
-# Short-Description:   Set keymap
-# Description:         Set the Console keymap
-### END INIT INFO
-
-# If setupcon is present, then we've been superseded by console-setup.
-if type setupcon >/dev/null 2>&1; then
-       exit 0
-fi
-
-. /lib/lsb/init-functions
-
-#
-# Load the keymaps *as soon as possible*
-#
-
-# Don't fail on error
-CONSOLE_TYPE=`fgconsole 2>/dev/null` || CONSOLE_TYPE="unknown"
-
-# Don't fail on serial consoles
-
-QUIT=0
-# fail silently if loadkeys not present (yet).
-command -v loadkeys >/dev/null 2>&1 || QUIT=1
-
-CONFDIR=/etc/console
-CONFFILEROOT=boottime
-EXT=kmap
-CONFFILE=${CONFDIR}/${CONFFILEROOT}.${EXT}.gz
-
-reset_kernel()
-{
-       # On Mac PPC machines, we may need to set kernel vars first
-        # We need to mount /proc to do that; not optimal, as its going to 
-        # be mounted in S10checkroot, but we need it set up before sulogin
-        # may be run in checkroot, which will need the keyboard to log in...
-       [ -x /sbin/sysctl ] || return
-       [ -r /etc/sysctl.conf ] || return
-       grep -v '^\#' /etc/sysctl.conf | grep -q keycodes 
-       if [ "$?" = "0" ] ; then
-           grep keycodes /etc/sysctl.conf | grep -v "^#" | while read d ; do
-               /sbin/sysctl -w $d 2> /dev/null || true
-            done
-        fi
-}
-
-unicode_start_stop()
-{
-       # Switch unicode mode by checking the locale.
-       # This will be needed before loading the keymap.
-       [ -x /usr/bin/unicode_start ] || [ -x /bin/unicode_start ] ||  return
-       [ -x /usr/bin/unicode_stop ] || [ -x /bin/unicode_stop ] || return
-
-       ENV_FILE="none"
-       [ -r /etc/environment ] && ENV_FILE="/etc/environment"
-       [ -r /etc/default/locale ] && ENV_FILE="/etc/default/locale" 
-       [ $ENV_FILE = none ] && return
-       
-       for var in LANG LC_ALL LC_CTYPE; do
-               value=$(egrep "^[^#]*${var}=" $ENV_FILE | tail -n1 | cut -d= -f2)
-               eval $var=$value
-       done
-
-       CHARMAP=`LANG=$LANG LC_ALL=$LC_ALL LC_CTYPE=$LC_CTYPE locale charmap`
-       if [ "$CHARMAP" = "UTF-8" ]; then
-               unicode_start 2> /dev/null || true
-       else
-               unicode_stop 2> /dev/null || true
-       fi
-}
-
-if [ ! $QUIT = '1' ] ; then
-
-  case "$1" in
-      start | restart | force-reload | reload)
-  
-       # Set kernel variables if required
-       reset_kernel
-
-        # First mount /proc if necessary...and if it is there (#392798)
-        unmount_proc="no"
-       if [ -d /proc ]; then
-               if [ ! -x /proc/$$ ]; then
-                       unmount_proc="yes"      
-                       mount -n /proc
-               fi
-  
-
-               if [ -f /proc/sys/dev/mac_hid/keyboard_sends_linux_keycodes ] ; then
-                       linux_keycodes=`cat /proc/sys/dev/mac_hid/keyboard_sends_linux_keycodes`
-               else
-                       linux_keycodes=1;
-               fi
-       else
-                       linux_keycodes=1;
-       fi
-
-       # load new map
-       if [ $linux_keycodes -gt 0 ] ; then 
-         if [ -r ${CONFFILE} ] ; then
-
-           # Switch console mode to UTF-8 or ASCII as necessary
-           unicode_start_stop
-
-           if [ $CONSOLE_TYPE = "serial" ] ; then 
-                   loadkeys -q ${CONFFILE} 2>&1 > /dev/null
-           else
-                   loadkeys -q ${CONFFILE}
-           fi
-           if [ $? -gt 0 ]
-               then
-               # if we've a serial console, we may not have a keyboard, so don't
-               # complain if we fail. 
-                  if [ ! $CONSOLE_TYPE = "serial" ]; then 
-                       log_warning_msg "Problem when loading ${CONFDIR}/${CONFFILEROOT}.${EXT}.gz, use install-keymap"
-                       sleep 10
-                  fi 
-               fi
-           fi
-       fi
-
-       # unmount /proc if we mounted it
-        [ "$unmount_proc" = "no" ] || umount -n /proc
-
-       ;;
-
-    stop)
-       ;;
-
-    *)
-       log_warning_msg "Usage: $0 {start|stop|restart|reload|force-reload}"
-       ;;
-  esac
-
-fi
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          killprocs
-# Required-Start:    $local_fs
-# Required-Stop:
-# Default-Start:     1
-# Default-Stop:
-# Short-Description: executed by init(8) upon entering runlevel 1 (single).
-### END INIT INFO
-
-PATH=/usr/sbin:/usr/bin:/sbin:/bin
-
-. /lib/lsb/init-functions
-
-do_start () {
-       # Kill all processes.
-       log_action_begin_msg "Sending all processes the TERM signal"
-       killall5 -15
-       log_action_end_msg 0
-       sleep 5
-       log_action_begin_msg "Sending all processes the KILL signal"
-       killall5 -9
-       log_action_end_msg 0
-
-       # We start update here, since we just killed it.
-       if [ -x /sbin/update ] && [ "$(uname -s)" = Linux ]
-       then
-               case "$(uname -r)" in
-                 0.*|1.*|2.[0123].*)
-                       /sbin/update
-                       ;;
-               esac
-       fi
-}
-
-case "$1" in
-  start)
-       do_start
-       ;;
-  restart|reload|force-reload)
-       echo "Error: argument '$1' not supported" >&2
-       exit 3
-       ;;
-  stop)
-       # No-op
-       ;;
-  *)
-       echo "Usage: $0 start|stop" >&2
-       exit 3
-       ;;
-esac
-#! /bin/sh
-# /etc/init.d/klogd: start the kernel log daemon.
-
-### BEGIN INIT INFO
-# Provides:             klogd
-# Required-Start:       syslog
-# Required-Stop:        syslog
-# Default-Start:        S 1 2 3 4 5
-# Default-Stop:         0 6
-# Short-Description:    Kernel logger
-### END INIT INFO
-
-PATH=/bin:/usr/bin:/sbin:/usr/sbin
-
-pidfile=/var/run/klogd/klogd.pid
-kmsgpipe=/var/run/klogd/kmsg
-kmsgpidfile=/var/run/klogd/kmsgpipe.pid
-binpath=/sbin/klogd
-
-test -f $binpath || exit 0
-. /lib/lsb/init-functions
-
-#  Use KLOGD="-k /boot/System.map-$(uname -r)" to specify System.map
-#
-KLOGD="-P $kmsgpipe"
-
-test ! -r /etc/default/klogd || . /etc/default/klogd
-
-. /lib/lsb/init-functions
-
-case "$1" in
-  start)
-    log_begin_msg "Starting kernel log daemon..."
-    # create klog-writeable pid and fifo directory
-    mkdir -p /var/run/klogd
-    chown klog:klog /var/run/klogd
-    mkfifo -m 700 $kmsgpipe
-    chown klog:klog $kmsgpipe
-    # shovel /proc/kmsg to pipe readable by klogd user
-    start-stop-daemon --start --pidfile $kmsgpidfile --exec /bin/dd -b -m -- bs=1 if=/proc/kmsg of=$kmsgpipe
-    # start klogd as non-root with reading from kmsgpipe
-    start-stop-daemon --start --quiet --chuid klog --exec $binpath -- $KLOGD
-    log_end_msg $?
-    ;;
-  stop)
-    log_begin_msg "Stopping kernel log daemon..."
-    start-stop-daemon --stop --quiet --retry 3 --oknodo --exec $binpath --pidfile $pidfile
-    # stop kmsgpipe
-    start-stop-daemon --stop --quiet --oknodo --pidfile $kmsgpidfile
-    rm -f $kmsgpidfile $kmsgpipe
-    log_end_msg $?
-    ;;
-  restart|force-reload)
-    $0 stop
-    sleep 1
-    $0 start
-    ;;
-  *)
-    log_success_msg "Usage: /etc/init.d/klogd {start|stop|restart|force-reload}"
-    exit 1
-esac
-
-exit 0
-#!/bin/sh
-#
-# chkconfig: - 20 90
-# description: Starts and stops "laptop-mode" - tweaks system behavior
-#              to extend battery life.
-#
-# config:  /etc/laptop-mode/laptop-mode.conf
-
-### BEGIN INIT INFO
-# Provides:          laptop-mode
-# Should-Start:      $all
-# Required-Start:    $local_fs
-# Required-Stop:     $local_fs
-# Default-Start:     2 3 4 5
-# Default-Stop:      0 1 6
-# Short-Description: Enable laptop-mode-tools power management functions
-# Description:       Enable laptop-mode-tools power management functions
-### END INIT INFO
-
-
-test -f /usr/sbin/laptop_mode || exit 0
-
-. /lib/lsb/init-functions
-TEMPFILE=`mktemp`
-
-if [ -f /etc/default/laptop-mode ]; then
-       . /etc/default/laptop-mode;
-fi
-if [ -f /etc/default/acpi-support ]; then
-       . /etc/default/acpi-support;
-fi
-
-if [ x$ENABLE_LAPTOP_MODE = xfalse ]; then
-       exit 0;
-fi
-
-# Enable laptop mode when the system is booted when running on battery.
-
-case $1 in
-  start)
-    log_action_begin_msg "Enabling laptop mode"
-    mkdir -p /var/run/laptop-mode-tools
-    touch /var/run/laptop-mode-tools/enabled
-    /usr/sbin/laptop_mode init auto > $TEMPFILE
-    log_action_end_msg $? "$( cat $TEMPFILE )"
-    ;;
-
-  restart|reload|force-reload)
-    # Full restart: first stop laptop mode completely (to restore default mount options etc.)
-    log_action_begin_msg "Disabling laptop mode"
-    mkdir -p /var/run/laptop-mode-tools
-    rm -f /var/run/laptop-mode-tools/enabled
-    /usr/sbin/laptop_mode init stop > $TEMPFILE
-    log_action_end_msg $? "$( cat $TEMPFILE )"
-
-    # Now remove files containing stored status, re-enable, and start it up again.
-    log_action_begin_msg "Enabling laptop mode"
-    rm -f /var/run/laptop-mode-tools/*\r
-    touch /var/run/laptop-mode-tools/enabled
-    /usr/sbin/laptop_mode init auto force > $TEMPFILE
-    log_action_end_msg $? "$( cat $TEMPFILE )"
-    ;;
-
-  stop)
-    log_action_begin_msg "Disabling laptop mode"
-    rm -f /var/run/laptop-mode-tools/enabled
-    /usr/sbin/laptop_mode init stop > $TEMPFILE
-    log_action_end_msg $? "$( cat $TEMPFILE )"
-    ;;
-
-  status)
-    echo "Laptop mode status:"
-    echo
-    /usr/sbin/laptop_mode status
-    ;;
+if opt.name:
+    if cli:
+        cli.update_ref(refname, commit, oldref)
+    else:
+        git.update_ref(refname, commit, oldref)
+
+if cli:
+    cli.close()
+
+secs = time.time() - start_time
+size = hashsplit.total_split
+if opt.bench:
+    log('\nbup: %.2fkbytes in %.2f secs = %.2f kbytes/sec\n'
+        % (size/1024., secs, size/1024./secs))
+#!/usr/bin/env python
+import sys, re, struct, mmap
+from bup import git, options
+from bup.helpers import *
+
+
+def s_from_bytes(bytes):
+    clist = [chr(b) for b in bytes]
+    return ''.join(clist)
+
+
+def report(count):
+    fields = ['VmSize', 'VmRSS', 'VmData', 'VmStk']
+    d = {}
+    for line in open('/proc/self/status').readlines():
+        l = re.split(r':\s*', line.strip(), 1)
+        d[l[0]] = l[1]
+    if count >= 0:
+        e1 = count
+        fields = [d[k] for k in fields]
+    else:
+        e1 = ''
+    print ('%9s  ' + ('%10s ' * len(fields))) % tuple([e1] + fields)
+    sys.stdout.flush()
+
+
+optspec = """
+bup memtest [-n elements] [-c cycles]
+--
+n,number=  number of objects per cycle
+c,cycles=  number of cycles to run
+ignore-midx  ignore .midx files, use only .idx files
+"""
+o = options.Options('bup memtest', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if extra:
+    o.fatal('no arguments expected')
+
+git.ignore_midx = opt.ignore_midx
+
+git.check_repo_or_die()
+m = git.PackIdxList(git.repo('objects/pack'))
+
+cycles = opt.cycles or 100
+number = opt.number or 10000
+
+report(-1)
+f = open('/dev/urandom')
+a = mmap.mmap(-1, 20)
+report(0)
+for c in xrange(cycles):
+    for n in xrange(number):
+        b = f.read(3)
+        if 0:
+            bytes = list(struct.unpack('!BBB', b)) + [0]*17
+            bytes[2] &= 0xf0
+            bin = struct.pack('!20s', s_from_bytes(bytes))
+        else:
+            a[0:2] = b[0:2]
+            a[2] = chr(ord(b[2]) & 0xf0)
+            bin = str(a[0:20])
+        #print bin.encode('hex')
+        m.exists(bin)
+    report((c+1)*number)
+#!/usr/bin/env python
+import sys, os, stat
+from bup import options, git, vfs
+from bup.helpers import *
+
+def print_node(text, n):
+    prefix = ''
+    if opt.hash:
+        prefix += "%s " % n.hash.encode('hex')
+    if stat.S_ISDIR(n.mode):
+        print '%s%s/' % (prefix, text)
+    elif stat.S_ISLNK(n.mode):
+        print '%s%s@' % (prefix, text)
+    else:
+        print '%s%s' % (prefix, text)
+
+
+optspec = """
+bup ls <dirs...>
+--
+s,hash   show hash for each file
+"""
+o = options.Options('bup ls', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+git.check_repo_or_die()
+top = vfs.RefList(None)
+
+if not extra:
+    extra = ['/']
+
+ret = 0
+for d in extra:
+    try:
+        n = top.lresolve(d)
+        if stat.S_ISDIR(n.mode):
+            for sub in n:
+                print_node(sub.name, sub)
+        else:
+            print_node(d, n)
+    except vfs.NodeError, e:
+        log('error: %s\n' % e)
+        ret = 1
+
+sys.exit(ret)
+#!/usr/bin/env python
+import sys, os, re, stat, readline, fnmatch
+from bup import options, git, shquote, vfs
+from bup.helpers import *
+
+def node_name(text, n):
+    if stat.S_ISDIR(n.mode):
+        return '%s/' % text
+    elif stat.S_ISLNK(n.mode):
+        return '%s@' % text
+    else:
+        return '%s' % text
+
+
+def do_ls(path, n):
+    l = []
+    if stat.S_ISDIR(n.mode):
+        for sub in n:
+            l.append(node_name(sub.name, sub))
+    else:
+        l.append(node_name(path, n))
+    print columnate(l, '')
     
-  *)
-    echo "Usage: $0 {stop|start|restart|reload|force-reload|status}" >&2
-    exit 2
-    ;;
-esac
-
-if [ -f $TEMPFILE ] ; then
-       rm $TEMPFILE
-fi
-
-exit 0
-#!/bin/sh
-### BEGIN INIT INFO
-# Provides:          libpam-foreground-clean
-# Required-Start:    $local_fs $remote_fs
-# Required-Stop:
-# Default-Start:     S
-# Default-Stop:
-# Short-Description: Clean old status files during boot.
-### END INIT INFO
-
-set -e
-
-. /lib/lsb/init-functions
-PATH=/sbin:/bin
-
-STATEDIR=/var/run/console
-
-case "$1" in
-  start)
-    if [ -d $STATEDIR ]; then
-      log_begin_msg "Cleaning up $STATEDIR/..."
-      rm -f $STATEDIR/*
-      log_end_msg 0
-    fi
-    exit 0
-    ;;
-
-  stop|restart|force-reload)
-    exit 0
-    ;;
-
-  *)
-    echo "Usage: $0 {start|stop|restart|force-reload}" >&2
-    exit 3
-    ;;
-esac
-#!/bin/sh -e
-#
-# loopback - brings up the loopback (127.0.0.1) network device so that
-#            DHCP and other such things will work
-#
 
-# Check the package is still installed
-[ -x /sbin/ifup ] || exit 0
-
-# Get LSB functions
-. /lib/lsb/init-functions
-. /etc/default/rcS
-
-case "$1" in
-    start)
-       [ -d /var/run/network ] || mkdir /var/run/network
-
-       log_begin_msg "Starting basic networking..."
-       if ifup --allow auto lo; then
-           log_end_msg 0
-       else
-           log_end_msg $?
-       fi
-       ;;
-    stop)
-       log_begin_msg "Stopping basic networking..."
-       if ifdown lo; then
-           log_end_msg 0
-       else
-           log_end_msg $?
-       fi
-       ;;
-    restart|force-reload)
-       exit 0
-       ;;
-    *)
-       echo "Usage: /etc/init.d/loopback {start|stop|restart|force-reload}"
-       exit 1
-       ;;
-esac
-
-exit 0
-#! /bin/sh
-
-N=/etc/init.d/makedev
-PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
-
-set -e
-
-case "$1" in
-  start)
-       test -L /dev/MAKEDEV || ln -fs /sbin/MAKEDEV /dev/MAKEDEV
-
-       # create dvb-devices, if the dvb-directory allready exists, and 
-       # no devfs or udev is in use (workaround for the changed major-number
-       # of the dvb-devices, introduced in kernel 2.6.8, to be able to 
-       # switch between kernels <= 2.6.7 and >= 2.6.8, without manual 
-       # recreation of the devices (MAKEDEV dvb checks the kernel-version 
-       # and uses the correct major-number))
-       
-       if [ ! -e /dev/.devfsd -a ! -e /dev/.udevdb ]; then
-               if [ -d /dev/dvb ]; then
-                       cd /dev && ./MAKEDEV dvb
-               fi
-       fi
-       
-       ;;
-  stop|reload|restart|force-reload)
-       ;;
-  *)
-       echo "Usage: $N {start|stop|restart|force-reload}" >&2
-       exit 1
-       ;;
-esac
-
-exit 0
-#!/bin/sh
-#
-# Start the RAID monitor daemon for all active md arrays if desired.
-#
-# Copyright (c) 2001-2004 Mario Jou/3en <joussen@debian.org>
-# Distributable under the terms of the GNU GPL version 2.
-
-MDADM=/sbin/mdadm
-DEBIANCONFIG=/etc/default/mdadm
-PIDFILE=/var/run/mdadm.pid
-
-test -x $MDADM || exit 0
-
-. /lib/lsb/init-functions
-
-MAIL_TO=root
-START_DAEMON=true
-test -f $DEBIANCONFIG && . $DEBIANCONFIG
-
-case "$1" in
-    start)
-        if [ "x$START_DAEMON" = "xtrue" ] ; then
-            log_begin_msg "Starting RAID monitoring services..."
-            start-stop-daemon -S -q -p $PIDFILE -x $MDADM -- -F -i $PIDFILE -m $MAIL_TO -f -s
-            log_end_msg $?
-        fi
-        ;;
-    stop)
-        if [ -f $PIDFILE ] ; then
-            log_begin_msg "Stopping RAID monitoring services..."
-            start-stop-daemon -K -q -p $PIDFILE -x $MDADM
-           log_end_msg $?
-            rm -f $PIDFILE
-        fi
-        ;;
-    restart|reload|force-reload)
-        $0 stop
-        $0 start
-        ;;
-    *)
-        log_success_msg "Usage: $0 {start|stop|restart|reload|force-reload}"
-        exit 1
-        ;;
-esac
-
-exit 0
-#!/bin/sh
-#
-# Start any arrays which are described in /etc/mdadm/mdadm.conf and which are
-# not running already.
-#
-# Copyright (c) 2001-2004 Mario Jou/3en <joussen@debian.org>
-# Distributable under the terms of the GNU GPL version 2.
-
-MDADM=/sbin/mdadm
-MDRUN=/sbin/mdrun
-CONFIG=/etc/mdadm/mdadm.conf
-DEBIANCONFIG=/etc/default/mdadm
-
-. /lib/lsb/init-functions
-
-test -x $MDADM || exit 0
-
-AUTOSTART=true
-test -f $DEBIANCONFIG && . $DEBIANCONFIG
-
-case "$1" in
-    start)
-       if [ "x$AUTOSTART" = "xtrue" ] ; then
-            if [ ! -f /proc/mdstat ] && [ -x /sbin/modprobe ] ; then
-                /sbin/modprobe -k md > /dev/null 2>&1  
-            fi
-            test -f /proc/mdstat || exit 0
-           log_begin_msg "Starting RAID devices..."
-           if [ -f $CONFIG ] && [ -x $MDADM ] ; then
-               $MDADM -A -s
-           elif [ -x $MDRUN ] ; then
-               $MDRUN
-           fi
-           log_end_msg $?
-       fi
-        ;;
-    stop|restart|reload|force-reload)
-        ;;
-    *)
-       log_success_msg "Usage: $0 {start|stop|restart|reload|force-reload}"
-        exit 1
-        ;;
-esac
-
-exit 0
-#!/bin/sh -e
-### BEGIN INIT INFO
-# Provides:          module-init-tools
-# Required-Start:    
-# Required-Stop:     
-# Should-Start:      checkroot
-# Should-stop:
-# Default-Start:     S
-# Default-Stop:
-# Short-Description: Process /etc/modules.
-# Description:       Load the modules listed in /etc/modules.
-### END INIT INFO
-
-# Silently exit if the kernel does not support modules or needs modutils.
-[ -f /proc/modules ] || exit 0
-[ ! -f /proc/ksyms ] || exit 0
-[ -x /sbin/modprobe  ] || exit 0
-
-. /etc/default/rcS
-. /lib/lsb/init-functions
-
-PATH="/sbin:/bin"
-
-KVER=$(uname -r)
-KMAJ=${KVER%${KVER#*.*[^.]}}
-KMAJ=${KMAJ%.}
-
-if [ -e /etc/modules-$KVER ]; then
-  MODULES_FILE=/etc/modules-$KVER
-elif [ -e /etc/modules-$KMAJ ]; then
-  MODULES_FILE=/etc/modules-$KMAJ
-else
-  MODULES_FILE=/etc/modules
-fi
-
-load_module() {
-  local module args
-  module="$1"
-  args="$2"
-
-  if [ "$VERBOSE" != no ]; then
-    log_action_msg "Loading kernel module $module"
-    modprobe $module $args || true
-  else
-    modprobe $module $args > /dev/null 2>&1 || true
-  fi   
-}
-
-if [ "$VERBOSE" = no ]; then
-  log_action_begin_msg 'Loading kernel modules'
-fi
-
-# Loop over every line in /etc/modules.
-log_begin_msg 'Loading manual drivers...'
-grep '^[^#]' $MODULES_FILE | \
-while read module args; do
-  [ "$module" ] || continue
-  load_module "$module" "$args"
-done
-
-if [ "$VERBOSE" = no ]; then 
-  log_action_end_msg 0
-fi
-
-exit 0
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          mountall-bootclean
-# Required-Start:    mountall
-# Required-Stop:
-# Default-Start:     S
-# Default-Stop:
-# Short-Description: bootclean after mountall.
-# Description:       Clean temporary filesystems after
-#                    all local filesystems have been mounted.
-### END INIT INFO
-
-case "$1" in
-  start|"")
-       # Clean /tmp
-       /etc/init.d/bootclean
-       ;;
-  restart|reload|force-reload)
-       echo "Error: argument '$1' not supported" >&2
-       exit 3
-       ;;
-  stop)
-       # No-op
-       ;;
-  *)
-       echo "Usage: mountall-bootclean.sh [start|stop]" >&2
-       exit 3
-       ;;
-esac
-
-:
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          mountall
-# Required-Start:    checkfs
-# Required-Stop: 
-# Should-Start:      lvm
-# Should-Stop:
-# Default-Start:     S
-# Default-Stop:
-# Short-Description: Mount all filesystems.
-# Description:
-### END INIT INFO
-
-PATH=/sbin:/bin
-. /lib/init/vars.sh
-
-. /lib/lsb/init-functions
-. /lib/init/mount-functions.sh
-
-if [ -r /etc/default/locale ]; then
-       . /etc/default/locale
-       export LANG
-fi
-
-do_start() {
-       #
-       # Mount local file systems in /etc/fstab.
-       #
-       pre_mountall
-       if [ "$VERBOSE" = no ]
-       then
-               log_action_begin_msg "Mounting local filesystems"
-               mount -a -t proc >/dev/null 2>&1  # Ignore error message due to /proc already being mounted
-               ES_TO_REPORT=$?
-               mount -a -t noproc,nfs,nfs4,smbfs,cifs,ncp,ncpfs,coda,ocfs2,gfs
-               ES=$?
-               ES_TO_REPORT=$(($ES_TO_REPORT | $ES))
-               if [ 0 = "$ES_TO_REPORT" ]
-               then
-                       log_action_end_msg 0
-               else
-                       log_action_end_msg 1 "code $ES_TO_REPORT"
-               fi
-       else
-               log_action_msg "Will now mount local filesystems"
-               mount -a -t proc >/dev/null 2>&1  # Ignore error message due to /proc already being mounted
-               ES=$?
-               [ 0 = "$ES" ] || log_failure_msg "Mounting proc filesystems failed with error code ${ES}."
-               mount -a -v -t noproc,nfs,nfs4,smbfs,cifs,ncp,ncpfs,coda,ocfs2,gfs
-               ES=$?
-               if [ 0 = "$ES" ]
-               then
-                       log_success_msg "Done mounting local filesystems."
-               else
-                       log_failure_msg "Mounting local filesystems failed with error code ${ES}."
-               fi
-       fi
-
-       post_mountall
-
-       case "$(uname -s)" in
-         *FreeBSD)
-               INITCTL=/etc/.initctl
-               ;;
-         *)
-               INITCTL=/dev/initctl
-               ;;
-       esac
-
-       #
-       # We might have mounted something over /dev, see if
-       # /dev/initctl is there.
-       #
-       if [ ! -p $INITCTL ]
-       then
-               rm -f $INITCTL
-               mknod -m 600 $INITCTL p
-       fi
-       kill -USR1 1
-
-       #
-       # Execute swapon command again, in case we want to swap to
-       # a file on a now mounted filesystem.
-       #
-       # Ignore 255 status due to swap already being enabled
-       #
-       if [ "$VERBOSE" = no ]
-       then
-               log_action_begin_msg "Activating swapfile swap"
-               swapon -a -e 2>/dev/null || :  # Stifle "Device or resource busy"
-               log_action_end_msg 0
-       else
-               log_action_msg "Will now activate swapfile swap"
-               swapon -a -e -v || :
-               log_success_msg "Done activating swapfile swap."
-       fi
-}
-
-case "$1" in
-  start|"")
-       do_start
-       ;;
-  restart|reload|force-reload)
-       echo "Error: argument '$1' not supported" >&2
-       exit 3
-       ;;
-  stop)
-       # No-op
-       ;;
-  *)
-       echo "Usage: mountall.sh [start|stop]" >&2
-       exit 3
-       ;;
-esac
-
-:
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          mountdevsubfs mountvirtfs
-# Required-Start:    mountkernfs
-# Required-Stop:
-# Default-Start:     S
-# Default-Stop:
-# Short-Description: Mount special file systems under /dev.
-# Description:       Mount the virtual filesystems the kernel provides
-#                    that ordinarily live under the /dev filesystem.
-### END INIT INFO
-
-PATH=/lib/init:/sbin:/bin
-TTYGRP=5
-TTYMODE=620
-[ -f /etc/default/devpts ] && . /etc/default/devpts
-
-TMPFS_SIZE=
-[ -f /etc/default/tmpfs ] && . /etc/default/tmpfs
-
-KERNEL="$(uname -s)"
-
-. /lib/lsb/init-functions
-. /lib/init/mount-functions.sh
-
-do_start () {
-       #
-       # Mount a tmpfs on /dev/shm
-       #
-       SHM_OPT=
-       [ "${SHM_SIZE:=$TMPFS_SIZE}" ] && SHM_OPT="-osize=$SHM_SIZE"
-       domount tmpfs shmfs /dev/shm $SHM_OPT
-
-       #
-       # Mount /dev/pts. Create master ptmx node if needed.
-       #
-       domount devpts "" /dev/pts -ogid=$TTYGRP,mode=$TTYMODE
-
-       #
-       # Magic to make /proc/bus/usb work
-       #
-       #mkdir -p /dev/bus/usb/.usbfs
-       #domount usbfs "" /dev/bus/usb/.usbfs -obusmode=0700,devmode=0600,listmode=0644
-       #ln -s .usbfs/devices /dev/bus/usb/devices
-       #mount --rbind /dev/bus/usb /proc/bus/usb
-}
-
-case "$1" in
-  "")
-       echo "Warning: mountdevsubfs should be called with the 'start' argument." >&2
-       do_start
-       ;;
-  start)
-       do_start
-       ;;
-  restart|reload|force-reload)
-       echo "Error: argument '$1' not supported" >&2
-       exit 3
-       ;;
-  stop)
-       # No-op
-       ;;
-  *)
-       echo "Usage: mountdevsubfs [start|stop]" >&2
-       exit 3
-       ;;
-esac
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          mountkernfs
-# Required-Start:
-# Required-Stop:
-# Default-Start:     S
-# Default-Stop:
-# Short-Description: Mount kernel virtual file systems.
-# Description:       Mount initial set of virtual filesystems the kernel
-#                    provides and that are required by everything.
-### END INIT INFO
-
-PATH=/lib/init:/sbin:/bin
-
-. /lib/lsb/init-functions
-. /lib/init/mount-functions.sh
-
-do_start () {
-       #
-       # Mount proc filesystem on /proc
-       #
-       domount proc "" /proc -onodev,noexec,nosuid
-
-       #
-       # Mount sysfs on /sys
-       #
-       domount sysfs "" /sys -onodev,noexec,nosuid
-
-       # Mount /var/run and /var/lock as tmpfs.
-       domount tmpfs "" /var/run -omode=0755,nodev,noexec,nosuid
-       domount tmpfs "" /var/lock -omode=1777,nodev,noexec,nosuid
-
-       # Mount spufs, if Cell Broadband processor is detected
-       if mountpoint -q /proc && grep -qs '^cpu.*Cell' /proc/cpuinfo; then
-               mkdir -p /spu
-               domount spufs "" /spu -ogid=spu
-       fi
-
-       # Propagate files from the initramfs to our new /var/run.
-       for file in /dev/.initramfs/varrun/*; do
-               [ -e "$file" ] || continue
-               cp -a "$file" "/var/run/${x#/dev/.initramfs/varrun/}"
-       done
-
-       if [ ! -d /var/run/sendsigs.omit.d/ ]; then
-               mkdir /var/run/sendsigs.omit.d/
-       fi
-}
-
-case "$1" in
-  "")
-       echo "Warning: mountvirtfs should be called with the 'start' argument." >&2
-       do_start
-       ;;
-  start)
-       do_start
-       ;;
-  restart|reload|force-reload)
-       echo "Error: argument '$1' not supported" >&2
-       exit 3
-       ;;
-  stop)
-       # No-op
-       ;;
-  *)
-       echo "Usage: mountvirtfs [start|stop]" >&2
-       exit 3
-       ;;
-esac
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          mountnfs-bootclean
-# Required-Start:    mountnfs
-# Required-Stop:
-# Default-Start:     S
-# Default-Stop:
-# Short-Description: bootclean after mountnfs.
-# Description:       Clean temporary filesystems after
-#                    network filesystems have been mounted.
-### END INIT INFO
-
-case "$1" in
-  start|"")
-       # Clean /tmp
-       /etc/init.d/bootclean
-       ;;
-  restart|reload|force-reload)
-       echo "Error: argument '$1' not supported" >&2
-       exit 3
-       ;;
-  stop)
-       # No-op
-       ;;
-  *)
-       echo "Usage: mountnfs-bootclean.sh [start|stop]" >&2
-       exit 3
-       ;;
-esac
-
-:
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          mountoverflowtmp
-# Required-Start:    mountall-bootclean
-# Required-Stop:
-# Default-Start:     S
-# Default-Stop:
-# Short-Description: mount emergency /tmp.
-# Description:       Mount a tmpfs on /tmp if there would
-#                    otherwise be too little space to log in.
-### END INIT INFO
-
-. /lib/lsb/init-functions
-
-set -e
-
-defs=/etc/default/mountoverflowtmp
-test ! -f "$defs" || . "$defs"
-
-: ${MINTMPKB:=1024}
-if test "$MINTMPKB" = "0"; then exit 0; fi
-
-case "$1" in
-  start|"")
-       log_action_begin_msg "Checking minimum space in /tmp"
-       df="`df -kP /tmp`"
-       avail="`printf "%s" "$df" | awk 'NR==2 { print $4 }'`"
-       log_action_end_msg 0
-       if test $avail -lt "$MINTMPKB"; then
-               log_action_begin_msg "Mounting emergency tmpfs on /tmp"
-               mount -t tmpfs -o size=1048576,mode=1777 overflow /tmp
-               log_action_end_msg 0
-       fi
-       ;;
-  restart|reload|force-reload)
-       echo "Error: argument '$1' not supported" >&2
-       exit 3
-       ;;
-  stop)
-       log_action_begin_msg "Unmounting any overflow tmpfs from /tmp"
-       if LANG=C LC_ALL=C mount | \
-               grep '^overflow on /tmp type tmpfs' >/dev/null; then
-               umount overflow
-       fi
-       log_action_end_msg 0
-       ;;
-  *)
-       echo "Usage: mountoverflowtmp [start|stop]" >&2
-       exit 3
-       ;;
-esac
-
-:
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          mtab
-# Required-Start:    mountall
-# Required-Stop:
-# Default-Start:     S
-# Default-Stop:
-# Short-Description: Update mtab file.
-# Description:       Update the mount program's mtab file after
-#                    all local filesystems have been mounted.
-### END INIT INFO
-
-PATH=/lib/init:/sbin:/bin
-TTYGRP=5
-TTYMODE=620
-[ -f /etc/default/devpts ] && . /etc/default/devpts
-
-TMPFS_SIZE=
-[ -f /etc/default/tmpfs ] && . /etc/default/tmpfs
-
-KERNEL="$(uname -s)"
-
-. /lib/lsb/init-functions
-. /lib/init/mount-functions.sh
-
-domtab ()
-{
-       # Directory present?
-       if [ ! -d $2 ]
-       then
-               return
-       fi
-
-       # Not mounted?
-       if ! mountpoint -q $2
-       then
-               return
-       fi
-
-       if [ -n "$3" ]
-       then
-               NAME="$3"
-       else
-               NAME="$1"
-       fi
-
-       # Already recorded?
-       if ! grep -E -sq "^([^ ]+) +$2 +" /etc/mtab
-       then
-               mount -f -t $1 $OPTS $4 $NAME $2
-       fi
-}
-
-do_start () {
-       DO_MTAB=""
-       MTAB_PATH="$(readlink -f /etc/mtab || :)"
-       case "$MTAB_PATH" in
-         /proc/*)
-               # Assume that /proc/ is not writable
-               ;;
-         /*)
-               # Only update mtab if it is known to be writable
-               # Note that the touch program is in /usr/bin
-               #if ! touch "$MTAB_PATH" >/dev/null 2>&1
-               #then
-               #       return
-               #fi
-               ;;
-         "")
-               [ -L /etc/mtab ] && MTAB_PATH="$(readlink /etc/mtab)"
-               if [ "$MTAB_PATH" ]
-               then
-                       log_failure_msg "Cannot initialize ${MTAB_PATH}."
-               else
-                       log_failure_msg "Cannot initialize /etc/mtab."
-               fi
-               ;;
-         *)
-               log_failure_msg "Illegal mtab location '${MTAB_PATH}'."
-               ;;
-       esac
-
-       #
-       # Initialize mtab file if necessary
-       #
-       if [ ! -f /etc/mtab ]
-       then
-               :> /etc/mtab
-               chmod 644 /etc/mtab
-       fi
-       if selinux_enabled && which restorecon >/dev/null 2>&1 && [ -r /etc/mtab ]
-       then
-               restorecon /etc/mtab
-       fi
-
-       # S01mountkernfs.sh
-       domtab proc /proc "proc" -onodev,noexec,nosuid
-       domtab sysfs /sys "sys" -onodev,noexec,nosuid
-       domtab tmpfs /var/run "varrun" -omode=0755,nodev,noexec,nosuid
-       domtab tmpfs /var/lock "varlock" -omode=1777,nodev,noexec,nosuid
-       domtab usbfs /proc/bus/usb "procbususb"
-
-       # S10udev
-       domtab tmpfs /dev "udev" -omode=0755
-
-       # S02mountdevsubfs
-       SHM_OPT=
-       [ "${SHM_SIZE:=$TMPFS_SIZE}" ] && SHM_OPT="-osize=$SHM_SIZE"
-       domtab tmpfs /dev/shm "devshm" $SHM_OPT
-       domtab devpts /dev/pts "devpts" -ogid=$TTYGRP,mode=$TTYMODE
-
-       # S07linux-restricted-modules-common
-       exec 9<&0 0</proc/mounts
-       while read FDEV FDIR FTYPE FOPTS REST
-       do
-               case "$FDIR" in
-                       /lib/modules/*/volatile)
-                               domtab "$FTYPE" "$FDIR" "lrm"
-                               ;;
-               esac
-       done
-       exec 0<&9 9<&-
-
-       # /etc/network/if-up.d/mountnfs
-       exec 9<&0 </etc/fstab
-       while read FDEV FDIR FTYPE FOPTS REST
-       do
-               case "$FDEV" in
-                 ""|\#*)
-                       continue
-                       ;;
-               esac
-               case "$FOPTS" in
-                 noauto|*,noauto|noauto,*|*,noauto,*)
-                       continue
-                       ;;
-               esac
-               case "$FTYPE" in
-                 nfs|nfs4|smbfs|cifs|coda|ncp|ncpfs|ocfs2|gfs)
-                       domtab "$FTYPE" "$FDIR" "$FDEV" "-o$FOPTS"
-                       ;;
-                 *)
-                       continue
-                       ;;
-               esac
-        done
-        exec 0<&9 9<&-
-
-       
-}
-
-case "$1" in
-  start|"")
-       do_start
-       ;;
-  restart|reload|force-reload)
-       echo "Error: argument '$1' not supported" >&2
-       exit 3
-       ;;
-  stop)
-       # No-op
-       ;;
-  *)
-       echo "Usage: mountall-mtab.sh [start|stop]" >&2
-       exit 3
-       ;;
-esac
-
-:
-#!/bin/bash
-#
-# MySQL daemon start/stop script.
-#
-# Debian version. Based on the original by TcX.
-#
-set -e
-set -u
-${DEBIAN_SCRIPT_DEBUG:+ set -v -x}
-
-test -x /usr/sbin/mysqld || exit 0
-
-SELF=$(cd $(dirname $0); pwd -P)/$(basename $0)
-CONF=/etc/mysql/my.cnf
-MYADMIN="/usr/bin/mysqladmin --defaults-file=/etc/mysql/debian.cnf"
-
-# priority can be overriden and "-s" adds output to stderr
-ERR_LOGGER="logger -p daemon.err -t /etc/init.d/mysql -i"
-
-# Safeguard (relative paths, core dumps..)
-cd /
-umask 077
-
-# mysqladmin likes to read /root/.my.cnf. This is usually not what I want
-# as many admins e.g. only store a password without a username there and
-# so break my scripts.
-export HOME=/etc/mysql/
-
-## fetch a particular option from mysql's invocation
-#
-# usage: void mysqld_get_param option
-mysqld_get_param() {
-       /usr/sbin/mysqld --print-defaults \
-               | tr " " "\n" \
-               | grep -- "--$1" \
-               | tail -n 1 \
-               | cut -d= -f2
-}
-
-## Checks if there is a server running and if so if it is accessible.
-#
-# check_alive insists on a pingable server
-# check_dead also fails if there is a lost mysqld in the process list
-#
-# Usage: boolean mysqld_status [check_alive|check_dead] [warn|nowarn]
-mysqld_status () {
-    ping_output=`$MYADMIN ping 2>&1`; ping_alive=$(( ! $? ))
-
-    ps_alive=0
-    pidfile=`mysqld_get_param pid-file`
-    if [ -f "$pidfile" ] && ps `cat $pidfile` >/dev/null 2>&1; then ps_alive=1; fi
+def write_to_file(inf, outf):
+    for blob in chunkyreader(inf):
+        outf.write(blob)
     
-    if [ "$1" = "check_alive"  -a  $ping_alive = 1 ] ||
-       [ "$1" = "check_dead"   -a  $ping_alive = 0  -a  $ps_alive = 0 ]; then
-       return 0 # EXIT_SUCCESS
-    else
-       if [ "$2" = "warn" ]; then
-           /bin/echo -e "$ps_alive processes alive and '$MYADMIN ping' resulted in\n$ping_output\n" | $ERR_LOGGER -p daemon.debug
-       fi
-       return 1 # EXIT_FAILURE
-    fi
-}
-
-#
-# main()
-#
-
-case "${1:-''}" in
-  'start')
-       # check for config file
-       if [ ! -r /etc/mysql/my.cnf ]; then
-         /bin/echo -e "\nWARNING: /etc/mysql/my.cnf cannot be read. See README.Debian.gz"
-        fi 
-       # Start daemon
-       echo -n "Starting MySQL database server: mysqld"
-       if mysqld_status check_alive nowarn; then
-          echo "...already running."
-       else
-           /usr/bin/mysqld_safe > /dev/null 2>&1 &
-           for i in 1 2 3 4 5 6; do
-                sleep 1
-               if mysqld_status check_alive nowarn ; then break; fi
-            done
-           if mysqld_status check_alive warn; then
-                echo "."
-               # Now start mysqlcheck or whatever the admin wants.
-               /etc/mysql/debian-start
-           else
-               echo "...failed."
-               /bin/echo -e "\tPlease take a look at the syslog."
-           fi
-       fi
-
-        if $MYADMIN variables | egrep -q have_bdb.*YES; then
-            /bin/echo "BerkeleyDB is obsolete, see /usr/share/doc/mysql-server-4.1/README.Debian.gz" | $ERR_LOGGER -p daemon.info
-        fi
-       ;;
-
-  'stop')
-       # * As a passwordless mysqladmin (e.g. via ~/.my.cnf) must be possible
-       # at least for cron, we can rely on it here, too. (although we have 
-       # to specify it explicit as e.g. sudo environments points to the normal
-       # users home and not /root)
-       echo -n "Stopping MySQL database server: mysqld"        
-       if ! mysqld_status check_dead nowarn; then
-         set +e
-         shutdown_out=`$MYADMIN shutdown 2>&1`; r=$?
-         set -e
-         if [ "$r" -ne 0 ]; then
-           /bin/echo -e -n "...failed.\n$shutdown_out\nKilling MySQL database server by signal: mysqld"
-           killall -15 mysqld
-            server_down=
-           for i in 1 2 3 4 5 6 7 8 9 10; do
-              sleep 1
-              if mysqld_status check_dead nowarn; then server_down=1; break; fi
-            done
-          if test -z "$server_down"; then killall -9 mysqld; fi
-         fi
-        fi
-
-        if ! mysqld_status check_dead warn; then
-         echo "...failed."
-         echo "Please stop MySQL manually and read /usr/share/doc/mysql-server-4.1/README.Debian.gz!"
-         exit -1
-       else
-         echo "."
-        fi
-       ;;
-
-  'restart')
-       set +e; $SELF stop; set -e
-       $SELF start 
-       ;;
-
-  'reload'|'force-reload')
-       echo -n "Reloading MySQL database server: mysqld"
-       $MYADMIN reload
-       echo "."
-       ;;
-
-  'status')
-       if mysqld_status check_alive nowarn; then
-         $MYADMIN version
-       else
-         echo "MySQL is stopped."
-         exit 3
-       fi
-       ;;
-
-  *)
-       echo "Usage: $SELF start|stop|restart|reload|force-reload|status"
-       exit 1
-       ;;
-esac
-
-#!/bin/bash
-#
-# MySQL NDB management daemon start/stop script.
-#
-set -e
-set -u
-${DEBIAN_SCRIPT_DEBUG:+ set -v -x}
-
-# Variables
-SELF=$(cd $(dirname $0); pwd -P)/$(basename $0)
-DAEMON=/usr/sbin/ndbd
-CONF=/etc/mysql/my.cnf
-export HOME=/etc/mysql/
-
-# Safeguard (relative paths, core dumps..)
-cd /
-umask 077
-
-# Exit *silently* if we're not supposed to be started.
-#
-# The Debian scripts should execute these scripts to stop and start
-# the daemon when upgrading if it is started. On the other hand it should
-# remain silently if the server has not even been configured.
-# See /usr/share/doc/mysql-server-*/README.Debian for more information.
-test -x $DAEMON || exit 0
-if $DAEMON --help | grep -q '^ndb-connectstring.*No default value'; then exit 0; fi
-
-#
-# main()
-#
-case "${1:-''}" in
-  'start')
-       # Start daemon
-        # Creatign a PID file does not work as the master process forks
-        # a child with different PID and then terminates itself.
-       echo -n "Starting MySQL NDB cluster server: ndbd"
-       if start-stop-daemon \
-               --start \
-               --exec $DAEMON \
-               --user mysql
-       then
-         echo "."
-       else
-         echo "...failed."
-         /bin/echo -e "\tPlease take a look at the syslog."
-         exit 1
-       fi                        
-       ;;
-
-  'stop')
-       echo -n "Stopping MySQL NDB cluster management server: ndbd"    
-       if start-stop-daemon \
-               --stop \
-               --oknodo \
-               --exec $DAEMON
-       then
-         echo "."
-       else
-         echo "...failed."
-         exit 1
-        fi
-       ;;
-
-  'restart'|'force-reload')
-       set +e; $SELF stop; set -e
-       $SELF start 
-       ;;
-
-  *)
-       echo "Usage: $SELF start|stop|restart|force-reload"
-       exit 1
-       ;;
-esac
-
-#!/bin/bash
-#
-# MySQL NDB management daemon start/stop script.
-#
-set -e
-set -u
-${DEBIAN_SCRIPT_DEBUG:+ set -v -x}
-
-# Variables
-SELF=$(cd $(dirname $0); pwd -P)/$(basename $0)
-DAEMON=/usr/sbin/ndb_mgmd
-CONF=/etc/mysql/ndb_mgmd.cnf
-export HOME=/etc/mysql/
-
-# Safeguard (relative paths, core dumps..)
-cd /
-umask 077
-
-# Exit *silently* if we're not supposed to be started.
-#
-# The Debian scripts should execute these scripts to stop and start
-# the daemon when upgrading if it is started. On the other hand it should
-# remain silently if the server has not even been configured.
-# See /usr/share/doc/mysql-server-*/README.Debian for more information.
-test -x $DAEMON || exit 0
-test -r $CONF || exit 0
-
-#
-# main()
-#
-case "${1:-''}" in
-  'start')
-       # Start daemon
-       echo -n "Starting MySQL NDB cluster management server: ndb_mgmd"
-       # --pid-file does not work as the daemon forks itself with $PID=$PID+1
-       if start-stop-daemon \
-               --start \
-               --exec $DAEMON \
-               --user mysql \
-               -- \
-               -f $CONF
-       then
-         echo "."
-       else
-         echo "...failed."
-         /bin/echo -e "\tPlease take a look at the syslog."
-         exit 1
-       fi                        
-       ;;
-
-  'stop')
-       echo -n "Stopping MySQL NDB cluster management server: ndb_mgmd"        
-       if start-stop-daemon \
-               --stop \
-               --oknodo \
-               --exec $DAEMON
-       then
-         echo "."
-       else
-         echo "...failed."
-         exit 1
-        fi
-       ;;
-
-  'restart'|'force-reload')
-       set +e; $SELF stop; set -e
-       $SELF start 
-       ;;
-
-  *)
-       echo "Usage: $SELF start|stop|restart|force-reload"
-       exit 1
-       ;;
-esac
-
-#!/bin/sh -e
-### BEGIN INIT INFO
-# Provides:          networking
-# Required-Start:    mountkernfs ifupdown $local_fs
-# Required-Stop:     ifupdown $local_fs
-# Default-Start:     S
-# Default-Stop:      0 6
-# Short-Description: Raise network interfaces.
-### END INIT INFO
-
-PATH="/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin"
-
-[ -x /sbin/ifup ] || exit 0
-
-. /lib/lsb/init-functions
-
-
-case "$1" in
-start)
-       log_action_begin_msg "Configuring network interfaces"
-        type usplash_write >/dev/null 2>/dev/null && usplash_write "TIMEOUT 120" || true
-       if [ "$VERBOSE" != no ]; then
-           if ifup -a; then
-               log_action_end_msg $?
-           else
-               log_action_end_msg $?
-           fi
-       else
-           if ifup -a >/dev/null 2>&1; then
-               log_action_end_msg $?
-           else
-               log_action_end_msg $?
-           fi
-       fi
-        type usplash_write >/dev/null 2>/dev/null && usplash_write "TIMEOUT 15" || true
-       ;;
-
-stop)
-       if sed -n 's/^[^ ]* \([^ ]*\) \([^ ]*\) .*$/\2/p' /proc/mounts | 
-               grep -qE '^(nfs[1234]?|smbfs|ncp|ncpfs|coda|cifs)$'; then
-           log_warning_msg "not deconfiguring network interfaces: network shares still mounted."
-           exit 0
-       fi
-
-       log_action_begin_msg "Deconfiguring network interfaces"
-       if [ "$VERBOSE" != no ]; then
-           if ifdown -a --exclude=lo; then
-               log_action_end_msg $?
-           else
-               log_action_end_msg $?
-           fi
-       else
-           if ifdown -a --exclude=lo >/dev/null 2>/dev/null; then
-               log_action_end_msg $?
-           else
-               log_action_end_msg $?
-           fi
-       fi
-       ;;
-
-force-reload|restart)
-       log_action_begin_msg "Reconfiguring network interfaces"
-       ifdown -a --exclude=lo || true
-       if ifup -a --exclude=lo; then
-           log_action_end_msg $?
-       else
-           log_action_end_msg $?
-       fi
-       ;;
-
-*)
-       echo "Usage: /etc/init.d/networking {start|stop|restart|force-reload}"
-       exit 1
-       ;;
-esac
-
-exit 0
-
-#!/bin/sh
-#
-# nfs-common    This shell script takes care of starting and stopping
-#               common daemons required for NFS clients and servers.
-#
-# chkconfig: 345 20 80
-# description: NFS is a popular protocol for file sharing across \
-#             TCP/IP networks. This service provides NFS file \
-#             locking functionality.
-#
-
-set -e
-
-# What is this?
-DESC="NFS common utilities"
-
-# Read config
-DEFAULTFILE=/etc/default/nfs-common
-PREFIX=
-NEED_LOCKD=
-NEED_IDMAPD=yes
-IDMAPD_PIDFILE=/var/run/rpc.idmapd.pid
-NEED_GSSD=yes
-GSSD_PIDFILE=/var/run/rpc.gssd.pid
-PIPEFS_MOUNTPOINT=/var/lib/nfs/rpc_pipefs
-RPCGSSDOPTS=
-if [ -f $DEFAULTFILE ]; then
-    . $DEFAULTFILE
-fi
-
-. /lib/lsb/init-functions
-
-# Determine whether lockd daemon is required.
-case "$NEED_LOCKD" in
-yes|no)        ;;
-*)  case `uname -r` in
-    '' | [01].* | 2.[0123].* )
-       # Older kernels may or may not need a lockd daemon.
-       # We must assume they do, unless we can prove otherwise.
-       # (A false positive here results only in a harmless message.)
-       NEED_LOCKD=yes
-       if test -f /proc/ksyms
-       then
-           grep -q lockdctl /proc/ksyms || NEED_LOCKD=no
-       fi
-       ;;
-
-    *)  # Modern kernels (>= 2.4) start a lockd thread automatically.
-       NEED_LOCKD=no
-       ;;
-    esac
-    ;;
-esac
-
-# Exit if required binaries are missing.
-[ -x $PREFIX/sbin/rpc.statd ] || exit 0
-[ -x $PREFIX/sbin/rpc.lockd ] || [ "$NEED_LOCKD"  = no ] || exit 0
-[ -x /usr/sbin/rpc.idmapd   ] || [ "$NEED_IDMAPD" = no ] || exit 0
-[ -x /usr/sbin/rpc.gssd     ] || [ "$NEED_GSSD"   = no ] || exit 0
-
-do_modprobe() {
-    modprobe -q "$1" || true
-}
 
-do_mount() {
-    if ! grep -E -qs "$1\$" /proc/filesystems
-    then
-       return 1
-    fi
-    if ! mountpoint -q "$2"
-    then
-       mount -t "$1" "$1" "$2"
-       return
-    fi
-    return 0
-}
-
-# See how we were called.
-case "$1" in
-  start)
-       cd /    # daemons should have root dir as cwd
-       log_begin_msg "Starting nfs statd..."
-       ERROR=0
-       start-stop-daemon --start --quiet \
-           --exec $PREFIX/sbin/rpc.statd -- $STATDOPTS || ERROR=1
-       log_end_msg $ERROR
-       if [ "$NEED_LOCKD" = yes ]
-       then
-           log_begin_msg "Starting nfs lockd..."
-           ERROR=0
-           start-stop-daemon --start --quiet \
-               --exec $PREFIX/sbin/rpc.lockd || ERROR=1
-           log_end_msg $ERROR
-       fi
-       if [ "$NEED_IDMAPD" = yes ] || [ "$NEED_GSSD" = yes ]
-       then
-           do_modprobe nfs
-           if do_mount rpc_pipefs $PIPEFS_MOUNTPOINT
-           then
-               if [ "$NEED_IDMAPD" = yes ]
-               then
-                   log_begin_msg "Starting rpc idmapd..."
-                   ERROR=0
-                   start-stop-daemon --start --quiet \
-                           --make-pidfile --pidfile $IDMAPD_PIDFILE \
-                           --exec /usr/sbin/rpc.idmapd || ERROR=1
-                   log_end_msg $ERROR
-               fi
-               if [ "$NEED_GSSD" = yes ]
-               then
-                   log_begin_msg "Starting rpc gssd..."
-                   ERROR=0
-                   start-stop-daemon --start --quiet \
-                           --make-pidfile --pidfile $GSSD_PIDFILE \
-                           --exec /usr/sbin/rpc.gssd -- $RPCGSSDOPTS || ERROR=1
-                   log_end_msg $ERROR
-               fi
-           fi
-       fi
-       ;;
-
-  stop)
-       if [ "$NEED_GSSD" = yes ]
-       then
-           log_begin_msg "Stopping rpc gssd..."
-           ERROR=0
-           start-stop-daemon --stop --oknodo --quiet \
-                   --name rpc.gssd --user 0 || ERROR=1
-           log_end_msg $ERROR
-           rm -f $GSSD_PIDFILE
-       fi
-       if [ "$NEED_IDMAPD" = yes ]
-       then
-           log_begin_msg "Stopping rpc idmapd..."
-           ERROR=0
-           start-stop-daemon --stop --oknodo --quiet \
-               --name rpc.idmapd --user 0 || ERROR=1
-           log_end_msg $ERROR
-           rm -f $IDMAPD_PIDFILE
-       fi
-       if [ "$NEED_LOCKD" = yes ]
-       then
-           log_begin_msg "Stopping nfs lockd..."
-           ERROR=0
-           start-stop-daemon --stop --oknodo --quiet \
-               --name rpc.lockd --user 0  || ERROR=1
-           log_end_msg $ERROR
-       fi
-       log_begin_msg "Stopping nfs statd..."
-       ERROR=0
-       start-stop-daemon --stop --oknodo --quiet \
-           --name rpc.statd --user 0 || ERROR=1
-       log_end_msg $ERROR
-       ;;
-
-  restart | force-reload)
-       $0 stop
-       sleep 1
-       $0 start
-       ;;
-
-  *)
-       log_success_msg "Usage: nfs-common {start|stop|restart}"
-       exit 1
-       ;;
-esac
-
-exit 0
-#!/bin/sh
-#
-# nfs-kernel-server
-#              This shell script takes care of starting and stopping
-#               the kernel-mode NFS server.
-#
-# chkconfig: 345 60 20
-# description: NFS is a popular protocol for file sharing across TCP/IP \
-#              networks. This service provides NFS server functionality, \
-#              which is configured via the /etc/exports file.
-#
-
-set -e
-
-# What is this?
-DESC="NFS kernel daemon"
-PREFIX=/usr
-
-# Exit if required binaries are missing.
-[ -x $PREFIX/sbin/rpc.nfsd    ] || exit 0
-[ -x $PREFIX/sbin/rpc.mountd  ] || exit 0
-[ -x $PREFIX/sbin/exportfs    ] || exit 0
-[ -x $PREFIX/sbin/rpc.svcgssd ] || exit 0
-
-# Read config
-DEFAULTFILE=/etc/default/nfs-kernel-server
-RPCNFSDCOUNT=8
-RPCMOUNTDOPTS=
-NEED_SVCGSSD=yes
-RPCGSSDOPTS=
-RPCSVCGSSDOPTS=
-PROCNFSD_MOUNTPOINT=/proc/fs/nfsd
-if [ -f $DEFAULTFILE ]; then
-    . $DEFAULTFILE
-fi
-
-. /lib/lsb/init-functions
-
-do_modprobe() {
-    modprobe -q "$1" || true
-}
-
-do_mount() {
-    if ! grep -E -qs "$1\$" /proc/filesystems
-    then
-       return 1
-    fi
-    if ! mountpoint -q "$2"
-    then
-       mount -t "$1" "$1" "$2"
-       return
-    fi
-    return 0
-}
-
-# See how we were called.
-case "$1" in
-  start)
-       cd /    # daemons should have root dir as cwd
-       if grep -q '^/' /etc/exports
-       then
-               do_modprobe nfsd
-               do_mount nfsd $PROCNFSD_MOUNTPOINT || NEED_SVCGSSD=no
-               log_begin_msg "Exporting directories for $DESC..."
-               ERROR=0
-               $PREFIX/sbin/exportfs -r || ERROR=1
-               log_end_msg $ERROR
-
-               if [ "$NEED_SVCGSSD" = yes ]
-               then
-                   log_begin_msg "Starting rpc svcgssd..."
-                   ERROR=0
-                   start-stop-daemon --start --quiet \
-                           --make-pidfile --pidfile /var/run/rpc.svcgssd.pid \
-                           --exec $PREFIX/sbin/rpc.svcgssd -- $RPCSVCGSSDOPTS || ERROR=1
-                   log_end_msg $ERROR
-               fi
-
-               log_begin_msg "Starting rpc nfsd..."
-               ERROR=0
-               start-stop-daemon --start --quiet \
-                   --exec $PREFIX/sbin/rpc.nfsd -- $RPCNFSDCOUNT || ERROR=1
-               log_end_msg $ERROR
-
-               # make sure 127.0.0.1 is a valid source for requests
-               ClearAddr=
-               if [ -f /proc/net/rpc/auth.unix.ip/channel ]
-               then
-                   fgrep -qs 127.0.0.1 /proc/net/rpc/auth.unix.ip/content || {
-                       echo "nfsd 127.0.0.1 2147483647 localhost" >/proc/net/rpc/auth.unix.ip/channel
-                       ClearAddr=yes
-                   }
-               fi
-
-               $PREFIX/bin/rpcinfo -u localhost nfs 3 >/dev/null 2>&1 ||
-                   RPCMOUNTDOPTS="$RPCMOUNTDOPTS --no-nfs-version 3"
-
-               [ -z "$ClearAddr" ] || echo "nfsd 127.0.0.1 1" >/proc/net/rpc/auth.unix.ip/channel
-
-               log_begin_msg "Starting rpc mountd..."
-               ERROR=0
-               start-stop-daemon --start --quiet \
-                   --exec $PREFIX/sbin/rpc.mountd -- $RPCMOUNTDOPTS || ERROR=1
-               log_end_msg $ERROR
-       else
-               log_warning_msg "Not starting $DESC: No exports."
-       fi
-       ;;
-
-  stop)
-       log_begin_msg "Stopping rpc mountd..."
-       ERROR=0
-       start-stop-daemon --stop --oknodo --quiet \
-           --name rpc.mountd --user 0 || ERROR=1
-       log_end_msg $ERROR
-       if [ "$NEED_SVCGSSD" = yes ]
-       then
-           log_begin_msg "Stopping rpc svcgssd..."
-           ERROR=0
-           start-stop-daemon --stop --oknodo --quiet \
-                   --name rpc.svcgssd --user 0 || ERROR=1
-           log_end_msg $ERROR
-           rm -f /var/run/rpc.svcgssd.pid
-       fi
-       log_begin_msg "Stopping rpc nfsd..."
-       ERROR=0
-       start-stop-daemon --stop --oknodo --quiet \
-           --name nfsd --user 0 --signal 2 || ERROR=1
-       log_end_msg $ERROR
-
-       log_begin_msg "Unexporting directories for $DESC..."
-       ERROR=0
-       $PREFIX/sbin/exportfs -au || ERROR=1
-       log_end_msg $ERROR
-       ;;
-
-  reload | force-reload)
-       log_begin_msg "Re-exporting directories for $DESC..."
-       ERROR=0
-       $PREFIX/sbin/exportfs -r || ERROR=1
-       log_end_msg $ERROR
-       ;;
-
-  restart)
-       $0 stop
-       sleep 1
-       $0 start
-       ;;
-
-  *)
-       log_success_msg "Usage: nfs-kernel-server {start|stop|reload|force-reload|restart}"
-       exit 1
-       ;;
-esac
-
-exit 0
-#! /bin/sh
-#
-### BEGIN INIT INFO
-# Provides:          pcmcia
-# Required-Start:    udev
-# Required-Stop:
-# Default-Start:     S
-# Default-Stop:
-# Short-Description: PCMCIA support
-# Description:       This service provides PCMCIA hardware support for
-#                    systems running Linux >= 2.6.13-rc1.
-### END INIT INFO
-
-set -e
-
-[ -f /sbin/pccardctl ] || exit 0
-
-# If /lib/lsb/init-functions doesn't exist
-# define them here, otherwise installer breaks
-if [ -f /lib/lsb/init-functions ]; then
-    . /lib/lsb/init-functions
-else
-    log_daemon_msg()
-    {
-       echo "$1: $2"
-    }
-    log_end_msg()
-    {
-       if [ "$1" = 0 ]; then
-           echo "done"
-       else
-           echo "failed!"
-       fi
-       return $1
-    }
-    log_success_msg()
-    {
-       echo "$@"
-    }
-    log_failure_msg()
-    {
-       echo "$@"
-    }
-fi
-
-[ -f /etc/default/pcmciautils ] && . /etc/default/pcmciautils
-
-case $PCMCIA in
-    no|false)
-       exit 0
-       ;;
-esac
-
-[ -f /etc/default/rcS ] && . /etc/default/rcS
-
-# Are we running from init?
-run_by_init()
-{
-    ([ "$previous" ] && [ "$runlevel" ]) || [ "$runlevel" = S ]
-}
-
-if ls /sys/class/pcmcia_socket/* >/dev/null 2>&1; then
-    if ! run_by_init; then
-       log_success_msg "PCMCIA bridge driver already present in kernel"
-    fi
-    exit 0
-fi
-
-KERNEL_VERSION="$(uname -r | sed 's/-.*//')"
-
-supported_kernel()
-{
-    case $KERNEL_VERSION in
-       2.[012345].*|2.6.[0-9]|2.6.[0-9][!0-9]*) return 1 ;;
-       2.6.1[012]|2.6.1[012][!0-9]*) return 1 ;;
-    esac
-    return 0
-}
-
-if ! supported_kernel; then
-    if ! run_by_init; then
-       log_failure_msg "pcmciautils requires Linux >= 2.6.13-rc1; use pcmcia-cs instead"
-    fi
-    exit 1
-fi
-
-if [ -z "$PCIC" ]; then
-    if ! run_by_init; then
-       log_failure_msg "No PCMCIA bridge module specified"
-    fi
-    exit 1
-fi
-
-if ! [ -e /dev/.udev ]; then
-    if ! run_by_init; then
-       log_failure_msg "pcmciautils requires udev to be enabled"
-    fi
-    exit 1
-fi
-
-if [ "$VERBOSE" = "no" ]; then
-    MODPROBE_OPTIONS="$MODPROBE_OPTIONS -Q"
-    export MODPROBE_OPTIONS
-fi
-
-case "$1" in
-    start)
-       log_daemon_msg "Loading PCMCIA bridge driver module" "$PCIC"
-
-       if [ "$CORE_OPTS" ]; then
-           modprobe -Qb pcmcia_core $CORE_OPTS
-       fi
-       
-       modprobe -Qb $PCIC $PCIC_OPTS
-       
-       log_end_msg $?
-       ;;
-
-    stop)
-       ;;
+def inputiter():
+    if os.isatty(sys.stdin.fileno()):
+        while 1:
+            try:
+                yield raw_input('bup> ')
+            except EOFError:
+                break
+    else:
+        for line in sys.stdin:
+            yield line
+
+
+def _completer_get_subs(line):
+    (qtype, lastword) = shquote.unfinished_word(line)
+    (dir,name) = os.path.split(lastword)
+    #log('\ncompleter: %r %r %r\n' % (qtype, lastword, text))
+    n = pwd.resolve(dir)
+    subs = list(filter(lambda x: x.name.startswith(name),
+                       n.subs()))
+    return (dir, name, qtype, lastword, subs)
+
+
+_last_line = None
+_last_res = None
+def completer(text, state):
+    global _last_line
+    global _last_res
+    try:
+        line = readline.get_line_buffer()[:readline.get_endidx()]
+        if _last_line != line:
+            _last_res = _completer_get_subs(line)
+            _last_line = line
+        (dir, name, qtype, lastword, subs) = _last_res
+        if state < len(subs):
+            sn = subs[state]
+            sn1 = sn.resolve('')  # deref symlinks
+            fullname = os.path.join(dir, sn.name)
+            if stat.S_ISDIR(sn1.mode):
+                ret = shquote.what_to_add(qtype, lastword, fullname+'/',
+                                          terminate=False)
+            else:
+                ret = shquote.what_to_add(qtype, lastword, fullname,
+                                          terminate=True) + ' '
+            return text + ret
+    except Exception, e:
+        log('\nerror in completion: %s\n' % e)
+
+            
+optspec = """
+bup ftp
+"""
+o = options.Options('bup ftp', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+git.check_repo_or_die()
+
+top = vfs.RefList(None)
+pwd = top
+
+if extra:
+    lines = extra
+else:
+    readline.set_completer_delims(' \t\n\r/')
+    readline.set_completer(completer)
+    readline.parse_and_bind("tab: complete")
+    lines = inputiter()
+
+for line in lines:
+    if not line.strip():
+        continue
+    words = [word for (wordstart,word) in shquote.quotesplit(line)]
+    cmd = words[0].lower()
+    #log('execute: %r %r\n' % (cmd, parm))
+    try:
+        if cmd == 'ls':
+            for parm in (words[1:] or ['.']):
+                do_ls(parm, pwd.resolve(parm))
+        elif cmd == 'cd':
+            for parm in words[1:]:
+                pwd = pwd.resolve(parm)
+        elif cmd == 'pwd':
+            print pwd.fullname()
+        elif cmd == 'cat':
+            for parm in words[1:]:
+                write_to_file(pwd.resolve(parm).open(), sys.stdout)
+        elif cmd == 'get':
+            if len(words) not in [2,3]:
+                raise Exception('Usage: get <filename> [localname]')
+            rname = words[1]
+            (dir,base) = os.path.split(rname)
+            lname = len(words)>2 and words[2] or base
+            inf = pwd.resolve(rname).open()
+            log('Saving %r\n' % lname)
+            write_to_file(inf, open(lname, 'wb'))
+        elif cmd == 'mget':
+            for parm in words[1:]:
+                (dir,base) = os.path.split(parm)
+                for n in pwd.resolve(dir).subs():
+                    if fnmatch.fnmatch(n.name, base):
+                        try:
+                            log('Saving %r\n' % n.name)
+                            inf = n.open()
+                            outf = open(n.name, 'wb')
+                            write_to_file(inf, outf)
+                            outf.close()
+                        except Exception, e:
+                            log('  error: %s\n' % e)
+        elif cmd == 'help' or cmd == '?':
+            log('Commands: ls cd pwd cat get mget help quit\n')
+        elif cmd == 'quit' or cmd == 'exit' or cmd == 'bye':
+            break
+        else:
+            raise Exception('no such command %r' % cmd)
+    except Exception, e:
+        log('error: %s\n' % e)
+        #raise
+#!/usr/bin/env python
+import sys, mmap
+from bup import options, _hashsplit
+from bup.helpers import *
+
+optspec = """
+bup random [-S seed] <numbytes>
+--
+S,seed=   optional random number seed (default 1)
+f,force   print random data to stdout even if it's a tty
+"""
+o = options.Options('bup random', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if len(extra) != 1:
+    o.fatal("exactly one argument expected")
+
+total = parse_num(extra[0])
+
+if opt.force or (not os.isatty(1) and
+                 not atoi(os.environ.get('BUP_FORCE_TTY')) & 1):
+    _hashsplit.write_random(sys.stdout.fileno(), total, opt.seed or 0)
+else:
+    log('error: not writing binary data to a terminal. Use -f to force.\n')
+    sys.exit(1)
+#!/usr/bin/env python
+import sys, os, glob
+from bup import options
+
+optspec = """
+bup help <command>
+"""
+o = options.Options('bup help', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if len(extra) == 0:
+    # the wrapper program provides the default usage string
+    os.execvp(os.environ['BUP_MAIN_EXE'], ['bup'])
+elif len(extra) == 1:
+    docname = (extra[0]=='bup' and 'bup' or ('bup-%s' % extra[0]))
+    exe = sys.argv[0]
+    (exepath, exefile) = os.path.split(exe)
+    manpath = os.path.join(exepath, '../Documentation/' + docname + '.[1-9]')
+    g = glob.glob(manpath)
+    if g:
+        os.execvp('man', ['man', '-l', g[0]])
+    else:
+        os.execvp('man', ['man', docname])
+else:
+    o.fatal("exactly one command name expected")
+#!/usr/bin/env python
+import sys, os, stat, errno, fuse, re, time, tempfile
+from bup import options, git, vfs
+from bup.helpers import *
+
+
+class Stat(fuse.Stat):
+    def __init__(self):
+        self.st_mode = 0
+        self.st_ino = 0
+        self.st_dev = 0
+        self.st_nlink = 0
+        self.st_uid = 0
+        self.st_gid = 0
+        self.st_size = 0
+        self.st_atime = 0
+        self.st_mtime = 0
+        self.st_ctime = 0
+        self.st_blocks = 0
+        self.st_blksize = 0
+        self.st_rdev = 0
+
+
+cache = {}
+def cache_get(top, path):
+    parts = path.split('/')
+    cache[('',)] = top
+    c = None
+    max = len(parts)
+    #log('cache: %r\n' % cache.keys())
+    for i in range(max):
+        pre = parts[:max-i]
+        #log('cache trying: %r\n' % pre)
+        c = cache.get(tuple(pre))
+        if c:
+            rest = parts[max-i:]
+            for r in rest:
+                #log('resolving %r from %r\n' % (r, c.fullname()))
+                c = c.lresolve(r)
+                key = tuple(pre + [r])
+                #log('saving: %r\n' % (key,))
+                cache[key] = c
+            break
+    assert(c)
+    return c
+        
     
-    restart)
-       $0 stop
-       $0 start
-       exit $?
-       ;;
-
-    reload|force-reload)
-       ;;
-
-    *)
-       log_success_msg "Usage: $0 {start|stop|restart|reload|force-reload}"
-       exit 2
-       ;;
-esac
-#!/bin/sh
-#
-# start/stop portmap daemon.
-
-### BEGIN INIT INFO
-# Provides:          portmap
-# Required-Start:    $network
-# Required-Stop:     $network
-# Should-Start:      $named
-# Should-Stop:       $named
-# Default-Start:     S 1 2 3 4 5
-# Default-Stop:      0 6
-### END INIT INFO
-
-test -f /sbin/portmap || exit 0
-
-. /lib/lsb/init-functions
-
-OPTIONS=""
-if [ -f /etc/default/portmap ]; then
-  . /etc/default/portmap
-elif [ -f /etc/portmap.conf ]; then
-  . /etc/portmap.conf
-fi
-
-case "$1" in
-    start)
-       pid=`pidof portmap`
-       if [ -n "$pid" ] ; then
-            log_begin_msg "Not starting portmap daemon.  Already running."
-            log_end_msg 0
-            exit 0
-       fi
-       log_begin_msg "Starting portmap daemon..."
-        start-stop-daemon --start --quiet --oknodo --exec /sbin/portmap -- $OPTIONS
-       log_end_msg $?
-
-       sleep 1 # needs a short pause or pmap_set won't work. :(
-       if [ -f /var/run/portmap.upgrade-state ]; then
-         log_begin_msg "Restoring old RPC service information..."
-         pmap_set </var/run/portmap.upgrade-state
-         log_end_msg $?
-         rm -f /var/run/portmap.upgrade-state
-       else
-         if [ -f /var/run/portmap.state ]; then
-           pmap_set </var/run/portmap.state
-           rm -f /var/run/portmap.state
-         fi
-       fi
-
-       ;;
-    stop)
-       log_begin_msg "Stopping portmap daemon..."
-       pmap_dump >/var/run/portmap.state
-       start-stop-daemon --stop --quiet --oknodo --exec /sbin/portmap
-       log_end_msg $?
-       ;;
-    force-reload)
-       $0 restart
-       ;;
-    restart)
-       $0 stop
-       $0 start
-       ;;
-    *)
-       log_success_msg "Usage: /etc/init.d/portmap {start|stop|force-reload|restart}"
-       exit 1
-       ;;
-esac
-
-exit 0
-
-#!/bin/sh -e
-#
-#   /etc/init.d/ppp: start or stop PPP link.
-#
-# This configuration method is deprecated, please use /etc/network/interfaces.
-
-[ -x /usr/sbin/pppd -a -f /etc/ppp/ppp_on_boot ] || exit 0
-if [ -x /etc/ppp/ppp_on_boot ]; then RUNFILE=1; fi
-. /lib/lsb/init-functions
-
-case "$1" in
-start)
-    log_begin_msg "Starting up PPP link..."
-    if [ "$RUNFILE" = "1" ]; then
-        /etc/ppp/ppp_on_boot
-    else
-        pppd call provider
-    fi
-    log_end_msg $?
-    ;;
-stop)
-    log_begin_msg "Shutting down PPP link..."
-    if [ "$RUNFILE" = "1" ]; then
-        poff -a
-    else
-        poff provider
-    fi
-    log_end_msg $?
-    ;;
-restart|force-reload)
-    log_begin_msg "Restarting PPP link..."
-    if [ "$RUNFILE" = "1" ]; then      
-        poff -a || true
-        sleep 5
-        /etc/ppp/ppp_on_boot
-    else                  
-        poff provider || true
-        sleep 5
-        pppd call provider
-    fi
-    log_end_msg $?
-    ;;
-*)
-    log_success_msg "Usage: /etc/init.d/ppp {start|stop|restart|force-reload}"
-    exit 1
-    ;;
-esac
-
-exit 0
-#!/bin/sh -e
-### BEGIN INIT INFO
-# Provides:          pppd-dns
-# Required-Start:    $local_fs
-# Default-Start:     S
-# Short-Description: Restore resolv.conf if the system crashed.
-### END INIT INFO
-#
-# Restore /etc/resolv.conf if the system crashed before the ppp link
-# was shut down.
-
-[ -x /etc/ppp/ip-down.d/0000usepeerdns ] \
-       && exec /etc/ppp/ip-down.d/0000usepeerdns
-
-#!/bin/sh
-###########################################################################
-# Autostart script for guest tools' service.
-#
-# Copyright (c) 2005-2008 Parallels Software International, Inc.
-# All rights reserved.
-# http://www.parallels.com
-###########################################################################
-
-
-###
-# chkconfig: 2345 99 20
-# description: Autostart script for guest tools' service.
-###
-
-### BEGIN INIT INFO
-# Provides: prltoolsd
-# required-start:
-# required-stop:
-# Default-Start: 2 3 4 5
-# Default-Stop:  0 1 6
-# Description:   Autostart script for guest tools' service.
-### END INIT INFO
-
-
-###########################################################################
-# Set configuration data
-###########################################################################
-
-prlfile="prltoolsd"
-exefile="/usr/bin/${prlfile}"
-pidfile="/var/run/${prlfile}.pid"
-
-# Set custom options if they are required
-PRLTOOLSD_OPTIONS="-p $pidfile"
-
-###########################################################################
-# Install client ID for wireless bridged networking
-###########################################################################
-
-# Install record for client ID sending for each networking card
-# in the system in the dhclient.conf (dhclient is installed)
-dhclient_install() {
-       # Locate dhclient.conf using strings. The directory can be
-       # different on different distributions
-       CONF=`strings /sbin/dhclient | grep etc | grep dhclient.conf`
-       IFACES=$*
-
-       # and can even not exists...
-       mkdir -p `dirname $CONF`
-       touch $CONF
-
-       for IFACE in $IFACES; do
-               HWADDR=`ifconfig -a | grep ^$IFACE | awk '{ print $5 }'`
-               export IFACE HWADDR
-
-               # Install section like
-                # interface "eth0" {
-               #       send dhcp-client-identifier 1:<real_mac>;
-               # }
-                # or leave it untouched if present
-               awk '
-                       BEGIN {
-                               inside_iface = 0
-                               iface_found = 0
-                       }
-                       END {
-                               iface = ENVIRON["IFACE"]
-                               addr = ENVIRON["HWADDR"]
-                               if (!iface_found) {
-                                       print "interface \""iface"\" {"
-                                       print " send dhcp-client-identifier 1:"addr"; # Remove this comment on manual client-id modification"
-                                       print "}"
-                               }
-                       }
-
-                       /^ *interface/ {
-                               iface = ENVIRON["IFACE"]
-                               test_if = $2
-                               gsub(/\"/, "", test_if)
-                               gsub(/ /, "", test_if)
-                               if (test_if == iface)
-                                       iface_found = inside_iface = 1
-                       }
-
-                       /dhcp-client-identifier/ {
-                               str = $0
-                               if (inside_iface &&
-                                   match(str, /Remove this/))
-                                       next
-                               else
-                                       inside_iface = 0
-                       }
-
-                       /\}/ {
-                               addr = ENVIRON["HWADDR"]
-
-                               if (inside_iface)
-                                       print " send dhcp-client-identifier 1:"addr"; # Remove this comment on manual client-id modification"
-                               inside_iface = 0
-                       }
-
-                       {
-                               print $0
-                       }
-               ' $CONF >$CONF.tmp1 || exit 0
-               mv $CONF.tmp1 $CONF
-       done
-}
-
-# Install key to send client ID (dhcpcd is installed)
-# Kludge to do this on the per/interface basis is not found
-dhcpc_install() {
-       CONF="/etc/sysconfig/network/dhcp"
-       HWADDR=`/sbin/ifconfig -a | awk '/HWaddr/ { print $5 ; exit }'`
-       export HWADDR
-       awk '/DHCLIENT_CLIENT_ID=/{
-               str = str1 = $0
-               sub(/\".*\"/, "", str1)
-               if (length(str1) + 2 >= length(str) || match($str, /Remove this/))
-                       print "DHCLIENT_CLIENT_ID=\"1:"ENVIRON["HWADDR"]"\" # Remove this comment on manual client-id modification"
-               else
-                       print $0
-               next
-       }
-       {
-               print $0
-       }
-       ' $CONF >$CONF.tmp1 || exit 0
-       mv $CONF.tmp1 $CONF
-}
-
-clientid_install() {
-       IFACES=`ifconfig -a | awk '/HWaddr/{ print $1 }' | xargs`
-       if [ -n "$IFACES" ]; then
-               [ -f /sbin/dhclient ] && dhclient_install $IFACES
-               [ -f /etc/sysconfig/network/dhcp ] && dhcpc_install $IFACES
-       fi
-}
-
-###########################################################################
-# Start and Stop operations for tools' daemon
-###########################################################################
-
-start() {
-    if [ -f $pidfile ]; then
-        rm -f $pidfile;
-    fi
-
-    echo -n $"Loading Parallels ToolsGate driver: "
-    if modprobe prl_tg; then
-        echo $"done"
-    else
-        echo $"failed"
-    fi
-
-    echo -n $"Loading Parallels Network driver: "
-
-       # Installing client-id to the DHCP client configuration
-       # is temporary disabled.
-
-    #clientid_install
-
-    if modprobe prl_eth; then
-        echo $"done"
-    else
-        echo $"failed"
-    fi
-
-    echo -n $"Loading Parallels Shared Folders driver: "
-    if modprobe prl_fs; then
-        echo $"done"
-    else
-        echo $"failed"
-    fi
-
-    echo -n $"Starting Parallels tools daemon: "
-    $exefile ${PRLTOOLSD_OPTIONS}
-    RETVAL=$?
-    if [ -n $RETVAL ]; then
-        echo $"done"
-    else
-        echo $"failed"
-    fi
-
-    return $RETVAL
-}
-
-stop() {
-    RETVAL=0
-
-    echo -n $"Shutting down Parallels tools daemon: "
-
-    if [ -f $pidfile ]; then
-        prlpid=`cat $pidfile 2>/dev/null`
-
-        if [ -n $prlpid ] && [ -e /proc/$prlpid ]; then
-            kill $prlpid;
-            RETVAL=$?
-        fi
-
-        rm -f $pidfile;
-    fi
-
-    if [ -n $RETVAL ]; then
-        echo $"done"
-    else
-        echo $"failed"
-    fi
-
-    return $RETVAL
-}
-
-###########################################################################
-# Perform initial operations
-###########################################################################
-
-[ -f $exefile ] || exit 0
-
-###########################################################################
-# Start/stop guest tools' service
-###########################################################################
-
-case "$1" in
-    start)
-        start
-    ;;
-    stop)
-        stop
-    ;;
-    restart)
-        stop
-        start
-    ;;
-    *)
-        echo "=> This script starts/stops Parallels guest tools' service"
-        echo "Usage: $0 <start | stop | restart>"
-        exit 1
-    ;;
-esac
-
-exit $?
-#! /bin/sh
-# /etc/init.d/procps: Set kernel variables from /etc/sysctl.conf
-#
-# written by Elrond <Elrond@Wunder-Nett.org>
-
-### BEGIN INIT INFO
-# Provides:          procps
-# Required-Start:    mountkernfs
-# Required-Stop:
-# Default-Start:     S
-# Default-Stop:
-# Short-Description: Configure kernel parameters at boottime
-# Description:  Loads kernel parameters that are specified in /etc/sysctl.conf
-### END INIT INFO
-
-
-# Check for existance of the default file and exit if not there,
-# Closes #52839 for the boot-floppy people
-[ -r /etc/default/rcS ] || exit 0
-. /etc/default/rcS
-. /lib/lsb/init-functions
-
-PATH=/sbin:$PATH
-which sysctl > /dev/null || exit 0
-
-
-case "$1" in
-       start|restart|force-reload)
-               if [ ! -r /etc/sysctl.conf ]
-               then
-                       exit 0
-               fi
-               quiet="-q"
-               if [ "$VERBOSE" = "yes" ]; then
-                       quiet=""
-               fi
-              log_action_begin_msg "Setting kernel variables"
-               sysctl $quiet -p
-              log_action_end_msg $?
-               ;;
-       stop)
-               ;;
-       *)
-               echo "Usage: /etc/init.d/procps {start|stop|restart|force-reload}" >&2
-               exit 3
-               ;;
-esac
-exit 0
-#! /bin/sh
-#
-# rc
-#
-# Starts/stops services on runlevel changes.
-#
-# Optimization: A start script is not run when the service was already
-# configured to run in the previous runlevel.  A stop script is not run
-# when the the service was already configured not to run in the previous
-# runlevel.
-#
-# Authors:
-#      Miquel van Smoorenburg <miquels@cistron.nl>
-#      Bruce Perens <Bruce@Pixar.com>
-
-PATH=/sbin:/bin:/usr/sbin:/usr/bin
-export PATH
-
-# Un-comment the following for debugging.
-# debug=echo
-
-# Specify method used to enable concurrent init.d scripts.
-# Valid options are 'none' and 'shell'.
-CONCURRENCY=none
 
-# Make sure the name survive changing the argument list
-scriptname="$0"
-
-umask 022
-
-#
-# Stub to do progress bar ticks (currently just for usplash) on startup
-#
-startup_progress() {
-    $@
-    step=$(($step + $step_change))
-    progress=$(($step * $progress_size / $num_steps + $first_step))
-    if type usplash_write >/dev/null 2>&1; then
-        usplash_write "PROGRESS $progress" || true
-    fi
-}
-
-#
-# Start script or program.
-#
-case "$CONCURRENCY" in
-  none)
-       startup() {
-               action=$1
-               shift
-               scripts="$@"
-               sh=sh
-               # Debian Policy Â§9.3.1 requires .sh scripts in runlevel S to be sourced
-               # However, some important packages currently contain .sh scripts
-               # that do "exit" at some point, thus killing this process.  Bad!
-               #[ S = "$runlevel" ] && sh=.
-               for script in $scripts ; do
-                       case "$script" in
-                         *.sh)
-                               if [ "." = "$sh" ] ; then
-                                       set "$action"
-                                       RC_SAVE_PATH="$PATH"
-                                       startup_progress $debug . "$script"
-                                       PATH="$RC_SAVE_PATH"
-                               else
-                                       startup_progress $debug $sh "$script" $action
-                               fi
-                               ;;
-                         *)
-                               startup_progress $debug "$script" $action
-                               ;;
-                       esac
-               done
-       }
-       ;;
-  shell)
-       startup() {
-               action=$1
-               shift
-               scripts="$@"
-               sh=sh
-               # Debian Policy Â§9.3.1 requires .sh scripts in runlevel S to be sourced
-               # However, some important packages currently contain .sh scripts
-               # that do "exit" at some point, thus killing this process.  Bad!
-               #[ S = "$runlevel" ] && sh=.
-               backgrounded=0
-               for script in $scripts ; do
-                       case "$script" in
-                         *.sh)
-                               if [ "." = "$sh" ] ; then
-                                       set "$action"
-                                       RC_SAVE_PATH="$PATH"
-                                       startup_progress $debug . "$script"
-                                       PATH="$RC_SAVE_PATH"
-                               else
-                                       startup_progress $debug $sh "$script" $action
-                               fi
-                               ;;
-                         *)
-                               startup_progress $debug "$script" $action &
-                               backgrounded=1
-                               ;;
-                       esac
-               done
-               [ 1 = "$backgrounded" ] && wait
-       }
-       ;;
-  startpar)
-       startup() {
-               action=$1
-               shift
-               scripts="$@"
-               sh=sh
-               # Debian Policy Â§9.3.1 requires .sh scripts in runlevel S to be sourced
-               # However, some important packages currently contain .sh scripts
-               # that do "exit" at some point, thus killing this process.  Bad!
-               #[ S = "$runlevel" ] && sh=.
-               # Make sure .sh scripts are sourced in runlevel S
-               if [ "." = "$sh" ] ; then
-                       newscripts=
-                       for script in $scripts ; do
-                               case "$script" in
-                                 *.sh)
-                                       set "$action"
-                                       RC_SAVE_PATH="$PATH"
-                                       startup_progress $debug . "$script"
-                                       PATH="$RC_SAVE_PATH"
-                                       ;;
-                                 *)
-                                       newscripts="$newscripts $script"
-                                       ;;
-                               esac
-                       done
-                       scripts="$newscripts"
-               fi
-
-               # startpar is not working as it should yet [pere 2005-09-10]
-               [ -n "$scripts" ] && startup_progress $debug startpar -a $action $scripts
-               startup_progress $debug startpar -a $action $scripts
-       }
-       ;;
-esac
-
-on_exit() {
-    echo "error: '$scriptname' exited outside the expected code flow."
-}
-trap on_exit EXIT # Enable emergency handler
-
-# Ignore CTRL-C only in this shell, so we can interrupt subprocesses.
-trap ":" INT QUIT TSTP
-
-# Should we also output to the console?
-# /proc won't be mounted if we don't have an initramfs, but then we're
-# dealing with custom systems so it's their own fault that they'll get
-# output from rcS ;)
-if grep -w -q quiet /proc/cmdline 2>/dev/null; then
-    QUIET=yes
-else
-    QUIET=no
-fi
-export QUIET
-
-# Set onlcr to avoid staircase effect.
-if [ "$QUIET" != yes ]; then
-    stty onlcr </dev/console >/dev/console 2>&1
-fi
-
-# Now find out what the current and what the previous runlevel are.
-runlevel=$RUNLEVEL
-
-# Get first argument. Set new runlevel to this argument.
-[ "$1" != "" ] && runlevel=$1
-if [ "$runlevel" = "" ]
-then
-       echo "Usage: $scriptname <runlevel>" >&2
-       exit 1
-fi
-previous=$PREVLEVEL
-[ "$previous" = "" ] && previous=N
-
-export runlevel previous
-
-if [ S = "$runlevel" ]
-then
-       #
-       # See if system needs to be setup. This is ONLY meant to
-       # be used for the initial setup after a fresh installation!
-       #
-       if [ -x /sbin/unconfigured.sh ]
-       then
-               /sbin/unconfigured.sh
-       fi
-fi
-
-. /etc/default/rcS
-export VERBOSE
-
-# Is there an rc directory for this new runlevel?
-if [ -d /etc/rc$runlevel.d ]
-then
-       # Split the progress bar into thirds
-       progress_size=$((100 / 3))
-
-       case "$runlevel" in
-               0|6)
-                       ACTION=stop
-                       # Count down from 0 to -100 and use the entire bar
-                       first_step=0
-                       progress_size=100
-                       step_change=-1
-                       ;;
-               S)
-                       ACTION=start
-                       # Use 2/3 of the space
-                       first_step=0
-                       progress_size=$(($progress_size * 2))
-                       step_change=1
-                       ;;
-               *)
-                       ACTION=start
-                       # Begin where rcS left off and use the final 1/3 of
-                       # the space (by leaving progress_size unchanged)
-                       first_step=$(($progress_size * 2))
-                       step_change=1
-                       ;;
-       esac
-
-       # Count the number of scripts we need to run (for usplash progress bar)
-       num_steps=0
-       for s in /etc/rc$runlevel.d/[SK]*; do
-            case "${s##/etc/rc$runlevel.d/S??}" in
-                gdm|xdm|kdm|ltsp-client-core|reboot|halt)
-                    break
-                    ;;
-            esac
-            num_steps=$(($num_steps + 1))
-        done
-
-        step=0
-
-       # First, run the KILL scripts.
-       if [ "$previous" != N ]
-       then
-               # Run all scripts with the same level in parallel
-               CURLEVEL=""
-               for s in /etc/rc$runlevel.d/K*
-               do
-                       level=$(echo $s | sed 's/.*\/K\([0-9][0-9]\).*/\1/')
-                       if [ "$level" = "$CURLEVEL" ]
-                       then
-                               continue
-                       fi
-                       CURLEVEL=$level
-                       SCRIPTS=""
-                       for i in /etc/rc$runlevel.d/K$level*
-                       do
-                               # Check if the script is there.
-                               [ ! -f $i ] && continue
-
-                               #
-                               # Find stop script in previous runlevel but
-                               # no start script there.
-                               #
-                               suffix=${i#/etc/rc$runlevel.d/K[0-9][0-9]}
-                               previous_stop=/etc/rc$previous.d/K[0-9][0-9]$suffix
-                               previous_start=/etc/rc$previous.d/S[0-9][0-9]$suffix
-                               #
-                               # If there is a stop script in the previous level
-                               # and _no_ start script there, we don't
-                               # have to re-stop the service.
-                               #
-                               [ -f $previous_stop ] && [ ! -f $previous_start ] && continue
-
-                               # Stop the service.
-                               SCRIPTS="$SCRIPTS $i"
-                       done
-                       startup stop $SCRIPTS
-               done
-       fi
-
-       # Now run the START scripts for this runlevel.
-       # Run all scripts with the same level in parallel
-       CURLEVEL=""
-       for s in /etc/rc$runlevel.d/S*
-       do
-               level=$(echo $s | sed 's/.*\/S\([0-9][0-9]\).*/\1/')
-               if [ "$level" = "$CURLEVEL" ]
-               then
-                       continue
-               fi
-               CURLEVEL=$level
-               SCRIPTS=""
-               for i in /etc/rc$runlevel.d/S$level*
-               do
-                       [ ! -f $i ] && continue
-
-                       if [ "$previous" != N ]
-                       then
-                               #
-                               # Find start script in previous runlevel and
-                               # stop script in this runlevel.
-                               #
-                               suffix=${i#/etc/rc$runlevel.d/S[0-9][0-9]}
-                               stop=/etc/rc$runlevel.d/K[0-9][0-9]$suffix
-                               previous_start=/etc/rc$previous.d/S[0-9][0-9]$suffix
-                               #
-                               # If there is a start script in the previous level
-                               # and _no_ stop script in this level, we don't
-                               # have to re-start the service.
-                               #
-                               [ -f $previous_start ] && [ ! -f $stop ] && continue
-                       fi
-                       SCRIPTS="$SCRIPTS $i"
-               done
-               startup $ACTION $SCRIPTS
-       done
-fi
-
-if [ S = "$runlevel" ]
-then
-       #
-       # For compatibility, run the files in /etc/rc.boot too.
-       #
-       [ -d /etc/rc.boot ] && run-parts /etc/rc.boot
-
-       #
-       # Finish setup if needed. The comment above about
-       # /sbin/unconfigured.sh applies here as well!
-       #
-       if [ -x /sbin/setup.sh ]
-       then
-               /sbin/setup.sh
-       fi
-fi
-
-trap - EXIT # Disable emergency handler
-
-exit 0
-
-#! /bin/sh
-
-PATH=/sbin:/bin:/usr/sbin:/usr/bin
-[ -f /etc/default/rcS ] && . /etc/default/rcS
-. /lib/lsb/init-functions
-
-do_start() {
-       if [ -x /etc/rc.local ]; then
-               log_begin_msg "Running local boot scripts (/etc/rc.local)"
-               /etc/rc.local
-               log_end_msg $?
-       fi
-}
-
-case "$1" in
-    start)
-       do_start
-        ;;
-    restart|reload|force-reload)
-        echo "Error: argument '$1' not supported" >&2
-        exit 3
-        ;;
-    stop)
-        ;;
-    *)
-        echo "Usage: $0 start|stop" >&2
-        exit 3
-        ;;
-esac
-#! /bin/sh
-#
-# rcS
-#
-# Call all S??* scripts in /etc/rcS.d/ in numerical/alphabetical order
-#
-
-exec /etc/init.d/rc S
-       Configuration of System V init under Debian GNU/Linux
-
-Most Unix versions have a file here that describes how the scripts
-in this directory work, and how the links in the /etc/rc?.d/ directories
-influence system startup/shutdown.
-
-For Debian, this information is contained in the policy manual, chapter 
-"System run levels and init.d scripts".  The Debian Policy Manual is 
-available at:
-
-    http://www.debian.org/doc/debian-policy/#contents
-
-The Debian Policy Manual is also available in the Debian package
-"debian-policy".  When this package is installed, the policy manual can be
-found in directory /usr/share/doc/debian-policy. If you have a browser
-installed you can probably read it at
-
-    file://localhost/usr/share/doc/debian-policy/
-
-Some more detailed information can also be found in the files in the
-/usr/share/doc/sysv-rc directory.
-
-Debian Policy dictates that /etc/init.d/*.sh scripts must work properly
-when sourced.  The following additional rules apply:
-
-* /etc/init.d/*.sh scripts may not rely for their correct functioning
-  on their being sourced rather than executed.  That is, they must work
-  properly when executed too. They must include "#!/bin/sh" at the top.
-
-* /etc/init.d/*.sh scripts must conform to the rules for sh scripts as
-  spelled out in the Debian policy section entitled "Scripts" (§10.4).
-
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          reboot
-# Required-Start:    umountroot $network
-# Required-Stop:
-# Should-Start:      lvm raid2
-# Default-Start:     6
-# Default-Stop:
-# Short-Description: Execute the reboot command.
-# Description:
-### END INIT INFO
-
-PATH=/usr/sbin:/usr/bin:/sbin:/bin
-
-. /lib/lsb/init-functions
-
-do_stop () {
-       # Message should end with a newline since kFreeBSD may
-       # print more stuff (see #323749)
-       log_action_msg "Will now restart"
-       reboot -d -f -i
-}
-
-case "$1" in
-  start)
-       # No-op
-       ;;
-  restart|reload|force-reload)
-       echo "Error: argument '$1' not supported" >&2
-       exit 3
-       ;;
-  stop)
-       do_stop
-       ;;
-  *)
-       echo "Usage: $0 start|stop" >&2
-       exit 3
-       ;;
-esac
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          rmnologin
-# Required-Start:    $local_fs $remote_fs
-# Required-Stop: 
-# Should-Start:      kdm xdm gdm $syslog
-# Default-Start:     0 1 2 3 4 5 6
-# Default-Stop:       
-# Short-Description: Remove /etc/nologin at boot
-# Description:       This script removes the /etc/nologin file as the
-#                    last step in the boot process, if DELAYLOGIN=yes.
-#                    If DELAYLOGIN=no, /etc/nologin was not created by
-#                    bootmisc earlier in the boot process.
-### END INIT INFO
-
-PATH=/sbin:/bin
-[ "$DELAYLOGIN" ] || DELAYLOGIN=yes
-. /lib/init/vars.sh
-
-do_start () {
-       #
-       # If login delaying is enabled then remove the flag file
-       #
-       case "$DELAYLOGIN" in
-         Y*|y*)
-               rm -f /var/lib/initscripts/nologin
-               ;;
-       esac
-}
-
-case "$1" in
-  start)
-       do_start
-       ;;
-  restart|reload|force-reload)
-       echo "Error: argument '$1' not supported" >&2
-       exit 3
-       ;;
-  stop)
-       # No-op
-       ;;
-  *)
-       echo "Usage: $0 start|stop" >&2
-       exit 3
-       ;;
-esac
-
-:
-#! /bin/sh
-
-### BEGIN INIT INFO
-# Provides:          rsyncd
-# Required-Start:    $network
-# Required-Stop:     $syslog
-# Should-Start:      $named $syslog
-# Should-Stop:       $syslog network
-# Default-Start:     2 3 4 5
-# Default-Stop:      0 1 6
-# Short-Description: fast remote file copy program daemon
-# Description:       rsync is a program that allows files to be copied to and
-#                    from remote machines in much the same way as rcp.
-#                    This provides rsyncd daemon functionality.
-### END INIT INFO
-
-set -e
-
-# /etc/init.d/rsync: start and stop the rsync daemon
-
-DAEMON=/usr/bin/rsync
-RSYNC_ENABLE=false
-RSYNC_OPTS=''
-RSYNC_DEFAULTS_FILE=/etc/default/rsync
-RSYNC_CONFIG_FILE=/etc/rsyncd.conf
-RSYNC_NICE_PARM=''
-
-test -x $DAEMON || exit 0
-
-. /lib/lsb/init-functions
-. /etc/default/rcS
-
-if [ -s $RSYNC_DEFAULTS_FILE ]; then
-    . $RSYNC_DEFAULTS_FILE
-    case "x$RSYNC_ENABLE" in
-        xtrue|xfalse)   ;;
-        xinetd)         exit 0
-                        ;;
-        *)              log_failure_msg "Value of RSYNC_ENABLE in $RSYNC_DEFAULTS_FILE must be either 'true' or 'false';"
-                        log_failure_msg "not starting rsync daemon."
-                        exit 1
-                        ;;
-    esac
-    case "x$RSYNC_NICE" in
-        x[0-9])         RSYNC_NICE_PARM="--nicelevel $RSYNC_NICE";;
-        x[1-9][0-9])    RSYNC_NICE_PARM="--nicelevel $RSYNC_NICE";;
-        x)              ;;
-        *)              log_warning_msg "Value of RSYNC_NICE in $RSYNC_DEFAULTS_FILE must be a value between 0 and 19 (inclusive);"
-                        log_warning_msg "ignoring RSYNC_NICE now."
-                        ;;
-    esac
-fi
-
-export PATH="${PATH:+$PATH:}/usr/sbin:/sbin"
-
-case "$1" in
-  start)
-       if "$RSYNC_ENABLE"; then
-            log_daemon_msg "Starting rsync daemon" "rsync"
-           if [ -s /var/run/rsync.pid ] && kill -0 $(cat /var/run/rsync.pid) >/dev/null 2>&1; then
-                log_progress_msg "apparently already running"
-                log_end_msg 0
-               exit 0
-           fi
-            if [ ! -s "$RSYNC_CONFIG_FILE" ]; then
-                log_failure_msg "missing or empty config file $RSYNC_CONFIG_FILE"
-               log_end_msg 1
-                exit 1
-            fi
-            if start-stop-daemon --start --quiet --background \
-                --pidfile /var/run/rsync.pid --make-pidfile \
-                $RSYNC_NICE_PARM --exec /usr/bin/rsync \
-                -- --no-detach --daemon --config "$RSYNC_CONFIG_FILE" $RSYNC_OPTS
-            then
-                rc=0
-                sleep 1
-                if ! kill -0 $(cat /var/run/rsync.pid) >/dev/null 2>&1; then
-                    log_failure_msg "rsync daemon failed to start"
-                    rc=1
-                fi
-            else
-                rc=1
-            fi
-            if [ $rc -eq 0 ]; then
-                log_end_msg 0
-            else
-                log_end_msg 1
-                rm -f /var/run/rsync.pid
-            fi
-        else
-            if [ -s "$RSYNC_CONFIG_FILE" ]; then
-               [ "$VERBOSE" != no ] && log_warning_msg "rsync daemon not enabled in /etc/default/rsync, not starting..."
-            fi
-        fi
-       ;;
-  stop)
-        log_daemon_msg "Stopping rsync daemon" "rsync"
-       start-stop-daemon --stop --quiet --oknodo --pidfile /var/run/rsync.pid
-        log_end_msg $?
-       rm -f /var/run/rsync.pid
-       ;;
-
-  reload|force-reload)
-        log_warning_msg "Reloading rsync daemon: not needed, as the daemon"
-        log_warning_msg "re-reads the config file whenever a client connects."
-       ;;
-
-  restart)
-       set +e
-        if $RSYNC_ENABLE; then
-            log_daemon_msg "Restarting rsync daemon" "rsync"
-           if [ -s /var/run/rsync.pid ] && kill -0 $(cat /var/run/rsync.pid) >/dev/null 2>&1; then
-               start-stop-daemon --stop --quiet --oknodo --pidfile /var/run/rsync.pid || true
-               sleep 1
-           else
-                log_warning_msg "rsync daemon not running, attempting to start."
-               rm -f /var/run/rsync.pid
-           fi
-            if start-stop-daemon --start --quiet --background \
-                --pidfile /var/run/rsync.pid --make-pidfile \
-                $RSYNC_NICE_PARM --exec /usr/bin/rsync \
-                -- --no-detach --daemon --config "$RSYNC_CONFIG_FILE" $RSYNC_OPTS
-            then
-                rc=0
-                sleep 1
-                if ! kill -0 $(cat /var/run/rsync.pid) >/dev/null 2>&1; then
-                    log_failure_msg "rsync daemon failed to start"
-                    rc=1
-                fi
-            else
-                rc=1
-            fi
-            if [ $rc -eq 0 ]; then
-                log_end_msg 0
-            else
-                log_end_msg 1
-                rm -f /var/run/rsync.pid
-            fi
-        else
-            [ "$VERBOSE" != no ] && log_warning_msg "rsync daemon not enabled in /etc/default/rsync, not starting..."
-        fi
-       ;;
-
-  *)
-       echo "Usage: /etc/init.d/rsync {start|stop|reload|force-reload|restart}"
-       exit 1
-esac
-
-exit 0
-#!/bin/sh
-
-### BEGIN INIT INFO
-# Provides:          samba
-# Required-Start:    $network $local_fs $remote_fs
-# Required-Stop:     $network $local_fs $remote_fs
-# Default-Start:     2 3 4 5
-# Default-Stop:      0 1 6
-# Short-Description: start Samba daemons (nmbd and smbd)
-### END INIT INFO
-
-
-# Defaults
-RUN_MODE="daemons"
-
-# Reads config file (will override defaults above)
-[ -r /etc/default/samba ] && . /etc/default/samba
-
-DAEMON=/usr/sbin/smbd
-PIDDIR=/var/run/samba
-NMBDPID=$PIDDIR/nmbd.pid
-SMBDPID=$PIDDIR/smbd.pid
-
-# clear conflicting settings from the environment
-unset TMPDIR
-
-# See if the daemons are there
-test -x /usr/sbin/nmbd -a -x /usr/sbin/smbd || exit 0
-
-. /lib/lsb/init-functions
-
-case "$1" in
-       start)
-               log_daemon_msg "Starting Samba daemons"
-               # Make sure we have our PIDDIR, even if it's on a tmpfs
-               install -o root -g root -m 755 -d $PIDDIR
-
-               NMBD_DISABLED=`testparm -s --parameter-name='disable netbios' 2>/dev/null`
-               if [ "$NMBD_DISABLED" != 'Yes' ]; then
-                       log_progress_msg "nmbd"
-                       if ! start-stop-daemon --start --quiet --oknodo --exec /usr/sbin/nmbd -- -D
-                       then
-                               log_end_msg 1
-                               exit 1
-                       fi
-               fi
-
-               if [ "$RUN_MODE" != "inetd" ]; then
-                       log_progress_msg "smbd"
-                       if ! start-stop-daemon --start --quiet --oknodo --exec /usr/sbin/smbd -- -D; then
-                               log_end_msg 1
-                               exit 1
-                       fi
-               fi
-
-               log_end_msg 0
-               ;;
-       stop)
-               log_daemon_msg "Stopping Samba daemons"
-               log_progress_msg "nmbd"
-
-               start-stop-daemon --stop --quiet --pidfile $NMBDPID
-               # Wait a little and remove stale PID file
-               sleep 1
-               if [ -f $NMBDPID ] && ! ps h `cat $NMBDPID` > /dev/null
-               then
-                       # Stale PID file (nmbd was succesfully stopped),
-                       # remove it (should be removed by nmbd itself IMHO.)
-                       rm -f $NMBDPID
-               fi
-
-               if [ "$RUN_MODE" != "inetd" ]; then
-                       log_progress_msg "smbd"
-                       start-stop-daemon --stop --quiet --pidfile $SMBDPID
-                       # Wait a little and remove stale PID file
-                       sleep 1
-                       if [ -f $SMBDPID ] && ! ps h `cat $SMBDPID` > /dev/null
-                       then
-                               # Stale PID file (nmbd was succesfully stopped),
-                               # remove it (should be removed by smbd itself IMHO.)
-                               rm -f $SMBDPID
-                       fi
-               fi
-
-               log_end_msg 0
-
-               ;;
-       reload)
-               log_daemon_msg "Reloading /etc/samba/smb.conf" "smbd only"
-
-               start-stop-daemon --stop --signal HUP --pidfile $SMBDPID
-
-               log_end_msg 0
-               ;;
-       restart|force-reload)
-               $0 stop
-               sleep 1
-               $0 start
-               ;;
-       status)
-               pidofproc -p $SMBDPID $DAEMON >/dev/null
-               status=$?
-               if [ $status -eq 0 ]; then
-                       log_success_msg "SMBD is running"
-               else
-                       log_failure_msg "SMBD is not running"
-               fi
-               exit $status
-               ;;
-       *)
-               echo "Usage: /etc/init.d/samba {start|stop|reload|restart|force-reload|status}"
-               exit 1
-               ;;
-esac
-
-exit 0
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          sendsigs
-# Required-Start:    
-# Required-Stop: 
-# Default-Start:     6
-# Default-Stop:       
-# Short-Description: Kill all remaining processes.
-# Description: 
-### END INIT INFO
-
-PATH=/usr/sbin:/usr/bin:/sbin:/bin
-
-. /lib/lsb/init-functions
-
-do_stop () {
-       OMITPIDS=
-       if [ -e /var/run/sendsigs.omit ]; then
-               for pid in $(cat /var/run/sendsigs.omit); do
-                       OMITPIDS="${OMITPIDS:+$OMITPIDS }-o $pid"
-               done
-       fi
-
-       if [ -d /var/run/sendsigs.omit.d/ ]; then
-               for pidfile in /var/run/sendsigs.omit.d/*; do
-                       [ -f "$pidfile" ] || continue
-                       for pid in $(cat $pidfile); do
-                               OMITPIDS="${OMITPIDS:+$OMITPIDS }-o $pid"
-                       done
-               done
-       fi
-
-       # Kill all processes.
-       log_action_begin_msg "Terminating all remaining processes"
-       killall5 -15 $OMITPIDS
-       log_action_end_msg 0
-       sleep 5
-       log_action_begin_msg "Sending all processes the KILL signal"
-       killall5 -9 $OMITPIDS
-       log_action_end_msg 0
-}
-
-case "$1" in
-  start)
-       # No-op
-       ;;
-  restart|reload|force-reload)
-       echo "Error: argument '$1' not supported" >&2
-       exit 3
-       ;;
-  stop)
-       do_stop
-       if which usplash_down >/dev/null; then
-               usplash_down
-       fi
-       ;;
-  *)
-       echo "Usage: $0 start|stop" >&2
-       exit 3
-       ;;
-esac
-
-:
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          single
-# Required-Start:    $local_fs killprocs
-# Required-Stop:
-# Default-Start:     1
-# Default-Stop:
-# Short-Description: executed by init(8) upon entering runlevel 1 (single).
-### END INIT INFO
-
-PATH=/sbin:/bin
-
-. /lib/lsb/init-functions
-
-do_start () {
-       log_action_msg "Will now switch to single-user mode"
-       exec init -t1 S
-}
-
-case "$1" in
-  start)
-       do_start
-       ;;
-  restart|reload|force-reload)
-       echo "Error: argument '$1' not supported" >&2
-       exit 3
-       ;;
-  stop)
-       # No-op
-       ;;
-  *)
-       echo "Usage: $0 start|stop" >&2
-       exit 3
-       ;;
-esac
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          skeleton
-# Required-Start:    $local_fs $remote_fs
-# Required-Stop:     $local_fs $remote_fs
-# Default-Start:     2 3 4 5
-# Default-Stop:      S 0 1 6
-# Short-Description: Example initscript
-# Description:       This file should be used to construct scripts to be
-#                    placed in /etc/init.d.
-### END INIT INFO
-
-# Author: Foo Bar <foobar@baz.org>
-#
-# Please remove the "Author" lines above and replace them
-# with your own name if you copy and modify this script.
-
-# Do NOT "set -e"
-
-# PATH should only include /usr/* if it runs after the mountnfs.sh script
-PATH=/usr/sbin:/usr/bin:/sbin:/bin
-DESC="Description of the service"
-NAME=daemonexecutablename
-DAEMON=/usr/sbin/$NAME
-DAEMON_ARGS="--options args"
-PIDFILE=/var/run/$NAME.pid
-SCRIPTNAME=/etc/init.d/$NAME
-
-# Exit if the package is not installed
-[ -x "$DAEMON" ] || exit 0
-
-# Read configuration variable file if it is present
-[ -r /etc/default/$NAME ] && . /etc/default/$NAME
-
-# Load the VERBOSE setting and other rcS variables
-[ -f /etc/default/rcS ] && . /etc/default/rcS
-
-# Define LSB log_* functions.
-# Depend on lsb-base (>= 3.0-6) to ensure that this file is present.
-. /lib/lsb/init-functions
-
-#
-# Function that starts the daemon/service
-#
-do_start()
-{
-       # Return
-       #   0 if daemon has been started
-       #   1 if daemon was already running
-       #   2 if daemon could not be started
-       start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON --test > /dev/null \
-               || return 1
-       start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON -- \
-               $DAEMON_ARGS \
-               || return 2
-       # Add code here, if necessary, that waits for the process to be ready
-       # to handle requests from services started subsequently which depend
-       # on this one.  As a last resort, sleep for some time.
-}
+class BupFs(fuse.Fuse):
+    def __init__(self, top):
+        fuse.Fuse.__init__(self)
+        self.top = top
+    
+    def getattr(self, path):
+        log('--getattr(%r)\n' % path)
+        try:
+            node = cache_get(self.top, path)
+            st = Stat()
+            st.st_mode = node.mode
+            st.st_nlink = node.nlinks()
+            st.st_size = node.size()
+            st.st_mtime = node.mtime
+            st.st_ctime = node.ctime
+            st.st_atime = node.atime
+            return st
+        except vfs.NoSuchFile:
+            return -errno.ENOENT
+
+    def readdir(self, path, offset):
+        log('--readdir(%r)\n' % path)
+        node = cache_get(self.top, path)
+        yield fuse.Direntry('.')
+        yield fuse.Direntry('..')
+        for sub in node.subs():
+            yield fuse.Direntry(sub.name)
+
+    def readlink(self, path):
+        log('--readlink(%r)\n' % path)
+        node = cache_get(self.top, path)
+        return node.readlink()
+
+    def open(self, path, flags):
+        log('--open(%r)\n' % path)
+        node = cache_get(self.top, path)
+        accmode = os.O_RDONLY | os.O_WRONLY | os.O_RDWR
+        if (flags & accmode) != os.O_RDONLY:
+            return -errno.EACCES
+        node.open()
+
+    def release(self, path, flags):
+        log('--release(%r)\n' % path)
+
+    def read(self, path, size, offset):
+        log('--read(%r)\n' % path)
+        n = cache_get(self.top, path)
+        o = n.open()
+        o.seek(offset)
+        return o.read(size)
+
+
+if not hasattr(fuse, '__version__'):
+    raise RuntimeError, "your fuse module is too old for fuse.__version__"
+fuse.fuse_python_api = (0, 2)
+
+
+optspec = """
+bup fuse [-d] [-f] <mountpoint>
+--
+d,debug   increase debug level
+f,foreground  run in foreground
+"""
+o = options.Options('bup fuse', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if len(extra) != 1:
+    o.fatal("exactly one argument expected")
+
+git.check_repo_or_die()
+top = vfs.RefList(None)
+f = BupFs(top)
+f.fuse_args.mountpoint = extra[0]
+if opt.debug:
+    f.fuse_args.add('debug')
+if opt.foreground:
+    f.fuse_args.setmod('foreground')
+print f.multithreaded
+f.multithreaded = False
+
+f.main()
+#!/usr/bin/env python
+from bup import git, options, client
+from bup.helpers import *
+
+optspec = """
+[BUP_DIR=...] bup init [-r host:path]
+--
+r,remote=  remote repository path
+"""
+o = options.Options('bup init', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if extra:
+    o.fatal("no arguments expected")
+
+
+if opt.remote:
+    git.init_repo()  # local repo
+    git.check_repo_or_die()
+    cli = client.Client(opt.remote, create=True)
+    cli.close()
+else:
+    git.init_repo()
+#!/usr/bin/env python
+import sys, math, struct, glob
+from bup import options, git
+from bup.helpers import *
+
+PAGE_SIZE=4096
+SHA_PER_PAGE=PAGE_SIZE/200.
+
+
+def merge(idxlist, bits, table):
+    count = 0
+    for e in git.idxmerge(idxlist):
+        count += 1
+        prefix = git.extract_bits(e, bits)
+        table[prefix] = count
+        yield e
+
+
+def do_midx(outdir, outfilename, infilenames):
+    if not outfilename:
+        assert(outdir)
+        sum = Sha1('\0'.join(infilenames)).hexdigest()
+        outfilename = '%s/midx-%s.midx' % (outdir, sum)
+    
+    inp = []
+    total = 0
+    for name in infilenames:
+        ix = git.PackIdx(name)
+        inp.append(ix)
+        total += len(ix)
+
+    log('Merging %d indexes (%d objects).\n' % (len(infilenames), total))
+    if (not opt.force and (total < 1024 and len(infilenames) < 3)) \
+       or (opt.force and not total):
+        log('midx: nothing to do.\n')
+        return
+
+    pages = int(total/SHA_PER_PAGE) or 1
+    bits = int(math.ceil(math.log(pages, 2)))
+    entries = 2**bits
+    log('Table size: %d (%d bits)\n' % (entries*4, bits))
+    
+    table = [0]*entries
+
+    try:
+        os.unlink(outfilename)
+    except OSError:
+        pass
+    f = open(outfilename + '.tmp', 'w+')
+    f.write('MIDX\0\0\0\2')
+    f.write(struct.pack('!I', bits))
+    assert(f.tell() == 12)
+    f.write('\0'*4*entries)
+    
+    for e in merge(inp, bits, table):
+        f.write(e)
+        
+    f.write('\0'.join(os.path.basename(p) for p in infilenames))
+
+    f.seek(12)
+    f.write(struct.pack('!%dI' % entries, *table))
+    f.close()
+    os.rename(outfilename + '.tmp', outfilename)
+
+    # this is just for testing
+    if 0:
+        p = git.PackMidx(outfilename)
+        assert(len(p.idxnames) == len(infilenames))
+        print p.idxnames
+        assert(len(p) == total)
+        pi = iter(p)
+        for i in merge(inp, total, bits, table):
+            assert(i == pi.next())
+            assert(p.exists(i))
+
+    print outfilename
+
+optspec = """
+bup midx [options...] <idxnames...>
+--
+o,output=  output midx filename (default: auto-generated)
+a,auto     automatically create .midx from any unindexed .idx files
+f,force    automatically create .midx from *all* .idx files
+"""
+o = options.Options('bup midx', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if extra and (opt.auto or opt.force):
+    o.fatal("you can't use -f/-a and also provide filenames")
+
+git.check_repo_or_die()
+
+if extra:
+    do_midx(git.repo('objects/pack'), opt.output, extra)
+elif opt.auto or opt.force:
+    paths = [git.repo('objects/pack')]
+    paths += glob.glob(git.repo('index-cache/*/.'))
+    for path in paths:
+        log('midx: scanning %s\n' % path)
+        if opt.force:
+            do_midx(path, opt.output, glob.glob('%s/*.idx' % path))
+        elif opt.auto:
+            m = git.PackIdxList(path)
+            needed = {}
+            for pack in m.packs:  # only .idx files without a .midx are open
+                if pack.name.endswith('.idx'):
+                    needed[pack.name] = 1
+            del m
+            do_midx(path, opt.output, needed.keys())
+        log('\n')
+else:
+    o.fatal("you must use -f or -a or provide input filenames")
+#!/usr/bin/env python
+import sys, os, random
+from bup import options
+from bup.helpers import *
+
+
+def randblock(n):
+    l = []
+    for i in xrange(n):
+        l.append(chr(random.randrange(0,256)))
+    return ''.join(l)
+
+
+optspec = """
+bup damage [-n count] [-s maxsize] [-S seed] <filenames...>
+--
+   WARNING: THIS COMMAND IS EXTREMELY DANGEROUS
+n,num=   number of blocks to damage
+s,size=  maximum size of each damaged block
+percent= maximum size of each damaged block (as a percent of entire file)
+equal    spread damage evenly throughout the file
+S,seed=  random number seed (for repeatable tests)
+"""
+o = options.Options('bup damage', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if not extra:
+    o.fatal('filenames expected')
+
+if opt.seed != None:
+    random.seed(opt.seed)
+
+for name in extra:
+    log('Damaging "%s"...\n' % name)
+    f = open(name, 'r+b')
+    st = os.fstat(f.fileno())
+    size = st.st_size
+    if opt.percent or opt.size:
+        ms1 = int(float(opt.percent or 0)/100.0*size) or size
+        ms2 = opt.size or size
+        maxsize = min(ms1, ms2)
+    else:
+        maxsize = 1
+    chunks = opt.num or 10
+    chunksize = size/chunks
+    for r in range(chunks):
+        sz = random.randrange(1, maxsize+1)
+        if sz > size:
+            sz = size
+        if opt.equal:
+            ofs = r*chunksize
+        else:
+            ofs = random.randrange(0, size - sz + 1)
+        log('  %6d bytes at %d\n' % (sz, ofs))
+        f.seek(ofs)
+        f.write(randblock(sz))
+    f.close()
+#!/usr/bin/env python
+import sys, struct, mmap
+from bup import options, git
+from bup.helpers import *
+
+suspended_w = None
+
+
+def init_dir(conn, arg):
+    git.init_repo(arg)
+    log('bup server: bupdir initialized: %r\n' % git.repodir)
+    conn.ok()
+
+
+def set_dir(conn, arg):
+    git.check_repo_or_die(arg)
+    log('bup server: bupdir is %r\n' % git.repodir)
+    conn.ok()
 
-#
-# Function that stops the daemon/service
-#
-do_stop()
-{
-       # Return
-       #   0 if daemon has been stopped
-       #   1 if daemon was already stopped
-       #   2 if daemon could not be stopped
-       #   other if a failure occurred
-       start-stop-daemon --stop --quiet --retry=TERM/30/KILL/5 --pidfile $PIDFILE --name $NAME
-       RETVAL="$?"
-       [ "$RETVAL" = 2 ] && return 2
-       # Wait for children to finish too if this is a daemon that forks
-       # and if the daemon is only ever run from this initscript.
-       # If the above conditions are not satisfied then add some other code
-       # that waits for the process to drop all resources that could be
-       # needed by services started subsequently.  A last resort is to
-       # sleep for some time.
-       start-stop-daemon --stop --quiet --oknodo --retry=0/30/KILL/5 --exec $DAEMON
-       [ "$?" = 2 ] && return 2
-       # Many daemons don't delete their pidfiles when they exit.
-       rm -f $PIDFILE
-       return "$RETVAL"
+    
+def list_indexes(conn, junk):
+    git.check_repo_or_die()
+    for f in os.listdir(git.repo('objects/pack')):
+        if f.endswith('.idx'):
+            conn.write('%s\n' % f)
+    conn.ok()
+
+
+def send_index(conn, name):
+    git.check_repo_or_die()
+    assert(name.find('/') < 0)
+    assert(name.endswith('.idx'))
+    idx = git.PackIdx(git.repo('objects/pack/%s' % name))
+    conn.write(struct.pack('!I', len(idx.map)))
+    conn.write(idx.map)
+    conn.ok()
+
+
+def receive_objects(conn, junk):
+    global suspended_w
+    git.check_repo_or_die()
+    suggested = {}
+    if suspended_w:
+        w = suspended_w
+        suspended_w = None
+    else:
+        w = git.PackWriter()
+    while 1:
+        ns = conn.read(4)
+        if not ns:
+            w.abort()
+            raise Exception('object read: expected length header, got EOF\n')
+        n = struct.unpack('!I', ns)[0]
+        #log('expecting %d bytes\n' % n)
+        if not n:
+            log('bup server: received %d object%s.\n' 
+                % (w.count, w.count!=1 and "s" or ''))
+            fullpath = w.close()
+            if fullpath:
+                (dir, name) = os.path.split(fullpath)
+                conn.write('%s.idx\n' % name)
+            conn.ok()
+            return
+        elif n == 0xffffffff:
+            log('bup server: receive-objects suspended.\n')
+            suspended_w = w
+            conn.ok()
+            return
+            
+        buf = conn.read(n)  # object sizes in bup are reasonably small
+        #log('read %d bytes\n' % n)
+        if len(buf) < n:
+            w.abort()
+            raise Exception('object read: expected %d bytes, got %d\n'
+                            % (n, len(buf)))
+        (type, content) = git._decode_packobj(buf)
+        sha = git.calc_hash(type, content)
+        oldpack = w.exists(sha)
+        # FIXME: we only suggest a single index per cycle, because the client
+        # is currently dumb to download more than one per cycle anyway.
+        # Actually we should fix the client, but this is a minor optimization
+        # on the server side.
+        if not suggested and \
+          oldpack and (oldpack == True or oldpack.endswith('.midx')):
+            # FIXME: we shouldn't really have to know about midx files
+            # at this layer.  But exists() on a midx doesn't return the
+            # packname (since it doesn't know)... probably we should just
+            # fix that deficiency of midx files eventually, although it'll
+            # make the files bigger.  This method is certainly not very
+            # efficient.
+            w.objcache.refresh(skip_midx = True)
+            oldpack = w.objcache.exists(sha)
+            log('new suggestion: %r\n' % oldpack)
+            assert(oldpack)
+            assert(oldpack != True)
+            assert(not oldpack.endswith('.midx'))
+            w.objcache.refresh(skip_midx = False)
+        if not suggested and oldpack:
+            assert(oldpack.endswith('.idx'))
+            (dir,name) = os.path.split(oldpack)
+            if not (name in suggested):
+                log("bup server: suggesting index %s\n" % name)
+                conn.write('index %s\n' % name)
+                suggested[name] = 1
+        else:
+            w._raw_write([buf])
+    # NOTREACHED
+
+
+def read_ref(conn, refname):
+    git.check_repo_or_die()
+    r = git.read_ref(refname)
+    conn.write('%s\n' % (r or '').encode('hex'))
+    conn.ok()
+
+
+def update_ref(conn, refname):
+    git.check_repo_or_die()
+    newval = conn.readline().strip()
+    oldval = conn.readline().strip()
+    git.update_ref(refname, newval.decode('hex'), oldval.decode('hex'))
+    conn.ok()
+
+
+def cat(conn, id):
+    git.check_repo_or_die()
+    try:
+        for blob in git.cat(id):
+            conn.write(struct.pack('!I', len(blob)))
+            conn.write(blob)
+    except KeyError, e:
+        log('server: error: %s\n' % e)
+        conn.write('\0\0\0\0')
+        conn.error(e)
+    else:
+        conn.write('\0\0\0\0')
+        conn.ok()
+
+
+optspec = """
+bup server
+"""
+o = options.Options('bup server', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if extra:
+    o.fatal('no arguments expected')
+
+log('bup server: reading from stdin.\n')
+
+commands = {
+    'init-dir': init_dir,
+    'set-dir': set_dir,
+    'list-indexes': list_indexes,
+    'send-index': send_index,
+    'receive-objects': receive_objects,
+    'read-ref': read_ref,
+    'update-ref': update_ref,
+    'cat': cat,
 }
 
+# FIXME: this protocol is totally lame and not at all future-proof.
+# (Especially since we abort completely as soon as *anything* bad happens)
+conn = Conn(sys.stdin, sys.stdout)
+lr = linereader(conn)
+for _line in lr:
+    line = _line.strip()
+    if not line:
+        continue
+    log('bup server: command: %r\n' % line)
+    words = line.split(' ', 1)
+    cmd = words[0]
+    rest = len(words)>1 and words[1] or ''
+    if cmd == 'quit':
+        break
+    else:
+        cmd = commands.get(cmd)
+        if cmd:
+            cmd(conn, rest)
+        else:
+            raise Exception('unknown server command: %r\n' % line)
+
+log('bup server: done\n')
+#!/usr/bin/env python
+import sys, time, struct
+from bup import hashsplit, git, options, client
+from bup.helpers import *
+from subprocess import PIPE
+
+
+optspec = """
+bup join [-r host:path] [refs or hashes...]
+--
+r,remote=  remote repository path
+"""
+o = options.Options('bup join', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+git.check_repo_or_die()
+
+if not extra:
+    extra = linereader(sys.stdin)
+
+ret = 0
+
+if opt.remote:
+    cli = client.Client(opt.remote)
+    cat = cli.cat
+else:
+    cp = git.CatPipe()
+    cat = cp.join
+
+for id in extra:
+    try:
+        for blob in cat(id):
+            sys.stdout.write(blob)
+    except KeyError, e:
+        sys.stdout.flush()
+        log('error: %s\n' % e)
+        ret = 1
+
+sys.exit(ret)
+#!/usr/bin/env python
+import sys, re, errno, stat, time, math
+from bup import hashsplit, git, options, index, client
+from bup.helpers import *
+
+
+optspec = """
+bup save [-tc] [-n name] <filenames...>
+--
+r,remote=  remote repository path
+t,tree     output a tree id
+c,commit   output a commit id
+n,name=    name of backup set to update (if any)
+v,verbose  increase log output (can be used more than once)
+q,quiet    don't show progress meter
+smaller=   only back up files smaller than n bytes
+"""
+o = options.Options('bup save', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+git.check_repo_or_die()
+if not (opt.tree or opt.commit or opt.name):
+    o.fatal("use one or more of -t, -c, -n")
+if not extra:
+    o.fatal("no filenames given")
+
+opt.progress = (istty and not opt.quiet)
+opt.smaller = parse_num(opt.smaller or 0)
+
+is_reverse = os.environ.get('BUP_SERVER_REVERSE')
+if is_reverse and opt.remote:
+    o.fatal("don't use -r in reverse mode; it's automatic")
+
+refname = opt.name and 'refs/heads/%s' % opt.name or None
+if opt.remote or is_reverse:
+    cli = client.Client(opt.remote)
+    oldref = refname and cli.read_ref(refname) or None
+    w = cli.new_packwriter()
+else:
+    cli = None
+    oldref = refname and git.read_ref(refname) or None
+    w = git.PackWriter()
+
+handle_ctrl_c()
+
+
+def eatslash(dir):
+    if dir.endswith('/'):
+        return dir[:-1]
+    else:
+        return dir
+
+
+parts = ['']
+shalists = [[]]
+
+def _push(part):
+    assert(part)
+    parts.append(part)
+    shalists.append([])
+
+def _pop(force_tree):
+    assert(len(parts) >= 1)
+    part = parts.pop()
+    shalist = shalists.pop()
+    tree = force_tree or w.new_tree(shalist)
+    if shalists:
+        shalists[-1].append(('40000', part, tree))
+    else:  # this was the toplevel, so put it back for sanity
+        shalists.append(shalist)
+    return tree
+
+lastremain = None
+def progress_report(n):
+    global count, subcount, lastremain
+    subcount += n
+    cc = count + subcount
+    pct = total and (cc*100.0/total) or 0
+    now = time.time()
+    elapsed = now - tstart
+    kps = elapsed and int(cc/1024./elapsed)
+    kps_frac = 10 ** int(math.log(kps+1, 10) - 1)
+    kps = int(kps/kps_frac)*kps_frac
+    if cc:
+        remain = elapsed*1.0/cc * (total-cc)
+    else:
+        remain = 0.0
+    if (lastremain and (remain > lastremain)
+          and ((remain - lastremain)/lastremain < 0.05)):
+        remain = lastremain
+    else:
+        lastremain = remain
+    hours = int(remain/60/60)
+    mins = int(remain/60 - hours*60)
+    secs = int(remain - hours*60*60 - mins*60)
+    if elapsed < 30:
+        remainstr = ''
+        kpsstr = ''
+    else:
+        kpsstr = '%dk/s' % kps
+        if hours:
+            remainstr = '%dh%dm' % (hours, mins)
+        elif mins:
+            remainstr = '%dm%d' % (mins, secs)
+        else:
+            remainstr = '%ds' % secs
+    progress('Saving: %.2f%% (%d/%dk, %d/%d files) %s %s\r'
+             % (pct, cc/1024, total/1024, fcount, ftotal,
+                remainstr, kpsstr))
+
+
+r = index.Reader(git.repo('bupindex'))
+
+def already_saved(ent):
+    return ent.is_valid() and w.exists(ent.sha) and ent.sha
+
+def wantrecurse_pre(ent):
+    return not already_saved(ent)
+
+def wantrecurse_during(ent):
+    return not already_saved(ent) or ent.sha_missing()
+
+total = ftotal = 0
+if opt.progress:
+    for (transname,ent) in r.filter(extra, wantrecurse=wantrecurse_pre):
+        if not (ftotal % 10024):
+            progress('Reading index: %d\r' % ftotal)
+        exists = ent.exists()
+        hashvalid = already_saved(ent)
+        ent.set_sha_missing(not hashvalid)
+        if not opt.smaller or ent.size < opt.smaller:
+            if exists and not hashvalid:
+                total += ent.size
+        ftotal += 1
+    progress('Reading index: %d, done.\n' % ftotal)
+    hashsplit.progress_callback = progress_report
+
+tstart = time.time()
+count = subcount = fcount = 0
+lastskip_name = None
+lastdir = ''
+for (transname,ent) in r.filter(extra, wantrecurse=wantrecurse_during):
+    (dir, file) = os.path.split(ent.name)
+    exists = (ent.flags & index.IX_EXISTS)
+    hashvalid = already_saved(ent)
+    wasmissing = ent.sha_missing()
+    oldsize = ent.size
+    if opt.verbose:
+        if not exists:
+            status = 'D'
+        elif not hashvalid:
+            if ent.sha == index.EMPTY_SHA:
+                status = 'A'
+            else:
+                status = 'M'
+        else:
+            status = ' '
+        if opt.verbose >= 2:
+            log('%s %-70s\n' % (status, ent.name))
+        elif not stat.S_ISDIR(ent.mode) and lastdir != dir:
+            if not lastdir.startswith(dir):
+                log('%s %-70s\n' % (status, os.path.join(dir, '')))
+            lastdir = dir
+
+    if opt.progress:
+        progress_report(0)
+    fcount += 1
+    
+    if not exists:
+        continue
+    if opt.smaller and ent.size >= opt.smaller:
+        if exists and not hashvalid:
+            add_error('skipping large file "%s"' % ent.name)
+            lastskip_name = ent.name
+        continue
+
+    assert(dir.startswith('/'))
+    dirp = dir.split('/')
+    while parts > dirp:
+        _pop(force_tree = None)
+    if dir != '/':
+        for part in dirp[len(parts):]:
+            _push(part)
+
+    if not file:
+        # no filename portion means this is a subdir.  But
+        # sub/parentdirectories already handled in the pop/push() part above.
+        oldtree = already_saved(ent) # may be None
+        newtree = _pop(force_tree = oldtree)
+        if not oldtree:
+            if lastskip_name and lastskip_name.startswith(ent.name):
+                ent.invalidate()
+            else:
+                ent.validate(040000, newtree)
+            ent.repack()
+        if exists and wasmissing:
+            count += oldsize
+        continue
+
+    # it's not a directory
+    id = None
+    if hashvalid:
+        mode = '%o' % ent.gitmode
+        id = ent.sha
+        shalists[-1].append((mode, 
+                             git.mangle_name(file, ent.mode, ent.gitmode),
+                             id))
+    else:
+        if stat.S_ISREG(ent.mode):
+            try:
+                f = hashsplit.open_noatime(ent.name)
+            except IOError, e:
+                add_error(e)
+                lastskip_name = ent.name
+            except OSError, e:
+                add_error(e)
+                lastskip_name = ent.name
+            else:
+                (mode, id) = hashsplit.split_to_blob_or_tree(w, [f])
+        else:
+            if stat.S_ISDIR(ent.mode):
+                assert(0)  # handled above
+            elif stat.S_ISLNK(ent.mode):
+                try:
+                    rl = os.readlink(ent.name)
+                except OSError, e:
+                    add_error(e)
+                    lastskip_name = ent.name
+                except IOError, e:
+                    add_error(e)
+                    lastskip_name = ent.name
+                else:
+                    (mode, id) = ('120000', w.new_blob(rl))
+            else:
+                add_error(Exception('skipping special file "%s"' % ent.name))
+                lastskip_name = ent.name
+        if id:
+            ent.validate(int(mode, 8), id)
+            ent.repack()
+            shalists[-1].append((mode,
+                                 git.mangle_name(file, ent.mode, ent.gitmode),
+                                 id))
+    if exists and wasmissing:
+        count += oldsize
+        subcount = 0
+
+
+if opt.progress:
+    pct = total and count*100.0/total or 100
+    progress('Saving: %.2f%% (%d/%dk, %d/%d files), done.    \n'
+             % (pct, count/1024, total/1024, fcount, ftotal))
+
+while len(parts) > 1:
+    _pop(force_tree = None)
+assert(len(shalists) == 1)
+tree = w.new_tree(shalists[-1])
+if opt.tree:
+    print tree.encode('hex')
+if opt.commit or opt.name:
+    msg = 'bup save\n\nGenerated by command:\n%r' % sys.argv
+    ref = opt.name and ('refs/heads/%s' % opt.name) or None
+    commit = w.new_commit(oldref, tree, msg)
+    if opt.commit:
+        print commit.encode('hex')
+
+w.close()  # must close before we can update the ref
+        
+if opt.name:
+    if cli:
+        cli.update_ref(refname, commit, oldref)
+    else:
+        git.update_ref(refname, commit, oldref)
+
+if cli:
+    cli.close()
+
+if saved_errors:
+    log('WARNING: %d errors encountered while saving.\n' % len(saved_errors))
+    sys.exit(1)
+#!/usr/bin/env python
+import sys, time
+from bup import options
+
+optspec = """
+bup tick
+"""
+o = options.Options('bup tick', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if extra:
+    o.fatal("no arguments expected")
+
+t = time.time()
+tleft = 1 - (t - int(t))
+time.sleep(tleft)
+#!/usr/bin/env python
+import os, sys, stat, time
+from bup import options, git, index, drecurse
+from bup.helpers import *
+
+
+def merge_indexes(out, r1, r2):
+    for e in index.MergeIter([r1, r2]):
+        # FIXME: shouldn't we remove deleted entries eventually?  When?
+        out.add_ixentry(e)
+
+
+class IterHelper:
+    def __init__(self, l):
+        self.i = iter(l)
+        self.cur = None
+        self.next()
+
+    def next(self):
+        try:
+            self.cur = self.i.next()
+        except StopIteration:
+            self.cur = None
+        return self.cur
+
+
+def check_index(reader):
+    try:
+        log('check: checking forward iteration...\n')
+        e = None
+        d = {}
+        for e in reader.forward_iter():
+            if e.children_n:
+                if opt.verbose:
+                    log('%08x+%-4d %r\n' % (e.children_ofs, e.children_n,
+                                            e.name))
+                assert(e.children_ofs)
+                assert(e.name.endswith('/'))
+                assert(not d.get(e.children_ofs))
+                d[e.children_ofs] = 1
+            if e.flags & index.IX_HASHVALID:
+                assert(e.sha != index.EMPTY_SHA)
+                assert(e.gitmode)
+        assert(not e or e.name == '/')  # last entry is *always* /
+        log('check: checking normal iteration...\n')
+        last = None
+        for e in reader:
+            if last:
+                assert(last > e.name)
+            last = e.name
+    except:
+        log('index error! at %r\n' % e)
+        raise
+    log('check: passed.\n')
+
+
+def update_index(top):
+    ri = index.Reader(indexfile)
+    wi = index.Writer(indexfile)
+    rig = IterHelper(ri.iter(name=top))
+    tstart = int(time.time())
+
+    hashgen = None
+    if opt.fake_valid:
+        def hashgen(name):
+            return (0100644, index.FAKE_SHA)
+
+    total = 0
+    for (path,pst) in drecurse.recursive_dirlist([top], xdev=opt.xdev):
+        if opt.verbose>=2 or (opt.verbose==1 and stat.S_ISDIR(pst.st_mode)):
+            sys.stdout.write('%s\n' % path)
+            sys.stdout.flush()
+            progress('Indexing: %d\r' % total)
+        elif not (total % 128):
+            progress('Indexing: %d\r' % total)
+        total += 1
+        while rig.cur and rig.cur.name > path:  # deleted paths
+            if rig.cur.exists():
+                rig.cur.set_deleted()
+                rig.cur.repack()
+            rig.next()
+        if rig.cur and rig.cur.name == path:    # paths that already existed
+            if pst:
+                rig.cur.from_stat(pst, tstart)
+            if not (rig.cur.flags & index.IX_HASHVALID):
+                if hashgen:
+                    (rig.cur.gitmode, rig.cur.sha) = hashgen(path)
+                    rig.cur.flags |= index.IX_HASHVALID
+            if opt.fake_invalid:
+                rig.cur.invalidate()
+            rig.cur.repack()
+            rig.next()
+        else:  # new paths
+            wi.add(path, pst, hashgen = hashgen)
+    progress('Indexing: %d, done.\n' % total)
+    
+    if ri.exists():
+        ri.save()
+        wi.flush()
+        if wi.count:
+            wr = wi.new_reader()
+            if opt.check:
+                log('check: before merging: oldfile\n')
+                check_index(ri)
+                log('check: before merging: newfile\n')
+                check_index(wr)
+            mi = index.Writer(indexfile)
+            merge_indexes(mi, ri, wr)
+            ri.close()
+            mi.close()
+            wr.close()
+        wi.abort()
+    else:
+        wi.close()
+
+
+optspec = """
+bup index <-p|m|u> [options...] <filenames...>
+--
+p,print    print the index entries for the given names (also works with -u)
+m,modified print only added/deleted/modified files (implies -p)
+s,status   print each filename with a status char (A/M/D) (implies -p)
+H,hash     print the hash for each object next to its name (implies -p)
+l,long     print more information about each file
+u,update   (recursively) update the index entries for the given filenames
+x,xdev,one-file-system  don't cross filesystem boundaries
+fake-valid mark all index entries as up-to-date even if they aren't
+fake-invalid mark all index entries as invalid
+check      carefully check index file integrity
+f,indexfile=  the name of the index file (default 'index')
+v,verbose  increase log output (can be used more than once)
+"""
+o = options.Options('bup index', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if not (opt.modified or opt['print'] or opt.status or opt.update or opt.check):
+    o.fatal('supply one or more of -p, -s, -m, -u, or --check')
+if (opt.fake_valid or opt.fake_invalid) and not opt.update:
+    o.fatal('--fake-{in,}valid are meaningless without -u')
+if opt.fake_valid and opt.fake_invalid:
+    o.fatal('--fake-valid is incompatible with --fake-invalid')
+
+git.check_repo_or_die()
+indexfile = opt.indexfile or git.repo('bupindex')
+
+handle_ctrl_c()
+
+if opt.check:
+    log('check: starting initial check.\n')
+    check_index(index.Reader(indexfile))
+
+paths = index.reduce_paths(extra)
+
+if opt.update:
+    if not paths:
+        o.fatal('update (-u) requested but no paths given')
+    for (rp,path) in paths:
+        update_index(rp)
+
+if opt['print'] or opt.status or opt.modified:
+    for (name, ent) in index.Reader(indexfile).filter(extra or ['']):
+        if (opt.modified 
+            and (ent.is_valid() or ent.is_deleted() or not ent.mode)):
+            continue
+        line = ''
+        if opt.status:
+            if ent.is_deleted():
+                line += 'D '
+            elif not ent.is_valid():
+                if ent.sha == index.EMPTY_SHA:
+                    line += 'A '
+                else:
+                    line += 'M '
+            else:
+                line += '  '
+        if opt.hash:
+            line += ent.sha.encode('hex') + ' '
+        if opt.long:
+            line += "%7s %7s " % (oct(ent.mode), oct(ent.gitmode))
+        print line + (name or './')
+
+if opt.check and (opt['print'] or opt.status or opt.modified or opt.update):
+    log('check: starting final check.\n')
+    check_index(index.Reader(indexfile))
+
+if saved_errors:
+    log('WARNING: %d errors encountered.\n' % len(saved_errors))
+    sys.exit(1)
+#!/usr/bin/env python
+import sys, os, struct
+from bup import options, helpers
+
+optspec = """
+bup rbackup-server
+--
+    This command is not intended to be run manually.
+"""
+o = options.Options('bup rbackup-server', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+if extra:
+    o.fatal('no arguments expected')
+
+# get the subcommand's argv.
+# Normally we could just pass this on the command line, but since we'll often
+# be getting called on the other end of an ssh pipe, which tends to mangle
+# argv (by sending it via the shell), this way is much safer.
+buf = sys.stdin.read(4)
+sz = struct.unpack('!I', buf)[0]
+assert(sz > 0)
+assert(sz < 1000000)
+buf = sys.stdin.read(sz)
+assert(len(buf) == sz)
+argv = buf.split('\0')
+
+# stdin/stdout are supposedly connected to 'bup server' that the caller
+# started for us (often on the other end of an ssh tunnel), so we don't want
+# to misuse them.  Move them out of the way, then replace stdout with
+# a pointer to stderr in case our subcommand wants to do something with it.
 #
-# Function that sends a SIGHUP to the daemon/service
+# It might be nice to do the same with stdin, but my experiments showed that
+# ssh seems to make its child's stderr a readable-but-never-reads-anything
+# socket.  They really should have used shutdown(SHUT_WR) on the other end
+# of it, but probably didn't.  Anyway, it's too messy, so let's just make sure
+# anyone reading from stdin is disappointed.
 #
-do_reload() {
-       #
-       # If the daemon can reload its configuration without
-       # restarting (for example, when it is sent a SIGHUP),
-       # then implement that here.
-       #
-       start-stop-daemon --stop --signal 1 --quiet --pidfile $PIDFILE --name $NAME
-       return 0
-}
-
-case "$1" in
-  start)
-       [ "$VERBOSE" != no ] && log_daemon_msg "Starting $DESC" "$NAME"
-       do_start
-       case "$?" in
-               0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
-               2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
-       esac
-       ;;
-  stop)
-       [ "$VERBOSE" != no ] && log_daemon_msg "Stopping $DESC" "$NAME"
-       do_stop
-       case "$?" in
-               0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
-               2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
-       esac
-       ;;
-  #reload|force-reload)
-       #
-       # If do_reload() is not implemented then leave this commented out
-       # and leave 'force-reload' as an alias for 'restart'.
-       #
-       #log_daemon_msg "Reloading $DESC" "$NAME"
-       #do_reload
-       #log_end_msg $?
-       #;;
-  restart|force-reload)
-       #
-       # If the "reload" option is implemented then remove the
-       # 'force-reload' alias
-       #
-       log_daemon_msg "Restarting $DESC" "$NAME"
-       do_stop
-       case "$?" in
-         0|1)
-               do_start
-               case "$?" in
-                       0) log_end_msg 0 ;;
-                       1) log_end_msg 1 ;; # Old process is still running
-                       *) log_end_msg 1 ;; # Failed to start
-               esac
-               ;;
-         *)
-               # Failed to stop
-               log_end_msg 1
-               ;;
-       esac
-       ;;
-  *)
-       #echo "Usage: $SCRIPTNAME {start|stop|restart|reload|force-reload}" >&2
-       echo "Usage: $SCRIPTNAME {start|stop|restart|force-reload}" >&2
-       exit 3
-       ;;
-esac
-
-:
-#! /bin/sh
-
-### BEGIN INIT INFO
-# Provides:            sshd
-# Required-Start:      $network $local_fs $remote_fs
-# Required-Stop:
-# Default-Start:       2 3 4 5
-# Default-Stop:                0 1 6
-# Short-Description:   OpenBSD Secure Shell server
-### END INIT INFO
-
-set -e
-
-# /etc/init.d/ssh: start and stop the OpenBSD "secure shell(tm)" daemon
-
-test -x /usr/sbin/sshd || exit 0
-( /usr/sbin/sshd -\? 2>&1 | grep -q OpenSSH ) 2>/dev/null || exit 0
-
-SSHD_OOM_ADJUST=-17
-if test -f /etc/default/ssh; then
-    . /etc/default/ssh
-fi
-
-. /lib/lsb/init-functions
-
-if [ -n "$2" ]; then
-    SSHD_OPTS="$SSHD_OPTS $2"
-fi
-
-# Are we running from init?
-run_by_init() {
-    ([ "$previous" ] && [ "$runlevel" ]) || [ "$runlevel" = S ]
-}
-
-check_for_no_start() {
-    # forget it if we're trying to start, and /etc/ssh/sshd_not_to_be_run exists
-    if [ -e /etc/ssh/sshd_not_to_be_run ]; then 
-       if [ "$1" = log_end_msg ]; then
-           log_end_msg 0
-       fi
-       if ! run_by_init; then
-           log_action_msg "OpenBSD Secure Shell server not in use (/etc/ssh/sshd_not_to_be_run)"
-       fi
-       exit 0
-    fi
-}
-
-check_dev_null() {
-    if [ ! -c /dev/null ]; then
-       if [ "$1" = log_end_msg ]; then
-           log_end_msg 1 || true
-       fi
-       if ! run_by_init; then
-           log_action_msg "/dev/null is not a character device!"
-       fi
-       exit 1
-    fi
-}
-
-check_privsep_dir() {
-    # Create the PrivSep empty dir if necessary
-    if [ ! -d /var/run/sshd ]; then
-       mkdir /var/run/sshd
-       chmod 0755 /var/run/sshd
-    fi
-}
-
-check_config() {
-    if [ ! -e /etc/ssh/sshd_not_to_be_run ]; then
-       /usr/sbin/sshd -t || exit 1
-    fi
-}
+# (You can't just leave stdin/stdout "not open" by closing the file
+# descriptors.  Then the next file that opens is automatically assigned 0 or 1,
+# and people *trying* to read/write stdin/stdout get screwed.)
+os.dup2(0, 3)
+os.dup2(1, 4)
+os.dup2(2, 1)
+in approximately the same placeRDONLY)
+and distrib-0)
+ution as(fd)
+
+in the original test filesERSE'] = helpers.hostname()
+os.execvp(argv[0], argv)
+sys.exit(99)
+#!/usr/bin/env python
+import sys, os, glob, subprocess, time
+from bup import options, git
+from bup.helpers import *
+
+par2_ok = 0
+nullf = open('/dev/null')
+
+def debug(s):
+    if opt.verbose:
+        log(s)
+
+def run(argv):
+    # at least in python 2.5, using "stdout=2" or "stdout=sys.stderr" below
+    # doesn't actually work, because subprocess closes fd #2 right before
+    # execing for some reason.  So we work around it by duplicating the fd
+    # first.
+    fd = os.dup(2)  # copy stderr
+    try:
+        p = subprocess.Popen(argv, stdout=fd, close_fds=False)
+        return p.wait()
+    finally:
+        os.close(fd)
+
+def par2_setup():
+    global par2_ok
+    rv = 1
+    try:
+        p = subprocess.Popen(['par2', '--help'],
+                             stdout=nullf, stderr=nullf, stdin=nullf)
+        rv = p.wait()
+    except OSError:
+        log('fsck: warning: par2 not found; disabling recovery features.\n')
+    else:
+        par2_ok = 1
+
+def parv(lvl):
+    if opt.verbose >= lvl:
+        if istty:
+            return []
+        else:
+            return ['-q']
+    else:
+        return ['-qq']
+
+def par2_generate(base):
+    return run(['par2', 'create', '-n1', '-c200'] + parv(2)
+               + ['--', base, base+'.pack', base+'.idx'])
+
+def par2_verify(base):
+    return run(['par2', 'verify'] + parv(3) + ['--', base])
+
+def par2_repair(base):
+    return run(['par2', 'repair'] + parv(2) + ['--', base])
+
+def quick_verify(base):
+    f = open(base + '.pack', 'rb')
+    f.seek(-20, 2)
+    wantsum = f.read(20)
+    assert(len(wantsum) == 20)
+    f.seek(0)
+    sum = Sha1()
+    for b in chunkyreader(f, os.fstat(f.fileno()).st_size - 20):
+        sum.update(b)
+    if sum.digest() != wantsum:
+        raise ValueError('expected %r, got %r' % (wantsum.encode('hex'),
+                                                  sum.hexdigest()))
+        
 
-adjust_oom() {
-    if [ -e /var/run/sshd.pid ]; then
-       PID="$(head -n1 /var/run/sshd.pid)"
-       if [ -e "/proc/$PID/oom_adj" ]; then
-           printf '%s' "$SSHD_OOM_ADJUST" >"/proc/$PID/oom_adj" || true
-       fi
-    fi
-}
+def git_verify(base):
+    if opt.quick:
+        try:
+            quick_verify(base)
+        except Exception, e:
+            debug('error: %s\n' % e)
+            return 1
+        return 0
+    else:
+        return run(['git', 'verify-pack', '--', base])
+    
+    
+def do_pack(base, last):
+    code = 0
+    if par2_ok and par2_exists and (opt.repair or not opt.generate):
+        vresult = par2_verify(base)
+        if vresult != 0:
+            if opt.repair:
+                rresult = par2_repair(base)
+                if rresult != 0:
+                    print '%s par2 repair: failed (%d)' % (last, rresult)
+                    code = rresult
+                else:
+                    print '%s par2 repair: succeeded (0)' % last
+                    code = 100
+            else:
+                print '%s par2 verify: failed (%d)' % (last, vresult)
+                code = vresult
+        else:
+            print '%s ok' % last
+    elif not opt.generate or (par2_ok and not par2_exists):
+        gresult = git_verify(base)
+        if gresult != 0:
+            print '%s git verify: failed (%d)' % (last, gresult)
+            code = gresult
+        else:
+            if par2_ok and opt.generate:
+                presult = par2_generate(base)
+                if presult != 0:
+                    print '%s par2 create: failed (%d)' % (last, presult)
+                    code = presult
+                else:
+                    print '%s ok' % last
+            else:
+                print '%s ok' % last
+    else:
+        assert(opt.generate and (not par2_ok or par2_exists))
+        debug('    skipped: par2 file already generated.\n')
+    return code
+
+
+optspec = """
+bup fsck [options...] [filenames...]
+--
+r,repair    attempt to repair errors using par2 (dangerous!)
+g,generate  generate auto-repair information using par2
+v,verbose   increase verbosity (can be used more than once)
+quick       just check pack sha1sum, don't use git verify-pack
+j,jobs=     run 'n' jobs in parallel
+par2-ok     immediately return 0 if par2 is ok, 1 if not
+disable-par2  ignore par2 even if it is available
+"""
+o = options.Options('bup fsck', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+par2_setup()
+if opt.par2_ok:
+    if par2_ok:
+        sys.exit(0)  # 'true' in sh
+    else:
+        sys.exit(1)
+if opt.disable_par2:
+    par2_ok = 0
+
+git.check_repo_or_die()
+
+if not extra:
+    debug('fsck: No filenames given: checking all packs.\n')
+    extra = glob.glob(git.repo('objects/pack/*.pack'))
+
+code = 0
+count = 0
+outstanding = {}
+for name in extra:
+    if name.endswith('.pack'):
+        base = name[:-5]
+    elif name.endswith('.idx'):
+        base = name[:-4]
+    elif name.endswith('.par2'):
+        base = name[:-5]
+    elif os.path.exists(name + '.pack'):
+        base = name
+    else:
+        raise Exception('%s is not a pack file!' % name)
+    (dir,last) = os.path.split(base)
+    par2_exists = os.path.exists(base + '.par2')
+    if par2_exists and os.stat(base + '.par2').st_size == 0:
+        par2_exists = 0
+    sys.stdout.flush()
+    debug('fsck: checking %s (%s)\n' 
+          % (last, par2_ok and par2_exists and 'par2' or 'git'))
+    if not opt.verbose:
+        progress('fsck (%d/%d)\r' % (count, len(extra)))
+    
+    if not opt.jobs:
+        nc = do_pack(base, last)
+        code = code or nc
+        count += 1
+    else:
+        while len(outstanding) >= opt.jobs:
+            (pid,nc) = os.wait()
+            nc >>= 8
+            if pid in outstanding:
+                del outstanding[pid]
+                code = code or nc
+                count += 1
+        pid = os.fork()
+        if pid:  # parent
+            outstanding[pid] = 1
+        else: # child
+            try:
+                sys.exit(do_pack(base, last))
+            except Exception, e:
+                log('exception: %r\n' % e)
+                sys.exit(99)
+                
+while len(outstanding):
+    (pid,nc) = os.wait()
+    nc >>= 8
+    if pid in outstanding:
+        del outstanding[pid]
+        code = code or nc
+        count += 1
+    if not opt.verbose:
+        progress('fsck (%d/%d)\r' % (count, len(extra)))
+
+if not opt.verbose and istty:
+    log('fsck done.           \n')
+sys.exit(code)
+#!/usr/bin/env python
+import sys, os, struct, getopt, subprocess, signal
+from bup import options, ssh
+from bup.helpers import *
+
+optspec = """
+bup rbackup <hostname> index ...
+bup rbackup <hostname> save ...
+bup rbackup <hostname> split ...
+"""
+o = options.Options('bup rbackup', optspec, optfunc=getopt.getopt)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+if len(extra) < 2:
+    o.fatal('arguments expected')
+
+class SigException(Exception):
+    def __init__(self, signum):
+        self.signum = signum
+        Exception.__init__(self, 'signal %d received' % signum)
+def handler(signum, frame):
+    raise SigException(signum)
+
+signal.signal(signal.SIGTERM, handler)
+signal.signal(signal.SIGINT, handler)
+
+sp = None
+p = None
+ret = 99
+
+try:
+    hostname = extra[0]
+    argv = extra[1:]
+    p = ssh.connect(hostname, 'rbackup-server')
+
+    argvs = '\0'.join(['bup'] + argv)
+    p.stdin.write(struct.pack('!I', len(argvs)) + argvs)
+    p.stdin.flush()
+
+    main_exe = os.environ.get('BUP_MAIN_EXE') or sys.argv[0]
+    sp = subprocess.Popen([main_exe, 'server'], stdin=p.stdout, stdout=p.stdin)
+
+    p.stdin.close()
+    p.stdout.close()
+
+finally:
+    while 1:
+        # if we get a signal while waiting, we have to keep waiting, just
+        # in case our child doesn't die.
+        try:
+            ret = p.wait()
+            sp.wait()
+            break
+        except SigException, e:
+            log('\nbup rbackup: %s\n' % e)
+            os.kill(p.pid, e.signum)
+            ret = 84
+sys.exit(ret)
+#!/usr/bin/env python
+import sys, os, re
+from bup import options
+
+optspec = """
+bup newliner
+"""
+o = options.Options('bup newliner', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if extra:
+    o.fatal("no arguments expected")
+
+r = re.compile(r'([\r\n])')
+lastlen = 0
+all = ''
+while 1:
+    l = r.split(all, 1)
+    if len(l) <= 1:
+        try:
+            b = os.read(sys.stdin.fileno(), 4096)
+        except KeyboardInterrupt:
+            break
+        if not b:
+            break
+        all += b
+    else:
+        assert(len(l) == 3)
+        (line, splitchar, all) = l
+        #splitchar = '\n'
+        sys.stdout.write('%-*s%s' % (lastlen, line, splitchar))
+        if splitchar == '\r':
+            lastlen = len(line)
+        else:
+            lastlen = 0
+        sys.stdout.flush()
+
+if lastlen or all:
+    sys.stdout.write('%-*s\n' % (lastlen, all))
+#!/usr/bin/env python
+import sys
+from bup import options, git, _hashsplit
+from bup.helpers import *
+
+
+optspec = """
+bup margin
+"""
+o = options.Options('bup margin', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if extra:
+    o.fatal("no arguments expected")
+
+git.check_repo_or_die()
+#git.ignore_midx = 1
+
+mi = git.PackIdxList(git.repo('objects/pack'))
+last = '\0'*20
+longmatch = 0
+for i in mi:
+    if i == last:
+        continue
+    #assert(str(i) >= last)
+    pm = _hashsplit.bitmatch(last, i)
+    longmatch = max(longmatch, pm)
+    last = i
+print longmatch
+#!/usr/bin/env python
+from bup import options, drecurse
+from bup.helpers import *
+
+optspec = """
+bup drecurse <path>
+--
+x,xdev,one-file-system   don't cross filesystem boundaries
+q,quiet  don't actually print filenames
+profile  run under the python profiler
+"""
+o = options.Options('bup drecurse', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if len(extra) != 1:
+    o.fatal("exactly one filename expected")
+
+it = drecurse.recursive_dirlist(extra, opt.xdev)
+if opt.profile:
+    import cProfile
+    def do_it():
+        for i in it:
+            pass
+    cProfile.run('do_it()')
+else:
+    if opt.quiet:
+        for i in it:
+            pass
+    else:
+        for (name,st) in it:
+            print name
+
+if saved_errors:
+    log('WARNING: %d errors encountered.\n' % len(saved_errors))
+    sys.exit(1)
+#!/usr/bin/env python
+import sys, time, struct
+from bup import hashsplit, git, options, client
+from bup.helpers import *
+from subprocess import PIPE
+
+
+optspec = """
+bup split [-tcb] [-n name] [--bench] [filenames...]
+--
+r,remote=  remote repository path
+b,blobs    output a series of blob ids
+t,tree     output a tree id
+c,commit   output a commit id
+n,name=    name of backup set to update (if any)
+N,noop     don't actually save the data anywhere
+q,quiet    don't print progress messages
+v,verbose  increase log output (can be used more than once)
+copy       just copy input to output, hashsplitting along the way
+bench      print benchmark timings to stderr
+max-pack-size=  maximum bytes in a single pack
+max-pack-objects=  maximum number of objects in a single pack
+fanout=  maximum number of blobs in a single tree
+"""
+o = options.Options('bup split', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+git.check_repo_or_die()
+if not (opt.blobs or opt.tree or opt.commit or opt.name or
+        opt.noop or opt.copy):
+    o.fatal("use one or more of -b, -t, -c, -n, -N, --copy")
+if (opt.noop or opt.copy) and (opt.blobs or opt.tree or 
+                               opt.commit or opt.name):
+    o.fatal('-N is incompatible with -b, -t, -c, -n')
+
+if opt.verbose >= 2:
+    git.verbose = opt.verbose - 1
+    opt.bench = 1
+if opt.max_pack_size:
+    hashsplit.max_pack_size = parse_num(opt.max_pack_size)
+if opt.max_pack_objects:
+    hashsplit.max_pack_objects = parse_num(opt.max_pack_objects)
+if opt.fanout:
+    hashsplit.fanout = parse_num(opt.fanout)
+if opt.blobs:
+    hashsplit.fanout = 0
+
+is_reverse = os.environ.get('BUP_SERVER_REVERSE')
+if is_reverse and opt.remote:
+    o.fatal("don't use -r in reverse mode; it's automatic")
+start_time = time.time()
+
+refname = opt.name and 'refs/heads/%s' % opt.name or None
+if opt.noop or opt.copy:
+    cli = w = oldref = None
+elif opt.remote or is_reverse:
+    cli = client.Client(opt.remote)
+    oldref = refname and cli.read_ref(refname) or None
+    w = cli.new_packwriter()
+else:
+    cli = None
+    oldref = refname and git.read_ref(refname) or None
+    w = git.PackWriter()
+
+files = extra and (open(fn) for fn in extra) or [sys.stdin]
+if w:
+    shalist = hashsplit.split_to_shalist(w, files)
+    tree = w.new_tree(shalist)
+else:
+    last = 0
+    for (blob, bits) in hashsplit.hashsplit_iter(files):
+        hashsplit.total_split += len(blob)
+        if opt.copy:
+            sys.stdout.write(str(blob))
+        megs = hashsplit.total_split/1024/1024
+        if not opt.quiet and last != megs:
+            progress('%d Mbytes read\r' % megs)
+            last = megs
+    progress('%d Mbytes read, done.\n' % megs)
+
+if opt.verbose:
+    log('\n')
+if opt.blobs:
+    for (mode,name,bin) in shalist:
+        print bin.encode('hex')
+if opt.tree:
+    print tree.encode('hex')
+if opt.commit or opt.name:
+    msg = 'bup split\n\nGenerated by command:\n%r' % sys.argv
+    ref = opt.name and ('refs/heads/%s' % opt.name) or None
+    commit = w.new_commit(oldref, tree, msg)
+    if opt.commit:
+        print commit.encode('hex')
+
+if w:
+    w.close()  # must close before we can update the ref
+        
+if opt.name:
+    if cli:
+        cli.update_ref(refname, commit, oldref)
+    else:
+        git.update_ref(refname, commit, oldref)
+
+if cli:
+    cli.close()
+
+secs = time.time() - start_time
+size = hashsplit.total_split
+if opt.bench:
+    log('\nbup: %.2fkbytes in %.2f secs = %.2f kbytes/sec\n'
+        % (size/1024., secs, size/1024./secs))
+#!/usr/bin/env python
+import sys, re, struct, mmap
+from bup import git, options
+from bup.helpers import *
+
+
+def s_from_bytes(bytes):
+    clist = [chr(b) for b in bytes]
+    return ''.join(clist)
+
+
+def report(count):
+    fields = ['VmSize', 'VmRSS', 'VmData', 'VmStk']
+    d = {}
+    for line in open('/proc/self/status').readlines():
+        l = re.split(r':\s*', line.strip(), 1)
+        d[l[0]] = l[1]
+    if count >= 0:
+        e1 = count
+        fields = [d[k] for k in fields]
+    else:
+        e1 = ''
+    print ('%9s  ' + ('%10s ' * len(fields))) % tuple([e1] + fields)
+    sys.stdout.flush()
+
+
+optspec = """
+bup memtest [-n elements] [-c cycles]
+--
+n,number=  number of objects per cycle
+c,cycles=  number of cycles to run
+ignore-midx  ignore .midx files, use only .idx files
+"""
+o = options.Options('bup memtest', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if extra:
+    o.fatal('no arguments expected')
+
+git.ignore_midx = opt.ignore_midx
+
+git.check_repo_or_die()
+m = git.PackIdxList(git.repo('objects/pack'))
+
+cycles = opt.cycles or 100
+number = opt.number or 10000
+
+report(-1)
+f = open('/dev/urandom')
+a = mmap.mmap(-1, 20)
+report(0)
+for c in xrange(cycles):
+    for n in xrange(number):
+        b = f.read(3)
+        if 0:
+            bytes = list(struct.unpack('!BBB', b)) + [0]*17
+            bytes[2] &= 0xf0
+            bin = struct.pack('!20s', s_from_bytes(bytes))
+        else:
+            a[0:2] = b[0:2]
+            a[2] = chr(ord(b[2]) & 0xf0)
+            bin = str(a[0:20])
+        #print bin.encode('hex')
+        m.exists(bin)
+    report((c+1)*number)
+#!/usr/bin/env python
+import sys, os, stat
+from bup import options, git, vfs
+from bup.helpers import *
+
+def print_node(text, n):
+    prefix = ''
+    if opt.hash:
+        prefix += "%s " % n.hash.encode('hex')
+    if stat.S_ISDIR(n.mode):
+        print '%s%s/' % (prefix, text)
+    elif stat.S_ISLNK(n.mode):
+        print '%s%s@' % (prefix, text)
+    else:
+        print '%s%s' % (prefix, text)
+
+
+optspec = """
+bup ls <dirs...>
+--
+s,hash   show hash for each file
+"""
+o = options.Options('bup ls', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+git.check_repo_or_die()
+top = vfs.RefList(None)
+
+if not extra:
+    extra = ['/']
+
+ret = 0
+for d in extra:
+    try:
+        n = top.lresolve(d)
+        if stat.S_ISDIR(n.mode):
+            for sub in n:
+                print_node(sub.name, sub)
+        else:
+            print_node(d, n)
+    except vfs.NodeError, e:
+        log('error: %s\n' % e)
+        ret = 1
+
+sys.exit(ret)
+#!/usr/bin/env python
+import sys, os, re, stat, readline, fnmatch
+from bup import options, git, shquote, vfs
+from bup.helpers import *
+
+def node_name(text, n):
+    if stat.S_ISDIR(n.mode):
+        return '%s/' % text
+    elif stat.S_ISLNK(n.mode):
+        return '%s@' % text
+    else:
+        return '%s' % text
+
+
+def do_ls(path, n):
+    l = []
+    if stat.S_ISDIR(n.mode):
+        for sub in n:
+            l.append(node_name(sub.name, sub))
+    else:
+        l.append(node_name(path, n))
+    print columnate(l, '')
+    
 
-export PATH="${PATH:+$PATH:}/usr/sbin:/sbin"
-
-case "$1" in
-  start)
-       check_privsep_dir
-       check_for_no_start
-       check_dev_null
-       log_daemon_msg "Starting OpenBSD Secure Shell server" "sshd"
-       if start-stop-daemon --start --quiet --oknodo --pidfile /var/run/sshd.pid --exec /usr/sbin/sshd -- $SSHD_OPTS; then
-           log_end_msg 0
-           adjust_oom
-       else
-           log_end_msg 1
-       fi
-       ;;
-  stop)
-       log_daemon_msg "Stopping OpenBSD Secure Shell server" "sshd"
-       if start-stop-daemon --stop --quiet --oknodo --pidfile /var/run/sshd.pid; then
-           log_end_msg 0
-       else
-           log_end_msg 1
-       fi
-       ;;
-
-  reload|force-reload)
-       check_for_no_start
-       check_config
-       log_daemon_msg "Reloading OpenBSD Secure Shell server's configuration" "sshd"
-       if start-stop-daemon --stop --signal 1 --quiet --oknodo --pidfile /var/run/sshd.pid --exec /usr/sbin/sshd; then
-           log_end_msg 0
-       else
-           log_end_msg 1
-       fi
-       ;;
-
-  restart)
-       check_privsep_dir
-       check_config
-       log_daemon_msg "Restarting OpenBSD Secure Shell server" "sshd"
-       start-stop-daemon --stop --quiet --oknodo --retry 30 --pidfile /var/run/sshd.pid
-       check_for_no_start log_end_msg
-       check_dev_null log_end_msg
-       if start-stop-daemon --start --quiet --oknodo --pidfile /var/run/sshd.pid --exec /usr/sbin/sshd -- $SSHD_OPTS; then
-           log_end_msg 0
-           adjust_oom
-       else
-           log_end_msg 1
-       fi
-       ;;
-
-  try-restart)
-       check_privsep_dir
-       check_config
-       log_daemon_msg "Restarting OpenBSD Secure Shell server" "sshd"
-       set +e
-       start-stop-daemon --stop --quiet --retry 30 --pidfile /var/run/sshd.pid
-       RET="$?"
-       set -e
-       case $RET in
-           0)
-               # old daemon stopped
-               check_for_no_start log_end_msg
-               check_dev_null log_end_msg
-               if start-stop-daemon --start --quiet --oknodo --pidfile /var/run/sshd.pid --exec /usr/sbin/sshd -- $SSHD_OPTS; then
-                   log_end_msg 0
-               else
-                   log_end_msg 1
-               fi
-               ;;
-           1)
-               # daemon not running
-               log_progress_msg "(not running)"
-               log_end_msg 0
-               ;;
-           *)
-               # failed to stop
-               log_progress_msg "(failed to stop)"
-               log_end_msg 1
-               ;;
-       esac
-       ;;
-
-  *)
-       log_action_msg "Usage: /etc/init.d/ssh {start|stop|reload|force-reload|restart|try-restart}"
-       exit 1
-esac
-
-exit 0
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          stop-bootlogd
-# Required-Start:    $remote_fs
-# Required-Stop:
-# Default-Start:     1 2 3 4 5
-# Default-Stop:
-# Short-Description: Stop bootlogd
-# Description:       See the bootlogd script
-### END INIT INFO
-
-NAME=stop-bootlogd
-DAEMON=/sbin/bootlogd
-
-[ -x "$DAEMON" ] || exit 0
-
-case "$1" in
-  start)
-       /etc/init.d/bootlogd stop
-       ;;
-  stop|restart|force-reload)
-       # No-op
-       ;;
-  *)
-       echo "Usage: $NAME {start|stop|restart|force-reload}" >&2
-       exit 3
-       ;;
-esac
-
-:
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          stop-bootlogd-single
-# Required-Start:    $remote_fs
-# Required-Stop:
-# Default-Start:     S
-# Default-Stop:
-# Short-Description: Stop bootlogd in single user mode
-# Description:       See the bootlogd script
-### END INIT INFO
-
-PATH=/usr/sbin:/usr/bin:/sbin:/bin
-NAME=stop-bootlogd-single
-DAEMON=/sbin/bootlogd
-
-[ -x "$DAEMON" ] || exit 0
-
-case "$1" in
-  start)
-       if [ ! -e /proc/cmdline ] || grep -q '\<single\>' /proc/cmdline
-       then
-               /etc/init.d/bootlogd stop
-       fi
-       ;;
-  stop|restart|force-reload)
-       # No-op
-       ;;
-  *)
-       echo "Usage: $NAME {start|stop|restart|force-reload}" >&2
-       exit 3
-       ;;
-esac
-
-:
-#! /bin/sh
-# /etc/init.d/sysklogd: start the system log daemon.
-
-### BEGIN INIT INFO
-# Provides:             syslog
-# Required-Start:       $local_fs $time
-# Required-Stop:        $local_fs $time
-# Should-Start:         $network $named
-# Should-Stop:          $network $named
-# Default-Start:        S 1 2 3 4 5
-# Default-Stop:         0 6
-# Short-Description:    System logger
-### END INIT INFO
-
-PATH=/bin:/usr/bin:/sbin:/usr/sbin
-
-pidfile=/var/run/syslogd.pid
-binpath=/sbin/syslogd
-
-test -x $binpath || exit 0
-
-# syslogd options should be set in /etc/default/syslogd
-SYSLOGD=""
-
-# user to run syslogd as - this can overriden in /etc/default/syslogd
-USER="syslog"
-
-test ! -r /etc/default/syslogd || . /etc/default/syslogd
-
-# allow ltsp to override
-test ! -r /etc/ltsp/syslogd || . /etc/ltsp/syslogd
-
-# Figure out under which user syslogd should be running as
-if echo ${SYSLOGD} | grep -q '^.*-u[[:space:]]*\([[:alnum:]]*\)[[:space:]]*.*$'
-then
-       # A specific user has been set on the command line, try to extract it.
-       USER=$(echo ${SYSLOGD} | sed -e 's/^.*-u[[:space:]]*\([[:alnum:]]*\)[[:space:]]*.*$/\1/')
-else
-       # By default, run syslogd under the syslog user
-       SYSLOGD="${SYSLOGD} -u ${USER}"
-fi
-
-# Unable to get the user under which syslogd should be running, stop.
-if [ -z "${USER}" ]
-then
-       log_failure_msg "Unable to get syslog user"
-       exit 1
-fi
-
-. /lib/lsb/init-functions
-
-create_xconsole()
-{
-    # Only proceed if /dev/xconsole is used at all
-    if ! grep -q '^[^#].*/dev/xconsole' /etc/syslog.conf
-    then
-       return
-    fi
-
-    if [ ! -e /dev/xconsole ]; then
-       mknod -m 640 /dev/xconsole p
-    else
-       chmod 0640 /dev/xconsole
-    fi
-
-    chown ${USER}:adm /dev/xconsole
+def write_to_file(inf, outf):
+    for blob in chunkyreader(inf):
+        outf.write(blob)
+    
 
-}
+def inputiter():
+    if os.isatty(sys.stdin.fileno()):
+        while 1:
+            try:
+                yield raw_input('bup> ')
+            except EOFError:
+                break
+    else:
+        for line in sys.stdin:
+            yield line
+
+
+def _completer_get_subs(line):
+    (qtype, lastword) = shquote.unfinished_word(line)
+    (dir,name) = os.path.split(lastword)
+    #log('\ncompleter: %r %r %r\n' % (qtype, lastword, text))
+    n = pwd.resolve(dir)
+    subs = list(filter(lambda x: x.name.startswith(name),
+                       n.subs()))
+    return (dir, name, qtype, lastword, subs)
+
+
+_last_line = None
+_last_res = None
+def completer(text, state):
+    global _last_line
+    global _last_res
+    try:
+        line = readline.get_line_buffer()[:readline.get_endidx()]
+        if _last_line != line:
+            _last_res = _completer_get_subs(line)
+            _last_line = line
+        (dir, name, qtype, lastword, subs) = _last_res
+        if state < len(subs):
+            sn = subs[state]
+            sn1 = sn.resolve('')  # deref symlinks
+            fullname = os.path.join(dir, sn.name)
+            if stat.S_ISDIR(sn1.mode):
+                ret = shquote.what_to_add(qtype, lastword, fullname+'/',
+                                          terminate=False)
+            else:
+                ret = shquote.what_to_add(qtype, lastword, fullname,
+                                          terminate=True) + ' '
+            return text + ret
+    except Exception, e:
+        log('\nerror in completion: %s\n' % e)
+
+            
+optspec = """
+bup ftp
+"""
+o = options.Options('bup ftp', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+git.check_repo_or_die()
+
+top = vfs.RefList(None)
+pwd = top
+
+if extra:
+    lines = extra
+else:
+    readline.set_completer_delims(' \t\n\r/')
+    readline.set_completer(completer)
+    readline.parse_and_bind("tab: complete")
+    lines = inputiter()
+
+for line in lines:
+    if not line.strip():
+        continue
+    words = [word for (wordstart,word) in shquote.quotesplit(line)]
+    cmd = words[0].lower()
+    #log('execute: %r %r\n' % (cmd, parm))
+    try:
+        if cmd == 'ls':
+            for parm in (words[1:] or ['.']):
+                do_ls(parm, pwd.resolve(parm))
+        elif cmd == 'cd':
+            for parm in words[1:]:
+                pwd = pwd.resolve(parm)
+        elif cmd == 'pwd':
+            print pwd.fullname()
+        elif cmd == 'cat':
+            for parm in words[1:]:
+                give or take a bitresolve(parm).open(), sys.stdout)
+        elif cmd == 'get':
+            if len(words) not in [2,3]:
+                raise Exception('Usage: get <filename> [localname]')
+            rname = words[1]
+            (dir,base) = os.path.split(rname)
+            lname = len(words)>2 and words[2] or base
+            inf = pwd.resolve(rname).open()
+            log('Saving %r\n' % lname)
+            write_to_file(inf, open(lname, 'wb'))
+        elif cmd == 'mget':
+            for parm in words[1:]:
+                (dir,base) = os.path.split(parm)
+                for n in pwd.resolve(dir).subs():
+                    if fnmatch.fnmatch(n.name, base):
+                        try:
+                            log('Saving %r\n' % n.name)
+                            inf = n.open()
+                            outf = open(n.name, 'wb')
+                            write_to_file(inf, outf)
+                            outf.close()
+                        except Exception, e:
+                            log('  error: %s\n' % e)
+        elif cmd == 'help' or cmd == '?':
+            log('Commands: ls cd pwd cat get mget help quit\n')
+        elif cmd == 'quit' or cmd == 'exit' or cmd == 'bye':
+            break
+        else:
+            raise Exception('no such command %r' % cmd)
+    except Exception, e:
+        log('error: %s\n' % e)
+        #raise
+#!/usr/bin/env python
+import sys, mmap
+from bup import options, _hashsplit
+from bup.helpers import *
+
+optspec = """
+bup random [-S seed] <numbytes>
+--
+S,seed=   optional random number seed (default 1)
+f,force   print random data to stdout even if it's a tty
+"""
+o = options.Options('bup random', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if len(extra) != 1:
+    o.fatal("exactly one argument expected")
+
+total = parse_num(extra[0])
+
+if opt.force or (not os.isatty(1) and
+                 not atoi(os.environ.get('BUP_FORCE_TTY')) & 1):
+    _hashsplit.write_random(sys.stdout.fileno(), total, opt.seed or 0)
+else:
+    log('error: not writing binary data to a terminal. Use -f to force.\n')
+    sys.exit(1)
+#!/usr/bin/env python
+import sys, os, glob
+from bup import options
+
+optspec = """
+bup help <command>
+"""
+o = options.Options('bup help', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if len(extra) == 0:
+    # the wrapper program provides the default usage string
+    os.execvp(os.environ['BUP_MAIN_EXE'], ['bup'])
+elif len(extra) == 1:
+    docname = (extra[0]=='bup' and 'bup' or ('bup-%s' % extra[0]))
+    exe = sys.argv[0]
+    (exepath, exefile) = os.path.split(exe)
+    manpath = os.path.join(exepath, '../Documentation/' + docname + '.[1-9]')
+    g = glob.glob(manpath)
+    if g:
+        os.execvp('man', ['man', '-l', g[0]])
+    else:
+        os.execvp('man', ['man', docname])
+else:
+    o.fatal("exactly one command name expected")
+#!/usr/bin/env python
+import sys, os, stat, errno, fuse, re, time, tempfile
+from bup import options, git, vfs
+from bup.helpers import *
+
+
+class Stat(fuse.Stat):
+    def __init__(self):
+        self.st_mode = 0
+        self.st_ino = 0
+        self.st_dev = 0
+        self.st_nlink = 0
+        self.st_uid = 0
+        self.st_gid = 0
+        self.st_size = 0
+        self.st_atime = 0
+        self.st_mtime = 0
+        self.st_ctime = 0
+        self.st_blocks = 0
+        self.st_blksize = 0
+        self.st_rdev = 0
+
+
+cache = {}
+def cache_get(top, path):
+    parts = path.split('/')
+    cache[('',)] = top
+    c = None
+    max = len(parts)
+    #log('cache: %r\n' % cache.keys())
+    for i in range(max):
+        pre = parts[:max-i]
+        #log('cache trying: %r\n' % pre)
+        c = cache.get(tuple(pre))
+        if c:
+            rest = parts[max-i:]
+            for r in rest:
+                #log('resolving %r from %r\n' % (r, c.fullname()))
+                c = c.lresolve(r)
+                key = tuple(pre + [r])
+                #log('saving: %r\n' % (key,))
+                cache[key] = c
+            break
+    assert(c)
+    return c
+        
+    
 
-fix_log_ownership()
-{
-       for l in `syslogd-listfiles -a`
-       do
-               chown ${USER}:adm $l
-       done
-}
+class BupFs(fuse.Fuse):
+    def __init__(self, top):
+        fuse.Fuse.__init__(self)
+        self.top = top
+    
+    def getattr(self, path):
+        log('--getattr(%r)\n' % path)
+        try:
+            node = cache_get(self.top, path)
+            st = Stat()
+            st.st_mode = node.mode
+            st.st_nlink = node.nlinks()
+            st.st_size = node.size()
+            st.st_mtime = node.mtime
+            st.st_ctime = node.ctime
+            st.st_atime = node.atime
+            return st
+        except vfs.NoSuchFile:
+            return -errno.ENOENT
+
+    def readdir(self, path, offset):
+        log('--readdir(%r)\n' % path)
+        node = cache_get(self.top, path)
+        yield fuse.Direntry('.')
+        yield fuse.Direntry('..')
+        for sub in node.subs():
+            yield fuse.Direntry(sub.name)
+
+    def readlink(self, path):
+        log('--readlink(%r)\n' % path)
+        node = cache_get(self.top, path)
+        return node.readlink()
+
+    def open(self, path, flags):
+        log('--open(%r)\n' % path)
+        node = cache_get(self.top, path)
+        accmode = os.O_RDONLY | os.O_WRONLY | os.O_RDWR
+        if (flags & accmode) != os.O_RDONLY:
+            return -errno.EACCES
+        node.open()
+
+    def release(self, path, flags):
+        log('--release(%r)\n' % path)
+
+    def read(self, path, size, offset):
+        log('--read(%r)\n' % path)
+        n = cache_get(self.top, path)
+        o = n.open()
+        o.seek(offset)
+        return o.read(size)
+
+
+if not hasattr(fuse, '__version__'):
+    raise RuntimeError, "your fuse module is too old for fuse.__version__"
+fuse.fuse_python_api = (0, 2)
+
+
+optspec = """
+bup fuse [-d] [-f] <mountpoint>
+--
+d,debug   increase debug level
+f,foreground  run in foreground
+"""
+o = options.Options('bup fuse', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if len(extra) != 1:
+    o.fatal("exactly one argument expected")
+
+git.check_repo_or_die()
+top = vfs.RefList(None)
+f = BupFs(top)
+f.fuse_args.mountpoint = extra[0]
+if opt.debug:
+    f.fuse_args.add('debug')
+if opt.foreground:
+    f.fuse_args.setmod('foreground')
+print f.multithreaded
+f.multithreaded = False
+
+f.main()
+#!/usr/bin/env python
+from bup import git, options, client
+from bup.helpers import *
+
+optspec = """
+[BUP_DIR=...] bup init [-r host:path]
+--
+r,remote=  remote repository path
+"""
+o = options.Options('bup init', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if extra:
+    o.fatal("no arguments expected")
+
+
+if opt.remote:
+    git.init_repo()  # local repo
+    git.check_repo_or_die()
+    cli = client.Client(opt.remote, create=True)
+    cli.close()
+else:
+    git.init_repo()
+#!/usr/bin/env python
+import sys, math, struct, glob
+from bup import options, git
+from bup.helpers import *
+
+PAGE_SIZE=4096
+SHA_PER_PAGE=PAGE_SIZE/200.
+
+
+def merge(idxlist, bits, table):
+    count = 0
+    for e in git.idxmerge(idxlist):
+        count += 1
+        prefix = git.extract_bits(e, bits)
+        table[prefix] = count
+        yield e
+
+
+def do_midx(outdir, outfilename, infilenames):
+    if not outfilename:
+        assert(outdir)
+        sum = Sha1('\0'.join(infilenames)).hexdigest()
+        outfilename = '%s/midx-%s.midx' % (outdir, sum)
+    
+    inp = []
+    total = 0
+    for name in infilenames:
+        ix = git.PackIdx(name)
+        inp.append(ix)
+        total += len(ix)
+
+    log('Merging %d indexes (%d objects).\n' % (len(infilenames), total))
+    if (not opt.force and (total < 1024 and len(infilenames) < 3)) \
+       or (opt.force and not total):
+        log('midx: nothing to do.\n')
+        return
+
+    pages = int(total/SHA_PER_PAGE) or 1
+    bits = int(math.ceil(math.log(pages, 2)))
+    entries = 2**bits
+    log('Table size: %d (%d bits)\n' % (entries*4, bits))
+    
+    table = [0]*entries
+
+    try:
+        os.unlink(outfilename)
+    except OSError:
+        pass
+    f = open(outfilename + '.tmp', 'w+')
+    f.write('MIDX\0\0\0\2')
+    f.write(struct.pack('!I', bits))
+    assert(f.tell() == 12)
+    f.write('\0'*4*entries)
+    
+    for e in merge(inp, bits, table):
+        f.write(e)
+        
+    f.write('\0'.join(os.path.basename(p) for p in infilenames))
+
+    f.seek(12)
+    f.write(struct.pack('!%dI' % entries, *table))
+    f.close()
+    os.rename(outfilename + '.tmp', outfilename)
+
+    # this is just for testing
+    if 0:
+        p = git.PackMidx(outfilename)
+        assert(len(p.idxnames) == len(infilenames))
+        print p.idxnames
+        assert(len(p) == total)
+        pi = iter(p)
+        for i in merge(inp, total, bits, table):
+            assert(i == pi.next())
+            assert(p.exists(i))
+
+    print outfilename
+
+optspec = """
+bup midx [options...] <idxnames...>
+--
+o,output=  output midx filename (default: auto-generated)
+a,auto     automatically create .midx from any unindexed .idx files
+f,force    automatically create .midx from *all* .idx files
+"""
+o = options.Options('bup midx', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if extra and (opt.auto or opt.force):
+    o.fatal("you can't use -f/-a and also provide filenames")
+
+git.check_repo_or_die()
+
+if extra:
+    do_midx(git.repo('objects/pack'), opt.output, extra)
+elif opt.auto or opt.force:
+    paths = [git.repo('objects/pack')]
+    paths += glob.glob(git.repo('index-cache/*/.'))
+    for path in paths:
+        log('midx: scanning %s\n' % path)
+        if opt.force:
+            do_midx(path, opt.output, glob.glob('%s/*.idx' % path))
+        elif opt.auto:
+            m = git.PackIdxList(path)
+            needed = {}
+            for pack in m.packs:  # only .idx files without a .midx are open
+                if pack.name.endswith('.idx'):
+                    needed[pack.name] = 1
+            del m
+            do_midx(path, opt.output, needed.keys())
+        log('\n')
+else:
+    o.fatal("you must use -f or -a or provide input filenames")
+#!/usr/bin/env python
+import sys, os, random
+from bup import options
+from bup.helpers import *
+
+
+def randblock(n):
+    l = []
+    for i in xrange(n):
+        l.append(chr(random.randrange(0,256)))
+    return ''.join(l)
+
+
+optspec = """
+bup damage [-n count] [-s maxsize] [-S seed] <filenames...>
+--
+   WARNING: THIS COMMAND IS EXTREMELY DANGEROUS
+n,num=   number of blocks to damage
+s,size=  maximum size of each damaged block
+percent= maximum size of each damaged block (as a percent of entire file)
+equal    spread damage evenly throughout the file
+S,seed=  random number seed (for repeatable tests)
+"""
+o = options.Options('bup damage', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if not extra:
+    o.fatal('filenames expected')
+
+if opt.seed != None:
+    random.seed(opt.seed)
+
+for name in extra:
+    log('Damaging "%s"...\n' % name)
+    f = open(name, 'r+b')
+    st = os.fstat(f.fileno())
+    size = st.st_size
+    if opt.percent or opt.size:
+        ms1 = int(float(opt.percent or 0)/100.0*size) or size
+        ms2 = opt.size or size
+        maxsize = min(ms1, ms2)
+    else:
+        maxsize = 1
+    chunks = opt.num or 10
+    chunksize = size/chunks
+    for r in range(chunks):
+        sz = random.randrange(1, maxsize+1)
+        if sz > size:
+            sz = size
+        if opt.equal:
+            ofs = r*chunksize
+        else:
+            ofs = random.randrange(0, size - sz + 1)
+        log('  %6d bytes at %d\n' % (sz, ofs))
+        f.seek(ofs)
+        f.write(randblock(sz))
+    f.close()
+#!/usr/bin/env python
+import sys, struct, mmap
+from bup import options, git
+from bup.helpers import *
+
+suspended_w = None
+
+
+def init_dir(conn, arg):
+    git.init_repo(arg)
+    log('bup server: bupdir initialized: %r\n' % git.repodir)
+    conn.ok()
+
+
+def set_dir(conn, arg):
+    git.check_repo_or_die(arg)
+    log('bup server: bupdir is %r\n' % git.repodir)
+    conn.ok()
 
-running()
-{
-    # No pidfile, probably no daemon present
-    #
-    if [ ! -f $pidfile ]
-    then
-       return 1
-    fi
-
-    pid=`cat $pidfile`
-
-    # No pid, probably no daemon present
-    #
-    if [ -z "$pid" ]
-    then
-       return 1
-    fi
-
-    if [ ! -d /proc/$pid ]
-    then
-       return 1
-    fi
-
-    cmd=`cat /proc/$pid/cmdline | tr "\000" "\n"|head -n 1`
-
-    # No syslogd?
-    #
-    if [ "$cmd" != "$binpath" ]
-    then
-       return 1
-    fi
-
-    return 0
+    
+def list_indexes(conn, junk):
+    git.check_repo_or_die()
+    for f in os.listdir(git.repo('objects/pack')):
+        if f.endswith('.idx'):
+            conn.write('%s\n' % f)
+    conn.ok()
+
+
+def send_index(conn, name):
+    git.check_repo_or_die()
+    assert(name.find('/') < 0)
+    assert(name.endswith('.idx'))
+    idx = git.PackIdx(git.repo('objects/pack/%s' % name))
+    conn.write(struct.pack('!I', len(idx.map)))
+    conn.write(idx.map)
+    conn.ok()
+
+
+def receive_objects(conn, junk):
+    global suspended_w
+    git.check_repo_or_die()
+    suggested = {}
+    if suspended_w:
+        w = suspended_w
+        suspended_w = None
+    else:
+        w = git.PackWriter()
+    while 1:
+        ns = conn.read(4)
+        if not ns:
+            w.abort()
+            raise Exception('object read: expected length header, got EOF\n')
+        n = struct.unpack('!I', ns)[0]
+        #log('expecting %d bytes\n' % n)
+        if not n:
+            log('bup server: received %d object%s.\n' 
+                % (w.count, w.count!=1 and "s" or ''))
+            fullpath = w.close()
+            if fullpath:
+                (dir, name) = os.path.split(fullpath)
+                conn.write('%s.idx\n' % name)
+            conn.ok()
+            return
+        elif n == 0xffffffff:
+            log('bup server: receive-objects suspended.\n')
+            suspended_w = w
+            conn.ok()
+            return
+            
+        buf = conn.read(n)  # object sizes in bup are reasonably small
+        #log('read %d bytes\n' % n)
+        if len(buf) < n:
+            w.abort()
+            raise Exception('object read: expected %d bytes, got %d\n'
+                            % (n, len(buf)))
+        (type, content) = git._decode_packobj(buf)
+        sha = git.calc_hash(type, content)
+        oldpack = w.exists(sha)
+        # FIXME: we only suggest a single index per cycle, because the client
+        # is currently dumb to download more than one per cycle anyway.
+        # Actually we should fix the client, but this is a minor optimization
+        # on the server side.
+        if not suggested and \
+          oldpack and (oldpack == True or oldpack.endswith('.midx')):
+            # FIXME: we shouldn't really have to know about midx files
+            # at this layer.  But exists() on a midx doesn't return the
+            # packname (since it doesn't know)... probably we should just
+            # fix that deficiency of midx files eventually, although it'll
+            # make the files bigger.  This method is certainly not very
+            # efficient.
+            w.objcache.refresh(skip_midx = True)
+            oldpack = w.objcache.exists(sha)
+            log('new suggestion: %r\n' % oldpack)
+            assert(oldpack)
+            assert(oldpack != True)
+            assert(not oldpack.endswith('.midx'))
+            w.objcache.refresh(skip_midx = False)
+        if not suggested and oldpack:
+            assert(oldpack.endswith('.idx'))
+            (dir,name) = os.path.split(oldpack)
+            if not (name in suggested):
+                log("bup server: suggesting index %s\n" % name)
+                conn.write('index %s\n' % name)
+                suggested[name] = 1
+        else:
+            w._raw_write([buf])
+    # NOTREACHED
+
+
+def read_ref(conn, refname):
+    git.check_repo_or_die()
+    r = git.read_ref(refname)
+    conn.write('%s\n' % (r or '').encode('hex'))
+    conn.ok()
+
+
+def update_ref(conn, refname):
+    git.check_repo_or_die()
+    newval = conn.readline().strip()
+    oldval = conn.readline().strip()
+    git.update_ref(refname, newval.decode('hex'), oldval.decode('hex'))
+    conn.ok()
+
+
+def cat(conn, id):
+    git.check_repo_or_die()
+    try:
+        for blob in git.cat(id):
+            conn.write(struct.pack('!I', len(blob)))
+            conn.write(blob)
+    except KeyError, e:
+        log('server: error: %s\n' % e)
+        conn.write('\0\0\0\0')
+        conn.error(e)
+    else:
+        conn.write('\0\0\0\0')
+        conn.ok()
+
+
+optspec = """
+bup server
+"""
+o = options.Options('bup server', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if extra:
+    o.fatal('no arguments expected')
+
+log('bup server: reading from stdin.\n')
+
+commands = {
+    'init-dir': init_dir,
+    'set-dir': set_dir,
+    'list-indexes': list_indexes,
+    'send-index': send_index,
+    'receive-objects': receive_objects,
+    'read-ref': read_ref,
+    'update-ref': update_ref,
+    'cat': cat,
 }
 
-case "$1" in
-  start)
-    log_begin_msg "Starting system log daemon..."
-    create_xconsole
-    fix_log_ownership
-    start-stop-daemon --start --quiet --pidfile $pidfile --name syslogd --startas $binpath -- $SYSLOGD
-    log_end_msg $?
-    ;;
-  stop)
-    log_begin_msg "Stopping system log daemon..."
-    start-stop-daemon --stop --quiet --pidfile $pidfile --name syslogd
-    log_end_msg $?
-    ;;
-  reload|force-reload)
-    log_begin_msg "Reloading system log daemon..."
-    fix_log_ownership
-    start-stop-daemon --stop --quiet --signal 1 --pidfile $pidfile --name syslogd
-    log_end_msg $?
-    ;;
-  restart)
-    log_begin_msg "Restarting system log daemon..."
-    start-stop-daemon --stop --retry 5 --quiet --pidfile $pidfile --name syslogd
-    fix_log_ownership
-    start-stop-daemon --start --quiet --pidfile $pidfile --name syslogd --startas $binpath -- $SYSLOGD
-    log_end_msg $?
-    ;;
-  reload-or-restart)
-    if running
-    then
-       $0 reload
-    else
-       $0 start
-    fi
-    ;;
-  *)
-    log_success_msg "Usage: /etc/init.d/sysklogd {start|stop|reload|restart|force-reload|reload-or-restart}"
-    exit 1
-esac
-
-exit 0
-#!/bin/sh -e
-# init script for udev
-
-# Check the package is still installed
-[ -x /sbin/udevd ] || exit 0
-
-# Get LSB functions
-. /lib/lsb/init-functions
-. /etc/default/rcS
-
-
-case "$1" in
-    start)
-       # We need the uevent support introduced in 2.6.15, bail out if we
-       # don't have it and fall back to a static /dev
-       if [ ! -f /sys/class/mem/null/uevent ]; then
-           if mountpoint -q /dev; then
-               # uh-oh, initramfs made some kind of /dev, get rid of it
-               umount -l /dev/.static/dev
-               umount -l /dev
-           fi
-           exit 1
-       fi
-
-       if ! mountpoint -q /dev; then
-           # initramfs didn't mount /dev, so we'll need to do that
-           mount -n --bind /dev /etc/udev
-           mount -n -t tmpfs -o mode=0755 udev /dev
-           mkdir -m 0700 -p /dev/.static/dev
-           mount -n --move /etc/udev /dev/.static/dev
-       fi
-
-       # Copy over default device tree
-       cp -a -f /lib/udev/devices/* /dev
-
-       # It's all over netlink now
-       if [ -e /proc/sys/kernel/hotplug ]; then
-           echo "" > /proc/sys/kernel/hotplug
-       fi
-       
-       # Start udevd
-       log_begin_msg "Starting kernel event manager..."
-       if start-stop-daemon --start --quiet --exec /sbin/udevd -- --daemon; then
-           log_end_msg 0
-       else
-           log_end_msg $?
-       fi
-
-       # This next bit can take a while
-       if type usplash_write >/dev/null 2>&1; then
-           usplash_write "TIMEOUT 360" ||:
-           trap "usplash_write 'TIMEOUT 15' ||:" 0
-       fi
-
-       # Log things that trigger does
-       /sbin/udevadm monitor -e >/dev/.udev.log &
-       UDEV_MONITOR_PID=$!
-
-       # Fix permissions and missing symlinks/programs for devices made in
-       # initramfs, and catch up on everything we missed
-       log_begin_msg "Loading hardware drivers..."
-       /sbin/udevadm trigger
-       if /sbin/udevadm settle; then
-           log_end_msg 0
-       else
-           log_end_msg $?
-       fi
-
-       # Kill the udev monitor again
-       kill $UDEV_MONITOR_PID
-       ;;
-    stop)
-       log_begin_msg "Stopping kernel event manager..."
-       if start-stop-daemon --stop --quiet --oknodo --exec /sbin/udevd; then
-           log_end_msg 0
-       else
-           log_end_msg $?
-       fi
-       umount -l /dev/.static/dev
-       umount -l /dev
-       ;;
-    restart)
-       cp -au /lib/udev/devices/* /dev
-
-       log_begin_msg "Loading additional hardware drivers..."
-       /sbin/udevadm trigger
-       if /sbin/udevadm settle; then
-           log_end_msg 0
-       else
-           log_end_msg $?
-       fi
-       ;;
-    reload|force-reload)
-       log_begin_msg "Reloading kernel event manager..."
-       if start-stop-daemon --stop --signal 1 --exec /sbin/udevd; then
-           log_end_msg 0
-       else
-           log_end_msg $?
-       fi
-       ;;
-*)
-       echo "Usage: /etc/init.d/udev {start|stop|restart|reload|force-reload}"
-       exit 1
-       ;;
-esac
-
-exit 0
-#!/bin/sh -e
-# init script to finish up udev
-
-# Check the package is still installed
-[ -x /sbin/udevd ] || exit 0
-
-# Get LSB functions
-. /lib/lsb/init-functions
-. /etc/default/rcS
-
-
-case "$1" in
-    start)
-       # Save udev log in /var/log/udev
-       if [ -e /dev/.udev.log ]; then
-           mv -f /dev/.udev.log /var/log/udev
-       fi
-
-       # Copy any rules generated while the root filesystem was read-only
-       for file in /dev/.udev/tmp-rules--*; do
-           dest=${file##*tmp-rules--}
-           [ "$dest" = '*' ] && break
-           cat $file >> /etc/udev/rules.d/$dest
-           rm -f $file
-       done
-       ;;
-    stop|restart|reload|force-reload)
-       ;;
-*)
-       echo "Usage: /etc/init.d/udev {start|stop|restart|reload|force-reload}"
-       exit 1
-       ;;
-esac
-
-exit 0
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          umountfs
-# Required-Start:    umountnfs urandom
-# Required-Stop:
-# Default-Start:     0 6
-# Default-Stop:
-# Short-Description: Turn off swap and unmount all local file systems.
-# Description:
-### END INIT INFO
-
-PATH=/usr/sbin:/usr/bin:/sbin:/bin
-. /lib/init/vars.sh
-
-. /lib/lsb/init-functions
-
-umask 022
-
-# Print in order of decreasing length
-#
-# Algorithm: Find and print longest argument, then call self
-# to print remaining arguments in order of decreasing length
-#
-# This function runs at one tenth the speed of the sort program
-# but we use the function because we don't want to rely on any
-# programs in /usr/.
+# FIXME: this protocol is totally lame and not at all future-proof.
+# (Especially since we abort completely as soon as *anything* bad happens)
+conn = Conn(sys.stdin, sys.stdout)
+lr = linereader(conn)
+for _line in lr:
+    line = _line.strip()
+    if not line:
+        continue
+    log('bup server: command: %r\n' % line)
+    words = line.split(' ', 1)
+    cmd = words[0]
+    rest = len(words)>1 and words[1] or ''
+    if cmd == 'quit':
+        break
+    else:
+        cmd = commands.get(cmd)
+        if cmd:
+            cmd(conn, rest)
+        else:
+            raise Exception('unknown server command: %r\n' % line)
+
+log('bup server: done\n')
+#!/usr/bin/env python
+import sys, time, struct
+from bup import hashsplit, git, options, client
+from bup.helpers import *
+from subprocess import PIPE
+
+
+optspec = """
+bup join [-r host:path] [refs or hashes...]
+--
+r,remote=  remote repository path
+"""
+o = options.Options('bup join', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+git.check_repo_or_die()
+
+if not extra:
+    extra = linereader(sys.stdin)
+
+ret = 0
+
+if opt.remote:
+    cli = client.Client(opt.remote)
+    cat = cli.cat
+else:
+    cp = git.CatPipe()
+    cat = cp.join
+
+for id in extra:
+    try:
+        for blob in cat(id):
+            sys.stdout.write(blob)
+    except KeyError, e:
+        sys.stdout.flush()
+        log('error: %s\n' % e)
+        ret = 1
+
+sys.exit(ret)
+#!/usr/bin/env python
+import sys, re, errno, stat, time, math
+from bup import hashsplit, git, options, index, client
+from bup.helpers import *
+
+
+optspec = """
+bup save [-tc] [-n name] <filenames...>
+--
+r,remote=  remote repository path
+t,tree     output a tree id
+c,commit   output a commit id
+n,name=    name of backup set to update (if any)
+v,verbose  increase log output (can be used more than once)
+q,quiet    don't show progress meter
+smaller=   only back up files smaller than n bytes
+"""
+o = options.Options('bup save', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+git.check_repo_or_die()
+if not (opt.tree or opt.commit or opt.name):
+    o.fatal("use one or more of -t, -c, -n")
+if not extra:
+    o.fatal("no filenames given")
+
+opt.progress = (istty and not opt.quiet)
+opt.smaller = parse_num(opt.smaller or 0)
+
+is_reverse = os.environ.get('BUP_SERVER_REVERSE')
+if is_reverse and opt.remote:
+    o.fatal("don't use -r in reverse mode; it's automatic")
+
+refname = opt.name and 'refs/heads/%s' % opt.name or None
+if opt.remote or is_reverse:
+    cli = client.Client(opt.remote)
+    oldref = refname and cli.read_ref(refname) or None
+    w = cli.new_packwriter()
+else:
+    cli = None
+    oldref = refname and git.read_ref(refname) or None
+    w = git.PackWriter()
+
+handle_ctrl_c()
+
+
+def eatslash(dir):
+    if dir.endswith('/'):
+        return dir[:-1]
+    else:
+        return dir
+
+
+parts = ['']
+shalists = [[]]
+
+def _push(part):
+    assert(part)
+    parts.append(part)
+    shalists.append([])
+
+def _pop(force_tree):
+    assert(len(parts) >= 1)
+    part = parts.pop()
+    shalist = shalists.pop()
+    tree = force_tree or w.new_tree(shalist)
+    if shalists:
+        shalists[-1].append(('40000', part, tree))
+    else:  # this was the toplevel, so put it back for sanity
+        shalists.append(shalist)
+    return tree
+
+lastremain = None
+def progress_report(n):
+    global count, subcount, lastremain
+    subcount += n
+    cc = count + subcount
+    pct = total and (cc*100.0/total) or 0
+    now = time.time()
+    elapsed = now - tstart
+    kps = elapsed and int(cc/1024./elapsed)
+    kps_frac = 10 ** int(math.log(kps+1, 10) - 1)
+    kps = int(kps/kps_frac)*kps_frac
+    if cc:
+        remain = elapsed*1.0/cc * (total-cc)
+    else:
+        remain = 0.0
+    if (lastremain and (remain > lastremain)
+          and ((remain - lastremain)/lastremain < 0.05)):
+        remain = lastremain
+    else:
+        lastremain = remain
+    hours = int(remain/60/60)
+    mins = int(remain/60 - hours*60)
+    secs = int(remain - hours*60*60 - mins*60)
+    if elapsed < 30:
+        remainstr = ''
+        kpsstr = ''
+    else:
+        kpsstr = '%dk/s' % kps
+        if hours:
+            remainstr = '%dh%dm' % (hours, mins)
+        elif mins:
+            remainstr = '%dm%d' % (mins, secs)
+        else:
+            remainstr = '%ds' % secs
+    progress('Saving: %.2f%% (%d/%dk, %d/%d files) %s %s\r'
+             % (pct, cc/1024, total/1024, fcount, ftotal,
+                remainstr, kpsstr))
+
+
+r = index.Reader(git.repo('bupindex'))
+
+def already_saved(ent):
+    return ent.is_valid() and w.exists(ent.sha) and ent.sha
+
+def wantrecurse_pre(ent):
+    return not already_saved(ent)
+
+def wantrecurse_during(ent):
+    return not already_saved(ent) or ent.sha_missing()
+
+total = ftotal = 0
+if opt.progress:
+    for (transname,ent) in r.filter(extra, wantrecurse=wantrecurse_pre):
+        if not (ftotal % 10024):
+            progress('Reading index: %d\r' % ftotal)
+        exists = ent.exists()
+        hashvalid = already_saved(ent)
+        ent.set_sha_missing(not hashvalid)
+        if not opt.smaller or ent.size < opt.smaller:
+            if exists and not hashvalid:
+                total += ent.size
+        ftotal += 1
+    progress('Reading index: %d, done.\n' % ftotal)
+    hashsplit.progress_callback = progress_report
+
+tstart = time.time()
+count = subcount = fcount = 0
+lastskip_name = None
+lastdir = ''
+for (transname,ent) in r.filter(extra, wantrecurse=wantrecurse_during):
+    (dir, file) = os.path.split(ent.name)
+    exists = (ent.flags & index.IX_EXISTS)
+    hashvalid = already_saved(ent)
+    wasmissing = ent.sha_missing()
+    oldsize = ent.size
+    if opt.verbose:
+        if not exists:
+            status = 'D'
+        elif not hashvalid:
+            if ent.sha == index.EMPTY_SHA:
+                status = 'A'
+            else:
+                status = 'M'
+        else:
+            status = ' '
+        if opt.verbose >= 2:
+            log('%s %-70s\n' % (status, ent.name))
+        elif not stat.S_ISDIR(ent.mode) and lastdir != dir:
+            if not lastdir.startswith(dir):
+                log('%s %-70s\n' % (status, os.path.join(dir, '')))
+            lastdir = dir
+
+    if opt.progress:
+        progress_report(0)
+    fcount += 1
+    
+    if not exists:
+        continue
+    if opt.smaller and ent.size >= opt.smaller:
+        if exists and not hashvalid:
+            add_error('skipping large file "%s"' % ent.name)
+            lastskip_name = ent.name
+        continue
+
+    assert(dir.startswith('/'))
+    dirp = dir.split('/')
+    while parts > dirp:
+        _pop(force_tree = None)
+    if dir != '/':
+        for part in dirp[len(parts):]:
+            _push(part)
+
+    if not file:
+        # no filename portion means this is a subdir.  But
+        # sub/parentdirectories already handled in the pop/push() part above.
+        oldtree = already_saved(ent) # may be None
+        newtree = _pop(force_tree = oldtree)
+        if not oldtree:
+            if lastskip_name and lastskip_name.startswith(ent.name):
+                ent.invalidate()
+            else:
+                ent.validate(040000, newtree)
+            ent.repack()
+        if exists and wasmissing:
+            count += oldsize
+        continue
+
+    # it's not a directory
+    id = None
+    if hashvalid:
+        mode = '%o' % ent.gitmode
+        id = ent.sha
+        shalists[-1].append((mode, 
+                             git.mangle_name(file, ent.mode, ent.gitmode),
+                             id))
+    else:
+        if stat.S_ISREG(ent.mode):
+            try:
+                f = hashsplit.open_noatime(ent.name)
+            except IOError, e:
+                add_error(e)
+                lastskip_name = ent.name
+            except OSError, e:
+                add_error(e)
+                lastskip_name = ent.name
+            else:
+                (mode, id) = hashsplit.split_to_blob_or_tree(w, [f])
+        else:
+            if stat.S_ISDIR(ent.mode):
+                assert(0)  # handled above
+            elif stat.S_ISLNK(ent.mode):
+                try:
+                    rl = os.readlink(ent.name)
+                except OSError, e:
+                    add_error(e)
+                    lastskip_name = ent.name
+                except IOError, e:
+                    add_error(e)
+                    lastskip_name = ent.name
+                else:
+                    (mode, id) = ('120000', w.new_blob(rl))
+            else:
+                add_error(Exception('skipping special file "%s"' % ent.name))
+                lastskip_name = ent.name
+        if id:
+            ent.validate(int(mode, 8), id)
+            ent.repack()
+            shalists[-1].append((mode,
+                                 git.mangle_name(file, ent.mode, ent.gitmode),
+                                 id))
+    if exists and wasmissing:
+        count += oldsize
+        subcount = 0
+
+
+if opt.progress:
+    pct = total and count*100.0/total or 100
+    progress('Saving: %.2f%% (%d/%dk, %d/%d files), done.    \n'
+             % (pct, count/1024, total/1024, fcount, ftotal))
+
+while len(parts) > 1:
+    _pop(force_tree = None)
+assert(len(shalists) == 1)
+tree = w.new_tree(shalists[-1])
+if opt.tree:
+    print tree.encode('hex')
+if opt.commit or opt.name:
+    msg = 'bup save\n\nGenerated by command:\n%r' % sys.argv
+    ref = opt.name and ('refs/heads/%s' % opt.name) or None
+    commit = w.new_commit(oldref, tree, msg)
+    if opt.commit:
+        print commit.encode('hex')
+
+w.close()  # must close before we can update the ref
+        
+if opt.name:
+    if cli:
+        cli.update_ref(refname, commit, oldref)
+    else:
+        git.update_ref(refname, commit, oldref)
+
+if cli:
+    cli.close()
+
+if saved_errors:
+    log('WARNING: %d errors encountered while saving.\n' % len(saved_errors))
+    sys.exit(1)
+#!/usr/bin/env python
+import sys, time
+from bup import options
+
+optspec = """
+bup tick
+"""
+o = options.Options('bup tick', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if extra:
+    o.fatal("no arguments expected")
+
+t = time.time()
+tleft = 1 - (t - int(t))
+time.sleep(tleft)
+#!/usr/bin/env python
+import os, sys, stat, time
+from bup import options, git, index, drecurse
+from bup.helpers import *
+
+
+def merge_indexes(out, r1, r2):
+    for e in index.MergeIter([r1, r2]):
+        # FIXME: shouldn't we remove deleted entries eventually?  When?
+        out.add_ixentry(e)
+
+
+class IterHelper:
+    def __init__(self, l):
+        self.i = iter(l)
+        self.cur = None
+        self.next()
+
+    def next(self):
+        try:
+            self.cur = self.i.next()
+        except StopIteration:
+            self.cur = None
+        return self.cur
+
+
+def check_index(reader):
+    try:
+        log('check: checking forward iteration...\n')
+        e = None
+        d = {}
+        for e in reader.forward_iter():
+            if e.children_n:
+                if opt.verbose:
+                    log('%08x+%-4d %r\n' % (e.children_ofs, e.children_n,
+                                            e.name))
+                assert(e.children_ofs)
+                assert(e.name.endswith('/'))
+                assert(not d.get(e.children_ofs))
+                d[e.children_ofs] = 1
+            if e.flags & index.IX_HASHVALID:
+                assert(e.sha != index.EMPTY_SHA)
+                assert(e.gitmode)
+        assert(not e or e.name == '/')  # last entry is *always* /
+        log('check: checking normal iteration...\n')
+        last = None
+        for e in reader:
+            if last:
+                assert(last > e.name)
+            last = e.name
+    except:
+        log('index error! at %r\n' % e)
+        raise
+    log('check: passed.\n')
+
+
+def update_index(top):
+    ri = index.Reader(indexfile)
+    wi = index.Writer(indexfile)
+    rig = IterHelper(ri.iter(name=top))
+    tstart = int(time.time())
+
+    hashgen = None
+    if opt.fake_valid:
+        def hashgen(name):
+            return (0100644, index.FAKE_SHA)
+
+    total = 0
+    for (path,pst) in drecurse.recursive_dirlist([top], xdev=opt.xdev):
+        if opt.verbose>=2 or (opt.verbose==1 and stat.S_ISDIR(pst.st_mode)):
+            sys.stdout.write('%s\n' % path)
+            sys.stdout.flush()
+            progress('Indexing: %d\r' % total)
+        elif not (total % 128):
+            progress('Indexing: %d\r' % total)
+        total += 1
+        while rig.cur and rig.cur.name > path:  # deleted paths
+            if rig.cur.exists():
+                rig.cur.set_deleted()
+                rig.cur.repack()
+            rig.next()
+        if rig.cur and rig.cur.name == path:    # paths that already existed
+            if pst:
+                rig.cur.from_stat(pst, tstart)
+            if not (rig.cur.flags & index.IX_HASHVALID):
+                if hashgen:
+                    (rig.cur.gitmode, rig.cur.sha) = hashgen(path)
+                    rig.cur.flags |= index.IX_HASHVALID
+            if opt.fake_invalid:
+                rig.cur.invalidate()
+            rig.cur.repack()
+            rig.next()
+        else:  # new paths
+            wi.add(path, pst, hashgen = hashgen)
+    progress('Indexing: %d, done.\n' % total)
+    
+    if ri.exists():
+        ri.save()
+        wi.flush()
+        if wi.count:
+            wr = wi.new_reader()
+            if opt.check:
+                log('check: before merging: oldfile\n')
+                check_index(ri)
+                log('check: before merging: newfile\n')
+                check_index(wr)
+            mi = index.Writer(indexfile)
+            merge_indexes(mi, ri, wr)
+            ri.close()
+            mi.close()
+            wr.close()
+        wi.abort()
+    else:
+        wi.close()
+
+
+optspec = """
+bup index <-p|m|u> [options...] <filenames...>
+--
+p,print    print the index entries for the given names (also works with -u)
+m,modified print only added/deleted/modified files (implies -p)
+s,status   print each filename with a status char (A/M/D) (implies -p)
+H,hash     print the hash for each object next to its name (implies -p)
+l,long     print more information about each file
+u,update   (recursively) update the index entries for the given filenames
+x,xdev,one-file-system  don't cross filesystem boundaries
+fake-valid mark all index entries as up-to-date even if they aren't
+fake-invalid mark all index entries as invalid
+check      carefully check index file integrity
+f,indexfile=  the name of the index file (default 'index')
+v,verbose  increase log output (can be used more than once)
+"""
+o = options.Options('bup index', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if not (opt.modified or opt['print'] or opt.status or opt.update or opt.check):
+    o.fatal('supply one or more of -p, -s, -m, -u, or --check')
+if (opt.fake_valid or opt.fake_invalid) and not opt.update:
+    o.fatal('--fake-{in,}valid are meaningless without -u')
+if opt.fake_valid and opt.fake_invalid:
+    o.fatal('--fake-valid is incompatible with --fake-invalid')
+
+git.check_repo_or_die()
+indexfile = opt.indexfile or git.repo('bupindex')
+
+handle_ctrl_c()
+
+if opt.check:
+    log('check: starting initial check.\n')
+    check_index(index.Reader(indexfile))
+
+paths = index.reduce_paths(extra)
+
+if opt.update:
+    if not paths:
+        o.fatal('update (-u) requested but no paths given')
+    for (rp,path) in paths:
+        update_index(rp)
+
+if opt['print'] or opt.status or opt.modified:
+    for (name, ent) in index.Reader(indexfile).filter(extra or ['']):
+        if (opt.modified 
+            and (ent.is_valid() or ent.is_deleted() or not ent.mode)):
+            continue
+        line = ''
+        if opt.status:
+            if ent.is_deleted():
+                line += 'D '
+            elif not ent.is_valid():
+                if ent.sha == index.EMPTY_SHA:
+                    line += 'A '
+                else:
+                    line += 'M '
+            else:
+                line += '  '
+        if opt.hash:
+            line += ent.sha.encode('hex') + ' '
+        if opt.long:
+            line += "%7s %7s " % (oct(ent.mode), oct(ent.gitmode))
+        print line + (name or './')
+
+if opt.check and (opt['print'] or opt.status or opt.modified or opt.update):
+    log('check: starting final check.\n')
+    check_index(index.Reader(indexfile))
+
+if saved_errors:
+    log('WARNING: %d errors encountered.\n' % len(saved_errors))
+    sys.exit(1)
+#!/usr/bin/env python
+import sys, os, struct
+from bup import options, helpers
+
+optspec = """
+bup rbackup-server
+--
+    This command is not intended to be run manually.
+"""
+o = options.Options('bup rbackup-server', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+if extra:
+    o.fatal('no arguments expected')
+
+# get the subcommand's argv.
+# Normally we could just pass this on the command line, but since we'll often
+# be getting called on the other end of an ssh pipe, which tends to mangle
+# argv (by sending it via the shell), this way is much safer.
+buf = sys.stdin.read(4)
+sz = struct.unpack('!I', buf)[0]
+assert(sz > 0)
+assert(sz < 1000000)
+buf = sys.stdin.read(sz)
+assert(len(buf) == sz)
+argv = buf.split('\0')
+
+# stdin/stdout are supposedly connected to 'bup server' that the caller
+# started for us (often on the other end of an ssh tunnel), so we don't want
+# to misuse them.  Move them out of the way, then replace stdout with
+# a pointer to stderr in case our subcommand wants to do something with it.
 #
-# N.B.: Arguments must not be null and must not contain whitespace
+# It might be nice to do the same with stdin, but my experiments showed that
+# ssh seems to make its child's stderr a readable-but-never-reads-anything
+# socket.  They really should have used shutdown(SHUT_WR) on the other end
+# of it, but probably didn't.  Anyway, it's too messy, so let's just make sure
+# anyone reading from stdin is disappointed.
 #
-pioodl() {
-       [ "$1" ] || return 0
-       ARGNUM=1
-       ARGNUM_LONGEST=0
-       ARGLENGTH_LONGEST=0
-       for ARG in "$@"
-       do
-               ARGLENGTH="${#ARG}"
-               if [ "$ARGLENGTH" -gt "$ARGLENGTH_LONGEST" ]
-               then
-                       ARGLENGTH_LONGEST="$ARGLENGTH"
-                       ARGNUM_LONGEST="$ARGNUM"
-               fi
-               ARGNUM=$(($ARGNUM + 1))
-       done
-       # The method of passing prevargs assumes that args can be
-       # delimited with spaces
-       ARGNUM=1
-       PREVARGS=""
-       while [ "$ARGNUM" -lt "$ARGNUM_LONGEST" ]
-       do
-               PREVARGS="$PREVARGS $1"
-               shift
-               ARGNUM=$(($ARGNUM + 1))
-       done
-       echo "$1"
-       shift
-       pioodl $PREVARGS "$@"
-}
+# (You can't just leave stdin/stdout "not open" by closing the file
+# descriptors.  Then the next file that opens is automatically assigned 0 or 1,
+# and people *trying* to read/write stdin/stdout get screwed.)
+os.dup2(0, 3)
+os.dup2(1, 4)
+os.dup2(2, 1)
+fd = os.open('/dev/null', os.O_RDONLY)
+os.dup2(fd, 0)
+os.close(fd)
+
+os.environ['BUP_SERVER_REVERSE'] = helpers.hostname()
+os.execvp(argv[0], argv)
+sys.exit(99)
+#!/usr/bin/env python
+import sys, os, glob, subprocess, time
+from bup import options, git
+from bup.helpers import *
+
+par2_ok = 0
+nullf = open('/dev/null')
+
+def debug(s):
+    if opt.verbose:
+        log(s)
+
+def run(argv):
+    # at least in python 2.5, using "stdout=2" or "stdout=sys.stderr" below
+    # doesn't actually work, because subprocess closes fd #2 right before
+    # execing for some reason.  So we work around it by duplicating the fd
+    # first.
+    fd = os.dup(2)  # copy stderr
+    try:
+        p = subprocess.Popen(argv, stdout=fd, close_fds=False)
+        return p.wait()
+    finally:
+        os.close(fd)
+
+def par2_setup():
+    global par2_ok
+    rv = 1
+    try:
+        p = subprocess.Popen(['par2', '--help'],
+                             stdout=nullf, stderr=nullf, stdin=nullf)
+        rv = p.wait()
+    except OSError:
+        log('fsck: warning: par2 not found; disabling recovery features.\n')
+    else:
+        par2_ok = 1
+
+def parv(lvl):
+    if opt.verbose >= lvl:
+        if istty:
+            return []
+        else:
+            return ['-q']
+    else:
+        return ['-qq']
+
+def par2_generate(base):
+    return run(['par2', 'create', '-n1', '-c200'] + parv(2)
+               + ['--', base, base+'.pack', base+'.idx'])
+
+def par2_verify(base):
+    return run(['par2', 'verify'] + parv(3) + ['--', base])
+
+def par2_repair(base):
+    return run(['par2', 'repair'] + parv(2) + ['--', base])
+
+def quick_verify(base):
+    f = open(base + '.pack', 'rb')
+    f.seek(-20, 2)
+    wantsum = f.read(20)
+    assert(len(wantsum) == 20)
+    f.seek(0)
+    sum = Sha1()
+    for b in chunkyreader(f, os.fstat(f.fileno()).st_size - 20):
+        sum.update(b)
+    if sum.digest() != wantsum:
+        raise ValueError('expected %r, got %r' % (wantsum.encode('hex'),
+                                                  sum.hexdigest()))
+        
 
+def git_verify(base):
+    if opt.quick:
+        try:
+            quick_verify(base)
+        except Exception, e:
+            debug('error: %s\n' % e)
+            return 1
+        return 0
+    else:
+        return run(['git', 'verify-pack', '--', base])
+    
+    
+def do_pack(base, last):
+    code = 0
+    if par2_ok and par2_exists and (opt.repair or not opt.generate):
+        vresult = par2_verify(base)
+        if vresult != 0:
+            if opt.repair:
+                rresult = par2_repair(base)
+                if rresult != 0:
+                    print '%s par2 repair: failed (%d)' % (last, rresult)
+                    code = rresult
+                else:
+                    print '%s par2 repair: succeeded (0)' % last
+                    code = 100
+            else:
+                print '%s par2 verify: failed (%d)' % (last, vresult)
+                code = vresult
+        else:
+            print '%s ok' % last
+    elif not opt.generate or (par2_ok and not par2_exists):
+        gresult = git_verify(base)
+        if gresult != 0:
+            print '%s git verify: failed (%d)' % (last, gresult)
+            code = gresult
+        else:
+            if par2_ok and opt.generate:
+                presult = par2_generate(base)
+                if presult != 0:
+                    print '%s par2 create: failed (%d)' % (last, presult)
+                    code = presult
+                else:
+                    print '%s ok' % last
+            else:
+                print '%s ok' % last
+    else:
+        assert(opt.generate and (not par2_ok or par2_exists))
+        debug('    skipped: par2 file already generated.\n')
+    return code
+
+
+optspec = """
+bup fsck [options...] [filenames...]
+--
+r,repair    attempt to repair errors using par2 (dangerous!)
+g,generate  generate auto-repair information using par2
+v,verbose   increase verbosity (can be used more than once)
+quick       just check pack sha1sum, don't use git verify-pack
+j,jobs=     run 'n' jobs in parallel
+par2-ok     immediately return 0 if par2 is ok, 1 if not
+disable-par2  ignore par2 even if it is available
+"""
+o = options.Options('bup fsck', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+par2_setup()
+if opt.par2_ok:
+    if par2_ok:
+        sys.exit(0)  # 'true' in sh
+    else:
+        sys.exit(1)
+if opt.disable_par2:
+    par2_ok = 0
+
+git.check_repo_or_die()
+
+if not extra:
+    debug('fsck: No filenames given: checking all packs.\n')
+    extra = glob.glob(git.repo('objects/pack/*.pack'))
+
+code = 0
+count = 0
+outstanding = {}
+for name in extra:
+    if name.endswith('.pack'):
+        base = name[:-5]
+    elif name.endswith('.idx'):
+        base = name[:-4]
+    elif name.endswith('.par2'):
+        base = name[:-5]
+    elif os.path.exists(name + '.pack'):
+        base = name
+    else:
+        raise Exception('%s is not a pack file!' % name)
+    (dir,last) = os.path.split(base)
+    par2_exists = os.path.exists(base + '.par2')
+    if par2_exists and os.stat(base + '.par2').st_size == 0:
+        par2_exists = 0
+    sys.stdout.flush()
+    debug('fsck: checking %s (%s)\n' 
+          % (last, par2_ok and par2_exists and 'par2' or 'git'))
+    if not opt.verbose:
+        progress('fsck (%d/%d)\r' % (count, len(extra)))
+    
+    if not opt.jobs:
+        nc = do_pack(base, last)
+        code = code or nc
+        count += 1
+    else:
+        while len(outstanding) >= opt.jobs:
+            (pid,nc) = os.wait()
+            nc >>= 8
+            if pid in outstanding:
+                del outstanding[pid]
+                code = code or nc
+                count += 1
+        pid = os.fork()
+        if pid:  # parent
+            outstanding[pid] = 1
+        else: # child
+            try:
+                sys.exit(do_pack(base, last))
+            except Exception, e:
+                log('exception: %r\n' % e)
+                sys.exit(99)
+                
+while len(outstanding):
+    (pid,nc) = os.wait()
+    nc >>= 8
+    if pid in outstanding:
+        del outstanding[pid]
+        code = code or nc
+        count += 1
+    if not opt.verbose:
+        progress('fsck (%d/%d)\r' % (count, len(extra)))
+
+if not opt.verbose and istty:
+    log('fsck done.           \n')
+sys.exit(code)
+#!/usr/bin/env python
+import sys, os, struct, getopt, subprocess, signal
+from bup import options, ssh
+from bup.helpers import *
+
+optspec = """
+bup rbackup <hostname> index ...
+bup rbackup <hostname> save ...
+bup rbackup <hostname> split ...
+"""
+o = options.Options('bup rbackup', optspec, optfunc=getopt.getopt)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+if len(extra) < 2:
+    o.fatal('arguments expected')
+
+class SigException(Exception):
+    def __init__(self, signum):
+        self.signum = signum
+        Exception.__init__(self, 'signal %d received' % signum)
+def handler(signum, frame):
+    raise SigException(signum)
+
+signal.signal(signal.SIGTERM, handler)
+signal.signal(signal.SIGINT, handler)
+
+sp = None
+p = None
+ret = 99
+
+try:
+    hostname = extra[0]
+    argv = extra[1:]
+    p = ssh.connect(hostname, 'rbackup-server')
+
+    argvs = '\0'.join(['bup'] + argv)
+    p.stdin.write(struct.pack('!I', len(argvs)) + argvs)
+    p.stdin.flush()
+
+    main_exe = os.environ.get('BUP_MAIN_EXE') or sys.argv[0]
+    sp = subprocess.Popen([main_exe, 'server'], stdin=p.stdout, stdout=p.stdin)
+
+    p.stdin.close()
+    p.stdout.close()
+
+finally:
+    while 1:
+        # if we get a signal while waiting, we have to keep waiting, just
+        # in case our child doesn't die.
+        try:
+            ret = p.wait()
+            sp.wait()
+            break
+        except SigException, e:
+            log('\nbup rbackup: %s\n' % e)
+            os.kill(p.pid, e.signum)
+            ret = 84
+sys.exit(ret)
+#!/usr/bin/env python
+import sys, os, re
+from bup import options
+
+optspec = """
+bup newliner
+"""
+o = options.Options('bup newliner', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if extra:
+    o.fatal("no arguments expected")
+
+r = re.compile(r'([\r\n])')
+lastlen = 0
+all = ''
+while 1:
+    l = r.split(all, 1)
+    if len(l) <= 1:
+        try:
+            b = os.read(sys.stdin.fileno(), 4096)
+        except KeyboardInterrupt:
+            break
+        if not b:
+            break
+        all += b
+    else:
+        assert(len(l) == 3)
+        (line, splitchar, all) = l
+        #splitchar = '\n'
+        sys.stdout.write('%-*s%s' % (lastlen, line, splitchar))
+        if splitchar == '\r':
+            lastlen = len(line)
+        else:
+            lastlen = 0
+        sys.stdout.flush()
+
+if lastlen or all:
+    sys.stdout.write('%-*s\n' % (lastlen, all))
+#!/usr/bin/env python
+import sys
+from bup import options, git, _hashsplit
+from bup.helpers import *
+
+
+optspec = """
+bup margin
+"""
+o = options.Options('bup margin', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if extra:
+    o.fatal("no arguments expected")
+
+git.check_repo_or_die()
+#git.ignore_midx = 1
+
+mi = git.PackIdxList(git.repo('objects/pack'))
+last = '\0'*20
+longmatch = 0
+for i in mi:
+    if i == last:
+        continue
+    #assert(str(i) >= last)
+    pm = _hashsplit.bitmatch(last, i)
+    longmatch = max(longmatch, pm)
+    last = i
+print longmatch
+#!/usr/bin/env python
+from bup import options, drecurse
+from bup.helpers import *
+
+optspec = """
+bup drecurse <path>
+--
+x,xdev,one-file-system   don't cross filesystem boundaries
+q,quiet  don't actually print filenames
+profile  run under the python profiler
+"""
+o = options.Options('bup drecurse', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if len(extra) != 1:
+    o.fatal("exactly one filename expected")
+
+it = drecurse.recursive_dirlist(extra, opt.xdev)
+if opt.profile:
+    import cProfile
+    def do_it():
+        for i in it:
+            pass
+    cProfile.run('do_it()')
+else:
+    if opt.quiet:
+        for i in it:
+            pass
+    else:
+        for (name,st) in it:
+            print name
+
+if saved_errors:
+    log('WARNING: %d errors encountered.\n' % len(saved_errors))
+    sys.exit(1)
+#!/usr/bin/env python
+import sys, time, struct
+from bup import hashsplit, git, options, client
+from bup.helpers import *
+from subprocess import PIPE
+
+
+optspec = """
+bup split [-tcb] [-n name] [--bench] [filenames...]
+--
+r,remote=  remote repository path
+b,blobs    output a series of blob ids
+t,tree     output a tree id
+c,commit   output a commit id
+n,name=    name of backup set to update (if any)
+N,noop     don't actually save the data anywhere
+q,quiet    don't print progress messages
+v,verbose  increase log output (can be used more than once)
+copy       just copy input to output, hashsplitting along the way
+bench      print benchmark timings to stderr
+max-pack-size=  maximum bytes in a single pack
+max-pack-objects=  maximum number of objects in a single pack
+fanout=  maximum number of blobs in a single tree
+"""
+o = options.Options('bup split', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+git.check_repo_or_die()
+if not (opt.blobs or opt.tree or opt.commit or opt.name or
+        opt.noop or opt.copy):
+    o.fatal("use one or more of -b, -t, -c, -n, -N, --copy")
+if (opt.noop or opt.copy) and (opt.blobs or opt.tree or 
+                               opt.commit or opt.name):
+    o.fatal('-N is incompatible with -b, -t, -c, -n')
+
+if opt.verbose >= 2:
+    git.verbose = opt.verbose - 1
+    opt.bench = 1
+if opt.max_pack_size:
+    hashsplit.max_pack_size = parse_num(opt.max_pack_size)
+if opt.max_pack_objects:
+    hashsplit.max_pack_objects = parse_num(opt.max_pack_objects)
+if opt.fanout:
+    hashsplit.fanout = parse_num(opt.fanout)
+if opt.blobs:
+    hashsplit.fanout = 0
+
+is_reverse = os.environ.get('BUP_SERVER_REVERSE')
+if is_reverse and opt.remote:
+    o.fatal("don't use -r in reverse mode; it's automatic")
+start_time = time.time()
+
+refname = opt.name and 'refs/heads/%s' % opt.name or None
+if opt.noop or opt.copy:
+    cli = w = oldref = None
+elif opt.remote or is_reverse:
+    cli = client.Client(opt.remote)
+    oldref = refname and cli.read_ref(refname) or None
+    w = cli.new_packwriter()
+else:
+    cli = None
+    oldref = refname and git.read_ref(refname) or None
+    w = git.PackWriter()
+
+files = extra and (open(fn) for fn in extra) or [sys.stdin]
+if w:
+    shalist = hashsplit.split_to_shalist(w, files)
+    tree = w.new_tree(shalist)
+else:
+    last = 0
+    for (blob, bits) in hashsplit.hashsplit_iter(files):
+        hashsplit.total_split += len(blob)
+        if opt.copy:
+            sys.stdout.write(str(blob))
+        megs = hashsplit.total_split/1024/1024
+        if not opt.quiet and last != megs:
+            progress('%d Mbytes read\r' % megs)
+            last = megs
+    progress('%d Mbytes read, done.\n' % megs)
+
+if opt.verbose:
+    log('\n')
+if opt.blobs:
+    for (mode,name,bin) in shalist:
+        print bin.encode('hex')
+if opt.tree:
+    print tree.encode('hex')
+if opt.commit or opt.name:
+    msg = 'bup split\n\nGenerated by command:\n%r' % sys.argv
+    ref = opt.name and ('refs/heads/%s' % opt.name) or None
+    commit = w.new_commit(oldref, tree, msg)
+    if opt.commit:
+        print commit.encode('hex')
+
+if w:
+    w.close()  # must close before we can update the ref
+        
+if opt.name:
+    if cli:
+        cli.update_ref(refname, commit, oldref)
+    else:
+        git.update_ref(refname, commit, oldref)
+
+if cli:
+    cli.close()
+
+secs = time.time() - start_time
+size = hashsplit.total_split
+if opt.bench:
+    log('\nbup: %.2fkbytes in %.2f secs = %.2f kbytes/sec\n'
+        % (size/1024., secs, size/1024./secs))
+#!/usr/bin/env python
+import sys, re, struct, mmap
+from bup import git, options
+from bup.helpers import *
+
+
+def s_from_bytes(bytes):
+    clist = [chr(b) for b in bytes]
+    return ''.join(clist)
+
+
+def report(count):
+    fields = ['VmSize', 'VmRSS', 'VmData', 'VmStk']
+    d = {}
+    for line in open('/proc/self/status').readlines():
+        l = re.split(r':\s*', line.strip(), 1)
+        d[l[0]] = l[1]
+    if count >= 0:
+        e1 = count
+        fields = [d[k] for k in fields]
+    else:
+        e1 = ''
+    print ('%9s  ' + ('%10s ' * len(fields))) % tuple([e1] + fields)
+    sys.stdout.flush()
+
+
+optspec = """
+bup memtest [-n elements] [-c cycles]
+--
+n,number=  number of objects per cycle
+c,cycles=  number of cycles to run
+ignore-midx  ignore .midx files, use only .idx files
+"""
+o = options.Options('bup memtest', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if extra:
+    o.fatal('no arguments expected')
+
+git.ignore_midx = opt.ignore_midx
+
+git.check_repo_or_die()
+m = git.PackIdxList(git.repo('objects/pack'))
+
+cycles = opt.cycles or 100
+number = opt.number or 10000
+
+report(-1)
+f = open('/dev/urandom')
+a = mmap.mmap(-1, 20)
+report(0)
+for c in xrange(cycles):
+    for n in xrange(number):
+        b = f.read(3)
+        if 0:
+            bytes = list(struct.unpack('!BBB', b)) + [0]*17
+            bytes[2] &= 0xf0
+            bin = struct.pack('!20s', s_from_bytes(bytes))
+        else:
+            a[0:2] = b[0:2]
+            a[2] = chr(ord(b[2]) & 0xf0)
+            bin = str(a[0:20])
+        #print bin.encode('hex')
+        m.exists(bin)
+    report((c+1)*number)
+#!/usr/bin/env python
+import sys, os, stat
+from bup import options, git, vfs
+from bup.helpers import *
+
+def print_node(text, n):
+    prefix = ''
+    if opt.hash:
+        prefix += "%s " % n.hash.encode('hex')
+    if stat.S_ISDIR(n.mode):
+        print '%s%s/' % (prefix, text)
+    elif stat.S_ISLNK(n.mode):
+        print '%s%s@' % (prefix, text)
+    else:
+        print '%s%s' % (prefix, text)
+
+
+optspec = """
+bup ls <dirs...>
+--
+s,hash   show hash for each file
+"""
+o = options.Options('bup ls', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+git.check_repo_or_die()
+top = vfs.RefList(None)
+
+if not extra:
+    extra = ['/']
+
+ret = 0
+for d in extra:
+    try:
+        n = top.lresolve(d)
+        if stat.S_ISDIR(n.mode):
+            for sub in n:
+                print_node(sub.name, sub)
+        else:
+            print_node(d, n)
+    except vfs.NodeError, e:
+        log('error: %s\n' % e)
+        ret = 1
+
+sys.exit(ret)
+#!/usr/bin/env python
+import sys, os, re, stat, readline, fnmatch
+from bup import options, git, shquote, vfs
+from bup.helpers import *
+
+def node_name(text, n):
+    if stat.S_ISDIR(n.mode):
+        return '%s/' % text
+    elif stat.S_ISLNK(n.mode):
+        return '%s@' % text
+    else:
+        return '%s' % text
+
+
+def do_ls(path, n):
+    l = []
+    if stat.S_ISDIR(n.mode):
+        for sub in n:
+            l.append(node_name(sub.name, sub))
+    else:
+        l.append(node_name(path, n))
+    print columnate(l, '')
+    
 
-do_stop () {
-       exec 9<&0 </proc/mounts
-       PROTECTED_MOUNTS="$(sed -n '0,/^\/[^ ]* \/ /p' /proc/mounts)"
-       WEAK_MTPTS="" #be gentle, don't use force
-       REG_MTPTS=""
-       TMPFS_MTPTS=""
-       while read DEV MTPT FSTYPE REST
-       do
-               echo "$PROTECTED_MOUNTS" | grep -qs "^$DEV $MTPT " && continue
-               case "$MTPT" in
-                       /|/proc|/dev|/.dev|/dev/pts|/dev/shm|/proc/*|/sys|/var/run|/var/lock)
-                       continue
-                       ;;
-               esac
-               case "$FSTYPE" in
-                       proc|procfs|linprocfs|devfs|sysfs|usbfs|usbdevfs|devpts|securityfs)
-                       continue
-                       ;;
-                 tmpfs)
-                       if [ -d "$MTPT" ]; then
-                               TMPFS_MTPTS="$TMPFS_MTPTS $MTPT"
-                       fi
-                       ;;
-                 *)
-                       REG_MTPTS="$REG_MTPTS $MTPT"
-                       if echo "$PROTECTED_MOUNTS" | grep -qs "^$DEV "; then
-                               WEAK_MTPTS="$WEAK_MTPTS $MTPT "
-                       fi
-                       ;;
-               esac
-       done
-
-       exec 0<&9 9<&-
-
-       #
-       # Make sure tmpfs file systems are umounted before turning off
-       # swap, to avoid running out of memory if the tmpfs filesystems
-       # use a lot of space.
-       #
-       if [ "$TMPFS_MTPTS" ]
-       then
-               if [ "$VERBOSE" = no ]
-               then
-                       log_action_begin_msg "Unmounting temporary filesystems"
-                       umount $TMPFS_MTPTS
-                       log_action_end_msg $?
-               else
-                       log_action_msg "Will now unmount temporary filesystems"
-                       umount -v $TMPFS_MTPTS
-                       ES=$?
-                       if [ "$ES" = 0 ]
-                       then
-                               log_success_msg "Done unmounting temporary filesystems."
-                       else
-                               log_failure_msg "Unmounting temporary filesystems failed with error code ${ES}."
-                       fi
-               fi
-       fi
-
-       #
-       # Deactivate swap
-       #
-       if [ "$VERBOSE" = no ]
-       then
-               log_action_begin_msg "Deactivating swap"
-               swapoff -a >/dev/null
-               log_action_end_msg $?
-       else
-               log_action_msg "Will now deactivate swap"
-               swapoff -a -v
-               ES=$?
-               if [ "$ES" = 0 ]
-               then
-                       log_success_msg "Done deactivating swap."
-               else
-                       log_failure_msg "Swap deactivation failed with error code ${ES}."
-               fi
-       fi
-
-       #
-       # Unmount local filesystems
-       #
-       [ -z "$REG_MTPTS" ] && return
-       [ "$VERBOSE" = no ] && log_action_begin_msg "Unmounting local filesystems"
-       REG_MTPTS="$(pioodl $REG_MTPTS)"
-       local ES2=0
-       for MTPT in $REG_MTPTS; do
-               if echo "$WEAK_MTPTS" | grep -qs " $MTPT "; then
-                       FORCE=""
-               else
-                       FORCE="-f"
-               fi
-               if [ "$VERBOSE" = no ]; then
-                       umount $FORCE -r -d $MTPT
-                       ES=$?
-                       [ "$ES" != 0 ] && [ "$ES2" = 0 ] && ES2=$ES
-               else
-                       log_action_begin_msg "Unmounting local filesystem $MTPT"
-                       umount $FORCE -v -r -d $MTPT
-                       ES=$?
-                       if [ "$ES" = 0 ]; then
-                               log_success_msg "Done unmounting local filesystem $MTPT."
-                       else
-                               log_failure_msg "Unmounting local filesystem $MTPT failed with error code $ES."
-                       fi
-               fi
-       done
-       [ "$VERBOSE" = no ] && log_action_end_msg $ES2
-}
+def write_to_file(inf, outf):
+    for blob in chunkyreader(inf):
+        outf.write(blob)
+    
 
-case "$1" in
-  start)
-       # No-op
-       ;;
-  restart|reload|force-reload)
-       echo "Error: argument '$1' not supported" >&2
-       exit 3
-       ;;
-  stop)
-       do_stop
-       ;;
-  *)
-       echo "Usage: $0 start|stop" >&2
-       exit 3
-       ;;
-esac
-
-:
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          umountnfs
-# Required-Start:    sendsigs
-# Required-Stop:
-# Default-Start:     6
-# Default-Stop:
-# Short-Description: Unmount all network filesystems except the root file system.
-# Description:       Also unmounts all virtual filesystems (proc, devfs, devpts,
-#                    usbfs, sysfs) that are not mounted at the top level.
-### END INIT INFO
-
-PATH=/usr/sbin:/usr/bin:/sbin:/bin
-KERNEL="$(uname -s)"
-RELEASE="$(uname -r)"
-. /lib/init/vars.sh
-
-. /lib/lsb/init-functions
-
-case "${KERNEL}:${RELEASE}" in
-  Linux:[01].*|Linux:2.[01].*)
-       FLAGS=""
-       ;;
-  Linux:2.[23].*|Linux:2.4.?|Linux:2.4.?-*|Linux:2.4.10|Linux:2.4.10-*)
-       FLAGS="-f"
-       ;;
-  *)
-       FLAGS="-f -l"
-       ;;
-esac
-
-do_stop () {
-       # Write a reboot record to /var/log/wtmp before unmounting
-       halt -w
-
-       # Remove bootclean flag files (precaution against symlink attacks)
-       rm -f /tmp/.clean /var/lock/.clean /var/run/.clean
-
-       [ "$VERBOSE" = no ] || log_action_begin_msg "Unmounting remote and non-toplevel virtual filesystems"
-
-       #
-       # Make list of points to unmount in reverse order of their creation
-       #
-
-       exec 9<&0 </proc/mounts
-
-       DIRS=""
-       while read DEV MTPT FSTYPE REST
-       do
-               case "$MTPT" in
-                 /|/proc|/dev|/dev/pts|/dev/shm|/proc/*|/sys|/var/run|/var/lock)
-                       continue
-                       ;;
-               esac
-               case "$FSTYPE" in
-                 nfs|nfs4|smbfs|ncp|ncpfs|cifs|coda|ocfs2|gfs)
-                       DIRS="$MTPT $DIRS"
-                       ;;
-                 proc|procfs|linprocfs|devfs|devpts|usbfs|usbdevfs|sysfs)
-                       DIRS="$MTPT $DIRS"
-                       ;;
-               esac
-       done
-
-       exec 0<&9 9<&-
-
-       if [ "$DIRS" ]
-       then
-               umount $FLAGS $DIRS
-       fi
-       ES=$?
-
-       [ "$VERBOSE" = no ] || log_action_end_msg $ES
-}
+def inputiter():
+    if os.isatty(sys.stdin.fileno()):
+        while 1:
+            try:
+                yield raw_input('bup> ')
+            except EOFError:
+                break
+    else:
+        for line in sys.stdin:
+            yield line
+
+
+def _completer_get_subs(line):
+    (qtype, lastword) = shquote.unfinished_word(line)
+    (dir,name) = os.path.split(lastword)
+    #log('\ncompleter: %r %r %r\n' % (qtype, lastword, text))
+    n = pwd.resolve(dir)
+    subs = list(filter(lambda x: x.name.startswith(name),
+                       n.subs()))
+    return (dir, name, qtype, lastword, subs)
+
+
+_last_line = None
+_last_res = None
+def completer(text, state):
+    global _last_line
+    global _last_res
+    try:
+        line = readline.get_line_buffer()[:readline.get_endidx()]
+        if _last_line != line:
+            _last_res = _completer_get_subs(line)
+            _last_line = line
+        (dir, name, qtype, lastword, subs) = _last_res
+        if state < len(subs):
+            sn = subs[state]
+            sn1 = sn.resolve('')  # deref symlinks
+            fullname = os.path.join(dir, sn.name)
+            if stat.S_ISDIR(sn1.mode):
+                ret = shquote.what_to_add(qtype, lastword, fullname+'/',
+                                          terminate=False)
+            else:
+                ret = shquote.what_to_add(qtype, lastword, fullname,
+                                          terminate=True) + ' '
+            return text + ret
+    except Exception, e:
+        log('\nerror in completion: %s\n' % e)
+
+            
+optspec = """
+bup ftp
+"""
+o = options.Options('bup ftp', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+git.check_repo_or_die()
+
+top = vfs.RefList(None)
+pwd = top
+
+if extra:
+    lines = extra
+else:
+    readline.set_completer_delims(' \t\n\r/')
+    readline.set_completer(completer)
+    readline.parse_and_bind("tab: complete")
+    lines = inputiter()
+
+for line in lines:
+    if not line.strip():
+        continue
+    words = [word for (wordstart,word) in shquote.quotesplit(line)]
+    cmd = words[0].lower()
+    #log('execute: %r %r\n' % (cmd, parm))
+    try:
+        if cmd == 'ls':
+            for parm in (words[1:] or ['.']):
+                do_ls(parm, pwd.resolve(parm))
+        elif cmd == 'cd':
+            for parm in words[1:]:
+                pwd = pwd.resolve(parm)
+        elif cmd == 'pwd':
+            print pwd.fullname()
+        elif cmd == 'cat':
+            for parm in words[1:]:
+                write_to_file(pwd.resolve(parm).open(), sys.stdout)
+        elif cmd == 'get':
+            if len(words) not in [2,3]:
+                raise Exception('Usage: get <filename> [localname]')
+            rname = words[1]
+            (dir,base) = os.path.split(rname)
+            lname = len(words)>2 and words[2] or base
+            inf = pwd.resolve(rname).open()
+            log('Saving %r\n' % lname)
+            write_to_file(inf, open(lname, 'wb'))
+        elif cmd == 'mget':
+            for parm in words[1:]:
+                (dir,base) = os.path.split(parm)
+                for n in pwd.resolve(dir).subs():
+                    if fnmatch.fnmatch(n.name, base):
+                        try:
+                            log('Saving %r\n' % n.name)
+                            inf = n.open()
+                            outf = open(n.name, 'wb')
+                            write_to_file(inf, outf)
+                            outf.close()
+                        except Exception, e:
+                            log('  error: %s\n' % e)
+        elif cmd == 'help' or cmd == '?':
+            log('Commands: ls cd pwd cat get mget help quit\n')
+        elif cmd == 'quit' or cmd == 'exit' or cmd == 'bye':
+            break
+        else:
+            raise Exception('no such command %r' % cmd)
+    except Exception, e:
+        log('error: %s\n' % e)
+        #raise
+#!/usr/bin/env python
+import sys, mmap
+from bup import options, _hashsplit
+from bup.helpers import *
+
+optspec = """
+bup random [-S seed] <numbytes>
+--
+S,seed=   optional random number seed (default 1)
+f,force   print random data to stdout even if it's a tty
+"""
+o = options.Options('bup random', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if len(extra) != 1:
+    o.fatal("exactly one argument expected")
+
+total = parse_num(extra[0])
+
+if opt.force or (not os.isatty(1) and
+                 not atoi(os.environ.get('BUP_FORCE_TTY')) & 1):
+    _hashsplit.write_random(sys.stdout.fileno(), total, opt.seed or 0)
+else:
+    log('error: not writing binary data to a terminal. Use -f to force.\n')
+    sys.exit(1)
+#!/usr/bin/env python
+import sys, os, glob
+from bup import options
+
+optspec = """
+bup help <command>
+"""
+o = options.Options('bup help', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if len(extra) == 0:
+    # the wrapper program provides the default usage string
+    os.execvp(os.environ['BUP_MAIN_EXE'], ['bup'])
+elif len(extra) == 1:
+    docname = (extra[0]=='bup' and 'bup' or ('bup-%s' % extra[0]))
+    exe = sys.argv[0]
+    (exepath, exefile) = os.path.split(exe)
+    manpath = os.path.join(exepath, '../Documentation/' + docname + '.[1-9]')
+    g = glob.glob(manpath)
+    if g:
+        os.execvp('man', ['man', '-l', g[0]])
+    else:
+        os.execvp('man', ['man', docname])
+else:
+    o.fatal("exactly one command name expected")
+#!/usr/bin/env python
+import sys, os, stat, errno, fuse, re, time, tempfile
+from bup import options, git, vfs
+from bup.helpers import *
+
+
+class Stat(fuse.Stat):
+    def __init__(self):
+        self.st_mode = 0
+        self.st_ino = 0
+        self.st_dev = 0
+        self.st_nlink = 0
+        self.st_uid = 0
+        self.st_gid = 0
+        self.st_size = 0
+        self.st_atime = 0
+        self.st_mtime = 0
+        self.st_ctime = 0
+        self.st_blocks = 0
+        self.st_blksize = 0
+        self.st_rdev = 0
+
+
+cache = {}
+def cache_get(top, path):
+    parts = path.split('/')
+    cache[('',)] = top
+    c = None
+    max = len(parts)
+    #log('cache: %r\n' % cache.keys())
+    for i in range(max):
+        pre = parts[:max-i]
+        #log('cache trying: %r\n' % pre)
+        c = cache.get(tuple(pre))
+        if c:
+            rest = parts[max-i:]
+            for r in rest:
+                #log('resolving %r from %r\n' % (r, c.fullname()))
+                c = c.lresolve(r)
+                key = tuple(pre + [r])
+                #log('saving: %r\n' % (key,))
+                cache[key] = c
+            break
+    assert(c)
+    return c
+        
+    
 
-case "$1" in
-  start)
-       # No-op
-       ;;
-  restart|reload|force-reload)
-       echo "Error: argument '$1' not supported" >&2
-       exit 3
-       ;;
-  stop|"")
-       do_stop
-       ;;
-  *)
-       echo "Usage: umountnfs.sh [start|stop]" >&2
-       exit 3
-       ;;
-esac
-
-:
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          umountroot
-# Required-Start:    umountfs
-# Required-Stop:     umountfs
-# Default-Start:     6
-# Default-Stop:
-# Short-Description: Mount the root filesystem read-only.
-### END INIT INFO
-
-PATH=/sbin:/bin
-. /lib/init/vars.sh
-
-. /lib/lsb/init-functions
-
-remount_ro () {
-       local MTPT=$1
-       [ "$VERBOSE" = no ] || log_action_begin_msg "Mounting $MTPT filesystem read-only"
-       MOUNT_FORCE_OPT=
-       [ "$(uname -s)" = "GNU/kFreeBSD" ] && MOUNT_FORCE_OPT=-f
-       # This:
-       #     mount -n -o remount,ro /
-       # will act on a bind mount of / if there is one.
-       # See #339023 and the comment in checkroot.sh
-       mount    $MOUNT_FORCE_OPT -n -o remount,ro -t dummytype dummydev $MTPT 2>/dev/null \
-       || mount $MOUNT_FORCE_OPT -n -o remount,ro              dummydev $MTPT 2>/dev/null \
-       || mount $MOUNT_FORCE_OPT -n -o remount,ro                       $MTPT
-       ES=$?
-       [ "$VERBOSE" = no ] || log_action_end_msg $ES
-}
+class BupFs(fuse.Fuse):
+    def __init__(self, top):
+        fuse.Fuse.__init__(self)
+        self.top = top
+    
+    def getattr(self, path):
+        log('--getattr(%r)\n' % path)
+        try:
+            node = cache_get(self.top, path)
+            st = Stat()
+            st.st_mode = node.mode
+            st.st_nlink = node.nlinks()
+            st.st_size = node.size()
+            st.st_mtime = node.mtime
+            st.st_ctime = node.ctime
+            st.st_atime = node.atime
+            return st
+        except vfs.NoSuchFile:
+            return -errno.ENOENT
+
+    def readdir(self, path, offset):
+        log('--readdir(%r)\n' % path)
+        node = cache_get(self.top, path)
+        yield fuse.Direntry('.')
+        yield fuse.Direntry('..')
+        for sub in node.subs():
+            yield fuse.Direntry(sub.name)
+
+    def readlink(self, path):
+        log('--readlink(%r)\n' % path)
+        node = cache_get(self.top, path)
+        return node.readlink()
+
+    def open(self, path, flags):
+        log('--open(%r)\n' % path)
+        node = cache_get(self.top, path)
+        accmode = os.O_RDONLY | os.O_WRONLY | os.O_RDWR
+        if (flags & accmode) != os.O_RDONLY:
+            return -errno.EACCES
+        node.open()
+
+    def release(self, path, flags):
+        log('--release(%r)\n' % path)
+
+    def read(self, path, size, offset):
+        log('--read(%r)\n' % path)
+        n = cache_get(self.top, path)
+        o = n.open()
+        o.seek(offset)
+        return o.read(size)
+
+
+if not hasattr(fuse, '__version__'):
+    raise RuntimeError, "your fuse module is too old for fuse.__version__"
+fuse.fuse_python_api = (0, 2)
+
+
+optspec = """
+bup fuse [-d] [-f] <mountpoint>
+--
+d,debug   increase debug level
+f,foreground  run in foreground
+"""
+o = options.Options('bup fuse', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if len(extra) != 1:
+    o.fatal("exactly one argument expected")
+
+git.check_repo_or_die()
+top = vfs.RefList(None)
+f = BupFs(top)
+f.fuse_args.mountpoint = extra[0]
+if opt.debug:
+    f.fuse_args.add('debug')
+if opt.foreground:
+    f.fuse_args.setmod('foreground')
+print f.multithreaded
+f.multithreaded = False
+
+f.main()
+#!/usr/bin/env python
+from bup import git, options, client
+from bup.helpers import *
+
+optspec = """
+[BUP_DIR=...] bup init [-r host:path]
+--
+r,remote=  remote repository path
+"""
+o = options.Options('bup init', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if extra:
+    o.fatal("no arguments expected")
+
+
+if opt.remote:
+    git.init_repo()  # local repo
+    git.check_repo_or_die()
+    cli = client.Client(opt.remote, create=True)
+    cli.close()
+else:
+    git.init_repo()
+#!/usr/bin/env python
+import sys, math, struct, glob
+from bup import options, git
+from bup.helpers import *
+
+PAGE_SIZE=4096
+SHA_PER_PAGE=PAGE_SIZE/200.
+
+
+def merge(idxlist, bits, table):
+    count = 0
+    for e in git.idxmerge(idxlist):
+        count += 1
+        prefix = git.extract_bits(e, bits)
+        table[prefix] = count
+        yield e
+
+
+def do_midx(outdir, outfilename, infilenames):
+    if not outfilename:
+        assert(outdir)
+        sum = Sha1('\0'.join(infilenames)).hexdigest()
+        outfilename = '%s/midx-%s.midx' % (outdir, sum)
+    
+    inp = []
+    total = 0
+    for name in infilenames:
+        ix = git.PackIdx(name)
+        inp.append(ix)
+        total += len(ix)
+
+    log('Merging %d indexes (%d objects).\n' % (len(infilenames), total))
+    if (not opt.force and (total < 1024 and len(infilenames) < 3)) \
+       or (opt.force and not total):
+        log('midx: nothing to do.\n')
+        return
+
+    pages = int(total/SHA_PER_PAGE) or 1
+    bits = int(math.ceil(math.log(pages, 2)))
+    entries = 2**bits
+    log('Table size: %d (%d bits)\n' % (entries*4, bits))
+    
+    table = [0]*entries
+
+    try:
+        os.unlink(outfilename)
+    except OSError:
+        pass
+    f = open(outfilename + '.tmp', 'w+')
+    f.write('MIDX\0\0\0\2')
+    f.write(struct.pack('!I', bits))
+    assert(f.tell() == 12)
+    f.write('\0'*4*entries)
+    
+    for e in merge(inp, bits, table):
+        f.write(e)
+        
+    f.write('\0'.join(os.path.basename(p) for p in infilenames))
+
+    f.seek(12)
+    f.write(struct.pack('!%dI' % entries, *table))
+    f.close()
+    os.rename(outfilename + '.tmp', outfilename)
+
+    # this is just for testing
+    if 0:
+        p = git.PackMidx(outfilename)
+        assert(len(p.idxnames) == len(infilenames))
+        print p.idxnames
+        assert(len(p) == total)
+        pi = iter(p)
+        for i in merge(inp, total, bits, table):
+            assert(i == pi.next())
+            assert(p.exists(i))
+
+    print outfilename
+
+optspec = """
+bup midx [options...] <idxnames...>
+--
+o,output=  output midx filename (default: auto-generated)
+a,auto     automatically create .midx from any unindexed .idx files
+f,force    automatically create .midx from *all* .idx files
+"""
+o = options.Options('bup midx', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if extra and (opt.auto or opt.force):
+    o.fatal("you can't use -f/-a and also provide filenames")
+
+git.check_repo_or_die()
+
+if extra:
+    do_midx(git.repo('objects/pack'), opt.output, extra)
+elif opt.auto or opt.force:
+    paths = [git.repo('objects/pack')]
+    paths += glob.glob(git.repo('index-cache/*/.'))
+    for path in paths:
+        log('midx: scanning %s\n' % path)
+        if opt.force:
+            do_midx(path, opt.output, glob.glob('%s/*.idx' % path))
+        elif opt.auto:
+            m = git.PackIdxList(path)
+            needed = {}
+            for pack in m.packs:  # only .idx files without a .midx are open
+                if pack.name.endswith('.idx'):
+                    needed[pack.name] = 1
+            del m
+            do_midx(path, opt.output, needed.keys())
+        log('\n')
+else:
+    o.fatal("you must use -f or -a or provide input filenames")
+#!/usr/bin/env python
+import sys, os, random
+from bup import options
+from bup.helpers import *
+
+
+def randblock(n):
+    l = []
+    for i in xrange(n):
+        l.append(chr(random.randrange(0,256)))
+    return ''.join(l)
+
+
+optspec = """
+bup damage [-n count] [-s maxsize] [-S seed] <filenames...>
+--
+   WARNING: THIS COMMAND IS EXTREMELY DANGEROUS
+n,num=   number of blocks to damage
+s,size=  maximum size of each damaged block
+percent= maximum size of each damaged block (as a percent of entire file)
+equal    spread damage evenly throughout the file
+S,seed=  random number seed (for repeatable tests)
+"""
+o = options.Options('bup damage', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if not extra:
+    o.fatal('filenames expected')
+
+if opt.seed != None:
+    random.seed(opt.seed)
+
+for name in extra:
+    log('Damaging "%s"...\n' % name)
+    f = open(name, 'r+b')
+    st = os.fstat(f.fileno())
+    size = st.st_size
+    if opt.percent or opt.size:
+        ms1 = int(float(opt.percent or 0)/100.0*size) or size
+        ms2 = opt.size or size
+        maxsize = min(ms1, ms2)
+    else:
+        maxsize = 1
+    chunks = opt.num or 10
+    chunksize = size/chunks
+    for r in range(chunks):
+        sz = random.randrange(1, maxsize+1)
+        if sz > size:
+            sz = size
+        if opt.equal:
+            ofs = r*chunksize
+        else:
+            ofs = random.randrange(0, size - sz + 1)
+        log('  %6d bytes at %d\n' % (sz, ofs))
+        f.seek(ofs)
+        f.write(randblock(sz))
+    f.close()
+#!/usr/bin/env python
+import sys, struct, mmap
+from bup import options, git
+from bup.helpers import *
+
+suspended_w = None
+
+
+def init_dir(conn, arg):
+    git.init_repo(arg)
+    log('bup server: bupdir initialized: %r\n' % git.repodir)
+    conn.ok()
+
+
+def set_dir(conn, arg):
+    git.check_repo_or_die(arg)
+    log('bup server: bupdir is %r\n' % git.repodir)
+    conn.ok()
 
-do_stop () {
-       # These directories must exist on the root filesystem as they are
-       # targets for system mountpoints.  We've just unmounted all other
-       # filesystems, so either they are mounted now (in which case the
-       # mount point exists) or we can make the mountpoint.
-       for dir in /proc /sys /var/run /var/lock; do
-           mkdir -p $dir || true
-       done
-       exec 9<&0 < /proc/mounts
-
-       REG_MTPTS=""
-       TMPFS_MTPTS=""
-       while read DEV MTPT FSTYPE REST
-       do
-               case "$MTPT" in
-                 /proc|/dev|/.dev|/dev/pts|/dev/shm|/proc/*|/sys|/var/run|/var/lock)
-                       continue
-                       ;;
-               esac
-               case "$FSTYPE" in 
-                 proc|procfs|linprocfs|devfs|sysfs|usbfs|usbdevfs|devpts|tmpfs)
-                       continue
-                       ;;
-                 *)
-                       remount_ro $MTPT
-                       ;;
-               esac
-       done
-
-       exec 0<&9 9<&-
+    
+def list_indexes(conn, junk):
+    git.check_repo_or_die()
+    for f in os.listdir(git.repo('objects/pack')):
+        if f.endswith('.idx'):
+            conn.write('%s\n' % f)
+    conn.ok()
+
+
+def send_index(conn, name):
+    git.check_repo_or_die()
+    assert(name.find('/') < 0)
+    assert(name.endswith('.idx'))
+    idx = git.PackIdx(git.repo('objects/pack/%s' % name))
+    conn.write(struct.pack('!I', len(idx.map)))
+    conn.write(idx.map)
+    conn.ok()
+
+
+def receive_objects(conn, junk):
+    global suspended_w
+    git.check_repo_or_die()
+    suggested = {}
+    if suspended_w:
+        w = suspended_w
+        suspended_w = None
+    else:
+        w = git.PackWriter()
+    while 1:
+        ns = conn.read(4)
+        if not ns:
+            w.abort()
+            raise Exception('object read: expected length header, got EOF\n')
+        n = struct.unpack('!I', ns)[0]
+        #log('expecting %d bytes\n' % n)
+        if not n:
+            log('bup server: received %d object%s.\n' 
+                % (w.count, w.count!=1 and "s" or ''))
+            fullpath = w.close()
+            if fullpath:
+                (dir, name) = os.path.split(fullpath)
+                conn.write('%s.idx\n' % name)
+            conn.ok()
+            return
+        elif n == 0xffffffff:
+            log('bup server: receive-objects suspended.\n')
+            suspended_w = w
+            conn.ok()
+            return
+            
+        buf = conn.read(n)  # object sizes in bup are reasonably small
+        #log('read %d bytes\n' % n)
+        if len(buf) < n:
+            w.abort()
+            raise Exception('object read: expected %d bytes, got %d\n'
+                            % (n, len(buf)))
+        (type, content) = git._decode_packobj(buf)
+        sha = git.calc_hash(type, content)
+        oldpack = w.exists(sha)
+        # FIXME: we only suggest a single index per cycle, because the client
+        # is currently dumb to download more than one per cycle anyway.
+        # Actually we should fix the client, but this is a minor optimization
+        # on the server side.
+        if not suggested and \
+          oldpack and (oldpack == True or oldpack.endswith('.midx')):
+            # FIXME: we shouldn't really have to know about midx files
+            # at this layer.  But exists() on a midx doesn't return the
+            # packname (since it doesn't know)... probably we should just
+            # fix that deficiency of midx files eventually, although it'll
+            # make the files bigger.  This method is certainly not very
+            # efficient.
+            w.objcache.refresh(skip_midx = True)
+            oldpack = w.objcache.exists(sha)
+            log('new suggestion: %r\n' % oldpack)
+            assert(oldpack)
+            assert(oldpack != True)
+            assert(not oldpack.endswith('.midx'))
+            w.objcache.refresh(skip_midx = False)
+        if not suggested and oldpack:
+            assert(oldpack.endswith('.idx'))
+            (dir,name) = os.path.split(oldpack)
+            if not (name in suggested):
+                log("bup server: suggesting index %s\n" % name)
+                conn.write('index %s\n' % name)
+                suggested[name] = 1
+        else:
+            w._raw_write([buf])
+    # NOTREACHED
+
+
+def read_ref(conn, refname):
+    git.check_repo_or_die()
+    r = git.read_ref(refname)
+    conn.write('%s\n' % (r or '').encode('hex'))
+    conn.ok()
+
+
+def update_ref(conn, refname):
+    git.check_repo_or_die()
+    newval = conn.readline().strip()
+    oldval = conn.readline().strip()
+    git.update_ref(refname, newval.decode('hex'), oldval.decode('hex'))
+    conn.ok()
+
+
+def cat(conn, id):
+    git.check_repo_or_die()
+    try:
+        for blob in git.cat(id):
+            conn.write(struct.pack('!I', len(blob)))
+            conn.write(blob)
+    except KeyError, e:
+        log('server: error: %s\n' % e)
+        conn.write('\0\0\0\0')
+        conn.error(e)
+    else:
+        conn.write('\0\0\0\0')
+        conn.ok()
+
+
+optspec = """
+bup server
+"""
+o = options.Options('bup server', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if extra:
+    o.fatal('no arguments expected')
+
+log('bup server: reading from stdin.\n')
+
+commands = {
+    'init-dir': init_dir,
+    'set-dir': set_dir,
+    'list-indexes': list_indexes,
+    'send-index': send_index,
+    'receive-objects': receive_objects,
+    'read-ref': read_ref,
+    'update-ref': update_ref,
+    'cat': cat,
 }
 
-case "$1" in
-  start)
-       # No-op
-       ;;
-  restart|reload|force-reload)
-       echo "Error: argument '$1' not supported" >&2
-       exit 3
-       ;;
-  stop)
-       do_stop
-       ;;
-  *)
-       echo "Usage: $0 start|stop" >&2
-       exit 3
-       ;;
-esac
-
-:
-#! /bin/sh
-#
-# skeleton     example file to build /etc/init.d/ scripts.
-#              This file should be used to construct scripts for /etc/init.d.
-#
-#              Written by Miquel van Smoorenburg <miquels@cistron.nl>.
-#              Modified for Debian 
-#              by Ian Murdock <imurdock@gnu.ai.mit.edu>.
+# FIXME: this protocol is totally lame and not at all future-proof.
+# (Especially since we abort completely as soon as *anything* bad happens)
+conn = Conn(sys.stdin, sys.stdout)
+lr = linereader(conn)
+for _line in lr:
+    line = _line.strip()
+    if not line:
+        continue
+    log('bup server: command: %r\n' % line)
+    words = line.split(' ', 1)
+    cmd = words[0]
+    rest = len(words)>1 and words[1] or ''
+    if cmd == 'quit':
+        break
+    else:
+        cmd = commands.get(cmd)
+        if cmd:
+            cmd(conn, rest)
+        else:
+            raise Exception('unknown server command: %r\n' % line)
+
+log('bup server: done\n')
+#!/usr/bin/env python
+import sys, time, struct
+from bup import hashsplit, git, options, client
+from bup.helpers import *
+from subprocess import PIPE
+
+
+optspec = """
+bup join [-r host:path] [refs or hashes...]
+--
+r,remote=  remote repository path
+"""
+o = options.Options('bup join', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+git.check_repo_or_die()
+
+if not extra:
+    extra = linereader(sys.stdin)
+
+ret = 0
+
+if opt.remote:
+    cli = client.Client(opt.remote)
+    cat = cli.cat
+else:
+    cp = git.CatPipe()
+    cat = cp.join
+
+for id in extra:
+    try:
+        for blob in cat(id):
+            sys.stdout.write(blob)
+    except KeyError, e:
+        sys.stdout.flush()
+        log('error: %s\n' % e)
+        ret = 1
+
+sys.exit(ret)
+#!/usr/bin/env python
+import sys, re, errno, stat, time, math
+from bup import hashsplit, git, options, index, client
+from bup.helpers import *
+
+
+optspec = """
+bup save [-tc] [-n name] <filenames...>
+--
+r,remote=  remote repository path
+t,tree     output a tree id
+c,commit   output a commit id
+n,name=    name of backup set to update (if any)
+v,verbose  increase log output (can be used more than once)
+q,quiet    don't show progress meter
+smaller=   only back up files smaller than n bytes
+"""
+o = options.Options('bup save', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+git.check_repo_or_die()
+if not (opt.tree or opt.commit or opt.name):
+    o.fatal("use one or more of -t, -c, -n")
+if not extra:
+    o.fatal("no filenames given")
+
+opt.progress = (istty and not opt.quiet)
+opt.smaller = parse_num(opt.smaller or 0)
+
+is_reverse = os.environ.get('BUP_SERVER_REVERSE')
+if is_reverse and opt.remote:
+    o.fatal("don't use -r in reverse mode; it's automatic")
+
+refname = opt.name and 'refs/heads/%s' % opt.name or None
+if opt.remote or is_reverse:
+    cli = client.Client(opt.remote)
+    oldref = refname and cli.read_ref(refname) or None
+    w = cli.new_packwriter()
+else:
+    cli = None
+    oldref = refname and git.read_ref(refname) or None
+    w = git.PackWriter()
+
+handle_ctrl_c()
+
+
+def eatslash(dir):
+    if dir.endswith('/'):
+        return dir[:-1]
+    else:
+        return dir
+
+
+parts = ['']
+shalists = [[]]
+
+def _push(part):
+    assert(part)
+    parts.append(part)
+    shalists.append([])
+
+def _pop(force_tree):
+    assert(len(parts) >= 1)
+    part = parts.pop()
+    shalist = shalists.pop()
+    tree = force_tree or w.new_tree(shalist)
+    if shalists:
+        shalists[-1].append(('40000', part, tree))
+    else:  # this was the toplevel, so put it back for sanity
+        shalists.append(shalist)
+    return tree
+
+lastremain = None
+def progress_report(n):
+    global count, subcount, lastremain
+    subcount += n
+    cc = count + subcount
+    pct = total and (cc*100.0/total) or 0
+    now = time.time()
+    elapsed = now - tstart
+    kps = elapsed and int(cc/1024./elapsed)
+    kps_frac = 10 ** int(math.log(kps+1, 10) - 1)
+    kps = int(kps/kps_frac)*kps_frac
+    if cc:
+        remain = elapsed*1.0/cc * (total-cc)
+    else:
+        remain = 0.0
+    if (lastremain and (remain > lastremain)
+          and ((remain - lastremain)/lastremain < 0.05)):
+        remain = lastremain
+    else:
+        lastremain = remain
+    hours = int(remain/60/60)
+    mins = int(remain/60 - hours*60)
+    secs = int(remain - hours*60*60 - mins*60)
+    if elapsed < 30:
+        remainstr = ''
+        kpsstr = ''
+    else:
+        kpsstr = '%dk/s' % kps
+        if hours:
+            remainstr = '%dh%dm' % (hours, mins)
+        elif mins:
+            remainstr = '%dm%d' % (mins, secs)
+        else:
+            remainstr = '%ds' % secs
+    progress('Saving: %.2f%% (%d/%dk, %d/%d files) %s %s\r'
+             % (pct, cc/1024, total/1024, fcount, ftotal,
+                remainstr, kpsstr))
+
+
+r = index.Reader(git.repo('bupindex'))
+
+def already_saved(ent):
+    return ent.is_valid() and w.exists(ent.sha) and ent.sha
+
+def wantrecurse_pre(ent):
+    return not already_saved(ent)
+
+def wantrecurse_during(ent):
+    return not already_saved(ent) or ent.sha_missing()
+
+total = ftotal = 0
+if opt.progress:
+    for (transname,ent) in r.filter(extra, wantrecurse=wantrecurse_pre):
+        if not (ftotal % 10024):
+            progress('Reading index: %d\r' % ftotal)
+        exists = ent.exists()
+        hashvalid = already_saved(ent)
+        ent.set_sha_missing(not hashvalid)
+        if not opt.smaller or ent.size < opt.smaller:
+            if exists and not hashvalid:
+                total += ent.size
+        ftotal += 1
+    progress('Reading index: %d, done.\n' % ftotal)
+    hashsplit.progress_callback = progress_report
+
+tstart = time.time()
+count = subcount = fcount = 0
+lastskip_name = None
+lastdir = ''
+for (transname,ent) in r.filter(extra, wantrecurse=wantrecurse_during):
+    (dir, file) = os.path.split(ent.name)
+    exists = (ent.flags & index.IX_EXISTS)
+    hashvalid = already_saved(ent)
+    wasmissing = ent.sha_missing()
+    oldsize = ent.size
+    if opt.verbose:
+        if not exists:
+            status = 'D'
+        elif not hashvalid:
+            if ent.sha == index.EMPTY_SHA:
+                status = 'A'
+            else:
+                status = 'M'
+        else:
+            status = ' '
+        if opt.verbose >= 2:
+            log('%s %-70s\n' % (status, ent.name))
+        elif not stat.S_ISDIR(ent.mode) and lastdir != dir:
+            if not lastdir.startswith(dir):
+                log('%s %-70s\n' % (status, os.path.join(dir, '')))
+            lastdir = dir
+
+    if opt.progress:
+        progress_report(0)
+    fcount += 1
+    
+    if not exists:
+        continue
+    if opt.smaller and ent.size >= opt.smaller:
+        if exists and not hashvalid:
+            add_error('skipping large file "%s"' % ent.name)
+            lastskip_name = ent.name
+        continue
+
+    assert(dir.startswith('/'))
+    dirp = dir.split('/')
+    while parts > dirp:
+        _pop(force_tree = None)
+    if dir != '/':
+        for part in dirp[len(parts):]:
+            _push(part)
+
+    if not file:
+        # no filename portion means this is a subdir.  But
+        # sub/parentdirectories already handled in the pop/push() part above.
+        oldtree = already_saved(ent) # may be None
+        newtree = _pop(force_tree = oldtree)
+        if not oldtree:
+            if lastskip_name and lastskip_name.startswith(ent.name):
+                ent.invalidate()
+            else:
+                ent.validate(040000, newtree)
+            ent.repack()
+        if exists and wasmissing:
+            count += oldsize
+        continue
+
+    # it's not a directory
+    id = None
+    if hashvalid:
+        mode = '%o' % ent.gitmode
+        id = ent.sha
+        shalists[-1].append((mode, 
+                             git.mangle_name(file, ent.mode, ent.gitmode),
+                             id))
+    else:
+        if stat.S_ISREG(ent.mode):
+            try:
+                f = hashsplit.open_noatime(ent.name)
+            except IOError, e:
+                add_error(e)
+                lastskip_name = ent.name
+            except OSError, e:
+                add_error(e)
+                lastskip_name = ent.name
+            else:
+                (mode, id) = hashsplit.split_to_blob_or_tree(w, [f])
+        else:
+            if stat.S_ISDIR(ent.mode):
+                assert(0)  # handled above
+            elif stat.S_ISLNK(ent.mode):
+                try:
+                    rl = os.readlink(ent.name)
+                except OSError, e:
+                    add_error(e)
+                    lastskip_name = ent.name
+                except IOError, e:
+                    add_error(e)
+                    lastskip_name = ent.name
+                else:
+                    (mode, id) = ('120000', w.new_blob(rl))
+            else:
+                add_error(Exception('skipping special file "%s"' % ent.name))
+                lastskip_name = ent.name
+        if id:
+            ent.validate(int(mode, 8), id)
+            ent.repack()
+            shalists[-1].append((mode,
+                                 git.mangle_name(file, ent.mode, ent.gitmode),
+                                 id))
+    if exists and wasmissing:
+        count += oldsize
+        subcount = 0
+
+
+if opt.progress:
+    pct = total and count*100.0/total or 100
+    progress('Saving: %.2f%% (%d/%dk, %d/%d files), done.    \n'
+             % (pct, count/1024, total/1024, fcount, ftotal))
+
+while len(parts) > 1:
+    _pop(force_tree = None)
+assert(len(shalists) == 1)
+tree = w.new_tree(shalists[-1])
+if opt.tree:
+    print tree.encode('hex')
+if opt.commit or opt.name:
+    msg = 'bup save\n\nGenerated by command:\n%r' % sys.argv
+    ref = opt.name and ('refs/heads/%s' % opt.name) or None
+    commit = w.new_commit(oldref, tree, msg)
+    if opt.commit:
+        print commit.encode('hex')
+
+w.close()  # must close before we can update the ref
+        
+if opt.name:
+    if cli:
+        cli.update_ref(refname, commit, oldref)
+    else:
+        git.update_ref(refname, commit, oldref)
+
+if cli:
+    cli.close()
+
+if saved_errors:
+    log('WARNING: %d errors encountered while saving.\n' % len(saved_errors))
+    sys.exit(1)
+#!/usr/bin/env python
+import sys, time
+from bup import options
+
+optspec = """
+bup tick
+"""
+o = options.Options('bup tick', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if extra:
+    o.fatal("no arguments expected")
+
+t = time.time()
+tleft = 1 - (t - int(t))
+time.sleep(tleft)
+#!/usr/bin/env python
+import os, sys, stat, time
+from bup import options, git, index, drecurse
+from bup.helpers import *
+
+
+def merge_indexes(out, r1, r2):
+    for e in index.MergeIter([r1, r2]):
+        # FIXME: shouldn't we remove deleted entries eventually?  When?
+        out.add_ixentry(e)
+
+
+class IterHelper:
+    def __init__(self, l):
+        self.i = iter(l)
+        self.cur = None
+        self.next()
+
+    def next(self):
+        try:
+            self.cur = self.i.next()
+        except StopIteration:
+            self.cur = None
+        return self.cur
+
+
+def check_index(reader):
+    try:
+        log('check: checking forward iteration...\n')
+        e = None
+        d = {}
+        for e in reader.forward_iter():
+            if e.children_n:
+                if opt.verbose:
+                    log('%08x+%-4d %r\n' % (e.children_ofs, e.children_n,
+                                            e.name))
+                assert(e.children_ofs)
+                assert(e.name.endswith('/'))
+                assert(not d.get(e.children_ofs))
+                d[e.children_ofs] = 1
+            if e.flags & index.IX_HASHVALID:
+                assert(e.sha != index.EMPTY_SHA)
+                assert(e.gitmode)
+        assert(not e or e.name == '/')  # last entry is *always* /
+        log('check: checking normal iteration...\n')
+        last = None
+        for e in reader:
+            if last:
+                assert(last > e.name)
+            last = e.name
+    except:
+        log('index error! at %r\n' % e)
+        raise
+    log('check: passed.\n')
+
+
+def update_index(top):
+    ri = index.Reader(indexfile)
+    wi = index.Writer(indexfile)
+    rig = IterHelper(ri.iter(name=top))
+    tstart = int(time.time())
+
+    hashgen = None
+    if opt.fake_valid:
+        def hashgen(name):
+            return (0100644, index.FAKE_SHA)
+
+    total = 0
+    for (path,pst) in drecurse.recursive_dirlist([top], xdev=opt.xdev):
+        if opt.verbose>=2 or (opt.verbose==1 and stat.S_ISDIR(pst.st_mode)):
+            sys.stdout.write('%s\n' % path)
+            sys.stdout.flush()
+            progress('Indexing: %d\r' % total)
+        elif not (total % 128):
+            progress('Indexing: %d\r' % total)
+        total += 1
+        while rig.cur and rig.cur.name > path:  # deleted paths
+            if rig.cur.exists():
+                rig.cur.set_deleted()
+                rig.cur.repack()
+            rig.next()
+        if rig.cur and rig.cur.name == path:    # paths that already existed
+            if pst:
+                rig.cur.from_stat(pst, tstart)
+            if not (rig.cur.flags & index.IX_HASHVALID):
+                if hashgen:
+                    (rig.cur.gitmode, rig.cur.sha) = hashgen(path)
+                    rig.cur.flags |= index.IX_HASHVALID
+            if opt.fake_invalid:
+                rig.cur.invalidate()
+            rig.cur.repack()
+            rig.next()
+        else:  # new paths
+            wi.add(path, pst, hashgen = hashgen)
+    progress('Indexing: %d, done.\n' % total)
+    
+    if ri.exists():
+        ri.save()
+        wi.flush()
+        if wi.count:
+            wr = wi.new_reader()
+            if opt.check:
+                log('check: before merging: oldfile\n')
+                check_index(ri)
+                log('check: before merging: newfile\n')
+                check_index(wr)
+            mi = index.Writer(indexfile)
+            merge_indexes(mi, ri, wr)
+            ri.close()
+            mi.close()
+            wr.close()
+        wi.abort()
+    else:
+        wi.close()
+
+
+optspec = """
+bup index <-p|m|u> [options...] <filenames...>
+--
+p,print    print the index entries for the given names (also works with -u)
+m,modified print only added/deleted/modified files (implies -p)
+s,status   print each filename with a status char (A/M/D) (implies -p)
+H,hash     print the hash for each object next to its name (implies -p)
+l,long     print more information about each file
+u,update   (recursively) update the index entries for the given filenames
+x,xdev,one-file-system  don't cross filesystem boundaries
+fake-valid mark all index entries as up-to-date even if they aren't
+fake-invalid mark all index entries as invalid
+check      carefully check index file integrity
+f,indexfile=  the name of the index file (default 'index')
+v,verbose  increase log output (can be used more than once)
+"""
+o = options.Options('bup index', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if not (opt.modified or opt['print'] or opt.status or opt.update or opt.check):
+    o.fatal('supply one or more of -p, -s, -m, -u, or --check')
+if (opt.fake_valid or opt.fake_invalid) and not opt.update:
+    o.fatal('--fake-{in,}valid are meaningless without -u')
+if opt.fake_valid and opt.fake_invalid:
+    o.fatal('--fake-valid is incompatible with --fake-invalid')
+
+git.check_repo_or_die()
+indexfile = opt.indexfile or git.repo('bupindex')
+
+handle_ctrl_c()
+
+if opt.check:
+    log('check: starting initial check.\n')
+    check_index(index.Reader(indexfile))
+
+paths = index.reduce_paths(extra)
+
+if opt.update:
+    if not paths:
+        o.fatal('update (-u) requested but no paths given')
+    for (rp,path) in paths:
+        update_index(rp)
+
+if opt['print'] or opt.status or opt.modified:
+    for (name, ent) in index.Reader(indexfile).filter(extra or ['']):
+        if (opt.modified 
+            and (ent.is_valid() or ent.is_deleted() or not ent.mode)):
+            continue
+        line = ''
+        if opt.status:
+            if ent.is_deleted():
+                line += 'D '
+            elif not ent.is_valid():
+                if ent.sha == index.EMPTY_SHA:
+                    line += 'A '
+                else:
+                    line += 'M '
+            else:
+                line += '  '
+        if opt.hash:
+            line += ent.sha.encode('hex') + ' '
+        if opt.long:
+            line += "%7s %7s " % (oct(ent.mode), oct(ent.gitmode))
+        print line + (name or './')
+
+if opt.check and (opt['print'] or opt.status or opt.modified or opt.update):
+    log('check: starting final check.\n')
+    check_index(index.Reader(indexfile))
+
+if saved_errors:
+    log('WARNING: %d errors encountered.\n' % len(saved_errors))
+    sys.exit(1)
+#!/usr/bin/env python
+import sys, os, struct
+from bup import options, helpers
+
+optspec = """
+bup rbackup-server
+--
+    This command is not intended to be run manually.
+"""
+o = options.Options('bup rbackup-server', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+if extra:
+    o.fatal('no arguments expected')
+
+# get the subcommand's argv.
+# Normally we could just pass this on the command line, but since we'll often
+# be getting called on the other end of an ssh pipe, which tends to mangle
+# argv (by sending it via the shell), this way is much safer.
+buf = sys.stdin.read(4)
+sz = struct.unpack('!I', buf)[0]
+assert(sz > 0)
+assert(sz < 1000000)
+buf = sys.stdin.read(sz)
+assert(len(buf) == sz)
+argv = buf.split('\0')
+
+# stdin/stdout are supposedly connected to 'bup server' that the caller
+# started for us (often on the other end of an ssh tunnel), so we don't want
+# to misuse them.  Move them out of the way, then replace stdout with
+# a pointer to stderr in case our subcommand wants to do something with it.
 #
-# Version:     @(#)skeleton  1.9  26-Feb-2001  miquels@cistron.nl
+# It might be nice to do the same with stdin, but my experiments showed that
+# ssh seems to make its child's stderr a readable-but-never-reads-anything
+# socket.  They really should have used shutdown(SHUT_WR) on the other end
+# of it, but probably didn't.  Anyway, it's too messy, so let's just make sure
+# anyone reading from stdin is disappointed.
 #
+# (You can't just leave stdin/stdout "not open" by closing the file
+# descriptors.  Then the next file that opens is automatically assigned 0 or 1,
+# and people *trying* to read/write stdin/stdout get screwed.)
+os.dup2(0, 3)
+os.dup2(1, 4)
+os.dup2(2, 1)
+fd = os.open('/dev/null', os.O_RDONLY)
+os.dup2(fd, 0)
+os.close(fd)
+
+os.environ['BUP_SERVER_REVERSE'] = helpers.hostname()
+os.execvp(argv[0], argv)
+sys.exit(99)
+#!/usr/bin/env python
+import sys, os, glob, subprocess, time
+from bup import options, git
+from bup.helpers import *
+
+par2_ok = 0
+nullf = open('/dev/null')
+
+def debug(s):
+    if opt.verbose:
+        log(s)
+
+def run(argv):
+    # at least in python 2.5, using "stdout=2" or "stdout=sys.stderr" below
+    # doesn't actually work, because subprocess closes fd #2 right before
+    # execing for some reason.  So we work around it by duplicating the fd
+    # first.
+    fd = os.dup(2)  # copy stderr
+    try:
+        p = subprocess.Popen(argv, stdout=fd, close_fds=False)
+        return p.wait()
+    finally:
+        os.close(fd)
+
+def par2_setup():
+    global par2_ok
+    rv = 1
+    try:
+        p = subprocess.Popen(['par2', '--help'],
+                             stdout=nullf, stderr=nullf, stdin=nullf)
+        rv = p.wait()
+    except OSError:
+        log('fsck: warning: par2 not found; disabling recovery features.\n')
+    else:
+        par2_ok = 1
+
+def parv(lvl):
+    if opt.verbose >= lvl:
+        if istty:
+            return []
+        else:
+            return ['-q']
+    else:
+        return ['-qq']
+
+def par2_generate(base):
+    return run(['par2', 'create', '-n1', '-c200'] + parv(2)
+               + ['--', base, base+'.pack', base+'.idx'])
+
+def par2_verify(base):
+    return run(['par2', 'verify'] + parv(3) + ['--', base])
+
+def par2_repair(base):
+    return run(['par2', 'repair'] + parv(2) + ['--', base])
+
+def quick_verify(base):
+    f = open(base + '.pack', 'rb')
+    f.seek(-20, 2)
+    wantsum = f.read(20)
+    assert(len(wantsum) == 20)
+    f.seek(0)
+    sum = Sha1()
+    for b in chunkyreader(f, os.fstat(f.fileno()).st_size - 20):
+        sum.update(b)
+    if sum.digest() != wantsum:
+        raise ValueError('expected %r, got %r' % (wantsum.encode('hex'),
+                                                  sum.hexdigest()))
+        
 
-PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
-DAEMON=/usr/sbin/uniconfd
-NAME=uniconfd
-DESC="UniConf daemon"
-
-test -x $DAEMON || exit 0
-
-# Include uniconf defaults if available
-if [ -f /etc/default/uniconfd ] ; then
-       . /etc/default/uniconfd
-fi
-
-DAEMON_OPTS="$UNICONFD_OPTS $UNICONFD_MOUNTS"
-
-case "$1" in
-  start)
-       echo -n "Starting $DESC: "
-       start-stop-daemon --start --quiet --pidfile /var/run/$NAME.pid \
-               --make-pidfile --background \
-               --exec $DAEMON -- -f $DAEMON_OPTS
-       if [ "$?" != "0" ]; then ERR=$?; echo; exit $ERR; fi
-       echo "$NAME."
-       ;;
-  stop)
-       echo -n "Stopping $DESC: "
-       start-stop-daemon --stop --quiet --pidfile /var/run/$NAME.pid \
-               --exec $DAEMON
-       if [ "$?" != "0" ]; then ERR=$?; echo; exit $ERR; fi
-       echo "$NAME."
-       ;;
-  #reload)
-       #
-       #       If the daemon can reload its config files on the fly
-       #       for example by sending it SIGHUP, do it here.
-       #
-       #       If the daemon responds to changes in its config file
-       #       directly anyway, make this a do-nothing entry.
-       #
-       # echo "Reloading $DESC configuration files."
-       # start-stop-daemon --stop --signal 1 --quiet --pidfile \
-       #       /var/run/$NAME.pid --exec $DAEMON
-  #;;
-  restart|force-reload)
-       #
-       #       If the "reload" option is implemented, move the "force-reload"
-       #       option to the "reload" entry above. If not, "force-reload" is
-       #       just the same as "restart".
-       #
-       echo -n "Restarting $DESC: "
-       start-stop-daemon --stop --quiet --pidfile \
-               /var/run/$NAME.pid --exec $DAEMON || exit $?
-       sleep 1
-       start-stop-daemon --start --quiet --pidfile \
-               /var/run/$NAME.pid --exec $DAEMON -- $DAEMON_OPTS
-       if [ "$?" != "0" ]; then ERR=$?; echo; exit $ERR; fi
-       echo "$NAME."
-       ;;
-  *)
-       N=/etc/init.d/$NAME
-       # echo "Usage: $N {start|stop|restart|reload|force-reload}" >&2
-       echo "Usage: $N {start|stop|restart|force-reload}" >&2
-       exit 1
-       ;;
-esac
-
-exit 0
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          urandom
-# Required-Start:    $local_fs
-# Required-Stop:     $local_fs
-# Default-Start:     S
-# Default-Stop:      0 6
-# Short-Description: Save and restore random seed between restarts.
-# Description        This script saves the random seed between restarts.
-#                    It is called from the boot, halt and reboot scripts.
-### END INIT INFO
-
-[ -c /dev/urandom ] || exit 0
-
-PATH=/usr/sbin:/usr/bin:/sbin:/bin
-SAVEDFILE=/var/lib/urandom/random-seed
-POOLSIZE=512
-[ -f /proc/sys/kernel/random/poolsize ] && POOLSIZE="$(cat /proc/sys/kernel/random/poolsize)"
-. /lib/init/vars.sh
-
-. /lib/lsb/init-functions
-
-case "$1" in
-  start|"")
-       [ "$VERBOSE" = no ] || log_action_begin_msg "Initializing random number generator"
-       # Load and then save $POOLSIZE bytes,
-       # which is the size of the entropy pool
-       if [ -f "$SAVEDFILE" ]
-       then
-               # Handle locally increased pool size
-               SAVEDSIZE="$(find "$SAVEDFILE" -printf "%s")"
-               if [ "$SAVEDSIZE" -gt "$POOLSIZE" ]
-               then
-                       [ -w /proc/sys/kernel/random/poolsize ] && echo $POOLSIZE > /proc/sys/kernel/random/poolsize
-                       POOLSIZE=$SAVEDSIZE
-               fi
-               cat "$SAVEDFILE" >/dev/urandom
-       fi
-       rm -f $SAVEDFILE
-       umask 077
-       dd if=/dev/urandom of=$SAVEDFILE bs=$POOLSIZE count=1 >/dev/null 2>&1
-       ES=$?
-       umask 022
-       [ "$VERBOSE" = no ] || log_action_end_msg $ES
-       ;;
-  stop)
-       # Carry a random seed from shut-down to start-up;
-       # see documentation in linux/drivers/char/random.c
-       [ "$VERBOSE" = no ] || log_action_begin_msg "Saving random seed"
-       umask 077
-       dd if=/dev/urandom of=$SAVEDFILE bs=$POOLSIZE count=1 >/dev/null 2>&1
-       ES=$?
-       [ "$VERBOSE" = no ] || log_action_end_msg $ES
-       ;;
-  restart|reload|force-reload)
-       echo "Error: argument '$1' not supported" >&2
-       exit 3
-       ;;
-  *)
-       echo "Usage: urandom start|stop" >&2
-       exit 3
-       ;;
-esac
-
-:
-#!/bin/sh
-
-test -x /usr/sbin/vbetool || exit 0
-set -e
-
-. /lib/lsb/init-functions
-
-test -f /etc/default/rcS && . /etc/default/rcS
-test -f /etc/default/acpi-support && . /etc/default/acpi-support
-test -f /usr/share/acpi-support/device-funcs && . /usr/share/acpi-support/device-funcs
-
-case "$1" in
- start)
-       if laptop-detect > /dev/null; then
-               LAPTOP=true;
-       fi
-
-       if [ x$LAPTOP != xtrue ]; then
-               exit 0;
-       fi
-
-        DeviceConfig
-       log_begin_msg "Saving VESA state..."
-       if [ "$SAVE_VBE_STATE" = "true" ]; then
-           if [ "$VERBOSE" = no ]; then 
-               if ! vbetool vbestate save > $VBESTATE 2>/dev/null; then
-                   log_end_msg $?
-                   exit 1
-               fi
-           else
-               if ! vbetool vbestate save > $VBESTATE ; then
-                   log_end_msg $?
-                   exit 1
-               fi
-           fi
-           log_end_msg 0
-        fi
-        ;;
- *)
-        exit 0
-        ;;
-esac
-#! /bin/sh
-### BEGIN INIT INFO
-# Provides:          waitnfs
-# Required-Start:    $network $local_fs
-# Required-Stop:
-# Default-Start:     S
-# Default-Stop:
-# Short-Description: Wait for critical network file systems to be mounted
-# Description:       Network file systems are mounted in the background when
-#                    interfaces are brought up; this script waits for
-#                    those among them which are critical for booting to be
-#                    mounted before carrying on.
-#                    Specifically, it will wait for file systems mounted
-#                    on /usr, /usr/*, /var, /var/* 
-#                    This script WILL NOT wait on other network file which are
-#                    mounted elsewhere!
-### END INIT INFO
-
-[ -f /etc/default/rcS ] && . /etc/default/rcS
-. /lib/lsb/init-functions
-
-do_start() {
-       [ -f /etc/fstab ] || return
-       #
-       # Read through fstab line by line, building a list of networked
-       # file systems mounted on /usr* or /var*
-       # Wait up to a fixed period of time for these file systems to mount
-       #
-
-       exec 9<&0 </etc/fstab
-
-       waitnfs=
-       while read DEV MTPT FSTYPE OPTS REST
-       do
-               case "$DEV" in
-                 ""|\#*)
-                       continue
-                       ;;
-               esac
-               case "$OPTS" in
-                 noauto|*,noauto|noauto,*|*,noauto,*)
-                       continue
-                       ;;
-               esac
-               case "$FSTYPE" in
-                 nfs|nfs4|smbfs|cifs|coda|ncp|ncpfs|ocfs2|gfs)
-                       ;;
-                 *)
-                       continue
-                       ;;
-               esac
-               case "$MTPT" in
-                 /usr/local|/usr/local/*)
-                       ;;
-                 /usr|/usr/*)
-                       waitnfs="$waitnfs $MTPT"
-                       ;;
-                 /var|/var/*)
-                       waitnfs="$waitnfs $MTPT"
-                       ;;
-               esac
-       done
-
-       exec 0<&9 9<&-
-
-       # Try mounting all networked filesystems here, just before waiting for
-       # them; background this call so as not to block startup sequence
-       /lib/init/mountall-net-fs &
-
-       # Wait for each path, the timeout is for all of them as that's
-       # really the maximum time we have to wait anyway
-       TIMEOUT=900
-       for mountpt in $waitnfs; do
-               log_action_begin_msg "Waiting for $mountpt"
-
-               while ! mountpoint -q $mountpt; do
-                       sleep 0.1
-
-                       TIMEOUT=$(( $TIMEOUT - 1 ))
-                       if [ $TIMEOUT -le 0 ]; then
-                               log_action_end_msg 1
-                               break
-                       fi
-               done
-
-               if [ $TIMEOUT -gt 0 ]; then
-                       log_action_end_msg 0
-               fi
-       done
-}
-
-case "$1" in
-    start)
-        do_start
-        ;;
-    restart|reload|force-reload)
-        echo "Error: argument '$1' not supported" >&2
-        exit 3
-        ;;
-    stop)
-        ;;
-    *)
-        echo "Usage: $0 start|stop" >&2
-        exit 3
-        ;;
-esac
-
-: exit 0
-#!/bin/sh
-
-### BEGIN INIT INFO
-# Provides:          winbind
-# Required-Start:    $network $local_fs $remote_fs
-# Required-Stop:     $network $local_fs $remote_fs
-# Default-Start:     2 3 4 5
-# Default-Stop:      0 1 6
-# Short-Description: start Winbind daemon
-### END INIT INFO
-
-
-PATH=/sbin:/bin:/usr/sbin:/usr/bin
-
-[ -r /etc/default/winbind ] && . /etc/default/winbind
-
-DAEMON=/usr/sbin/winbindd
-PIDDIR=/var/run/samba
-
-# clear conflicting settings from the environment
-unset TMPDIR
-
-# See if the daemon is there
-test -x $DAEMON || exit 0
-
-. /lib/lsb/init-functions
-
-case "$1" in
-       start)
-               log_daemon_msg "Starting the Winbind daemon" "winbind"
-
-               mkdir -p /var/run/samba/winbindd_privileged || return 1
-               chgrp winbindd_priv $PIDDIR/winbindd_privileged/ || return 1
-               chmod 0750 $PIDDIR/winbindd_privileged/ || return 1
-               start-stop-daemon --start --quiet --oknodo --exec $DAEMON -- $WINBINDD_OPTS
-
-               log_end_msg $?
-               ;;
-
-       stop)
-               log_daemon_msg "Stopping the Winbind daemon" "winbind"
-               start-stop-daemon --stop --quiet --oknodo --exec $DAEMON
-               log_end_msg $?
-               ;;
-
-       restart|force-reload)
-               $0 stop && sleep 2 && $0 start
-               ;;
-
-       *)
-               echo "Usage: /etc/init.d/winbind {start|stop|restart|force-reload}"
-               exit 1
-               ;;
-esac
-#!/bin/sh
-
-### BEGIN INIT INFO
-# Provides:            wpa-ifupdown
-# Required-Start:      $network
-# Required-Stop:       $network
-# Should-Start:
-# Should-Stop:
-# Default-Start:
-# Default-Stop:                0 6
-# Short-Description:   Stop wpa_supplicant processes started via ifupdown
-# Description:         Run ifdown on interfaces authenticated via
-#                      wpa_supplicant. Sendsigs terminates wpa_supplicant
-#                      processes before networking is stopped causing each
-#                      network interface authenticated via a wpa_supplicant
-#                      daemon to be terminated abrubtly.
-### END INIT INFO
-
-PATH=/usr/sbin:/usr/bin:/sbin:/bin
-
-test -d /var/run || exit 0
-
-test -x /sbin/ifdown || exit 0
-
-. /lib/lsb/init-functions
-
-stop_wpa_action () {
-       test -x /sbin/wpa_action || return
-       unset IFACES
-       IFACES=$(find /var/run -maxdepth 1 -type f -name 'wpa_action.*.pid' -printf '%P\n' | cut -d'.' -f2)
-       if test -n "$IFACES"; then
-               log_daemon_msg "Stopping wpa_action roaming interfaces"
-               for iface in $IFACES; do
-                       log_progress_msg "$iface"
-                       # wpa_action executes /sbin/ifdown
-                       wpa_action "$iface" stop >/dev/null 2>&1
-               done
-               log_end_msg 0
-       fi
-}
-
-stop_wpa_supplicant () {
-       unset IFACES
-       IFACES=$(find /var/run -maxdepth 1 -type f -name 'wpa_supplicant.*.pid' -printf '%P\n' | cut -d'.' -f2)
-       if test -n "$IFACES"; then
-               log_daemon_msg "Stopping wpa_supplicant interfaces"
-               for iface in $IFACES; do
-                       log_progress_msg "$iface"
-                       ifdown $iface >/dev/null 2>&1
-               done
-               log_end_msg 0
-       fi
-}
-
-case "$1" in
-       start|restart|force-reload)
-               # No-op
-               ;;
-       stop)
-               stop_wpa_action
-               stop_wpa_supplicant
-               ;;
-       *)
-               echo "Usage: $0 {start|stop|restart|force-reload}" >&2
-               exit 3
-               ;;
-esac
-
-exit 0
-#!/bin/sh
-# /etc/init.d/x11-common: set up the X server and ICE socket directories
-### BEGIN INIT INFO
-# Provides:          x11-common
-# Required-Start:    $local_fs $remote_fs
-# Required-Stop:     $local_fs $remote_fs
-# Should-Start:      $named
-# Should-Stop:       $named
-# Default-Start:     S
-# Default-Stop:
-### END INIT INFO
-
-set -e
-
-PATH=/bin:/usr/bin:/sbin:/usr/sbin
-SOCKET_DIR=/tmp/.X11-unix
-ICE_DIR=/tmp/.ICE-unix
-
-. /lib/lsb/init-functions
-if [ -f /etc/default/rcS ]; then
-  . /etc/default/rcS
-fi
-
-do_restorecon () {
-  # Restore file security context (SELinux).
-  if which restorecon >/dev/null 2>&1; then
-    restorecon "$1"
-  fi
-}
-
-set_up_socket_dir () {
-  if [ "$VERBOSE" != no ]; then
-    log_begin_msg "Setting up X server socket directory $SOCKET_DIR..."
-  fi
-  if [ -e $SOCKET_DIR ] && [ ! -d $SOCKET_DIR ]; then
-    mv $SOCKET_DIR $SOCKET_DIR.$$
-  fi
-  mkdir -p $SOCKET_DIR
-  chown 0:0 $SOCKET_DIR
-  chmod 1777 $SOCKET_DIR
-  do_restorecon $SOCKET_DIR
-  [ "$VERBOSE" != no ] && log_end_msg 0 || return 0
-}
-
-set_up_ice_dir () {
-  if [ "$VERBOSE" != no ]; then
-    log_begin_msg "Setting up ICE socket directory $ICE_DIR..."
-  fi
-  if [ -e $ICE_DIR ] && [ ! -d $ICE_DIR ]; then
-    mv $ICE_DIR $ICE_DIR.$$
-  fi
-  mkdir -p $ICE_DIR
-  chown 0:0 $ICE_DIR
-  chmod 1777 $ICE_DIR
-  do_restorecon $ICE_DIR
-  [ "$VERBOSE" != no ] && log_end_msg 0 || return 0
-}
-
-do_status () {
-    if [ -d $ICE_DIR ] && [ -d $SOCKET_DIR ]; then
-      return 0
-    else
-      return 4
-    fi
-}
-
-case "$1" in
-  start)
-    set_up_socket_dir
-    set_up_ice_dir
-  ;;
-
-  restart|reload|force-reload)
-    /etc/init.d/x11-common start
-  ;;
-
-  stop)
-   :
-  ;;
-
-  status)
-    do_status
-  ;;
-  *)
-    log_success_msg "Usage: /etc/init.d/x11-common {start|stop|status|restart|reload|force-reload}"
-    exit 1
-    ;;
-esac
-
-exit 0
-
-# vim:set ai et sts=2 sw=2 tw=0:
+def git_verify(base):
+    if opt.quick:
+        try:
+            quick_verify(base)
+        except Exception, e:
+            debug('error: %s\n' % e)
+            return 1
+        return 0
+    else:
+        return run(['git', 'verify-pack', '--', base])
+    
+    
+def do_pack(base, last):
+    code = 0
+    if par2_ok and par2_exists and (opt.repair or not opt.generate):
+        vresult = par2_verify(base)
+        if vresult != 0:
+            if opt.repair:
+                rresult = par2_repair(base)
+                if rresult != 0:
+                    print '%s par2 repair: failed (%d)' % (last, rresult)
+                    code = rresult
+                else:
+                    print '%s par2 repair: succeeded (0)' % last
+                    code = 100
+            else:
+                print '%s par2 verify: failed (%d)' % (last, vresult)
+                code = vresult
+        else:
+            print '%s ok' % last
+    elif not opt.generate or (par2_ok and not par2_exists):
+        gresult = git_verify(base)
+        if gresult != 0:
+            print '%s git verify: failed (%d)' % (last, gresult)
+            code = gresult
+        else:
+            if par2_ok and opt.generate:
+                presult = par2_generate(base)
+                if presult != 0:
+                    print '%s par2 create: failed (%d)' % (last, presult)
+                    code = presult
+                else:
+                    print '%s ok' % last
+            else:
+                print '%s ok' % last
+    else:
+        assert(opt.generate and (not par2_ok or par2_exists))
+        debug('    skipped: par2 file already generated.\n')
+    return code
+
+
+optspec = """
+bup fsck [options...] [filenames...]
+--
+r,repair    attempt to repair errors using par2 (dangerous!)
+g,generate  generate auto-repair information using par2
+v,verbose   increase verbosity (can be used more than once)
+quick       just check pack sha1sum, don't use git verify-pack
+j,jobs=     run 'n' jobs in parallel
+par2-ok     immediately return 0 if par2 is ok, 1 if not
+disable-par2  ignore par2 even if it is available
+"""
+o = options.Options('bup fsck', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+par2_setup()
+if opt.par2_ok:
+    if par2_ok:
+        sys.exit(0)  # 'true' in sh
+    else:
+        sys.exit(1)
+if opt.disable_par2:
+    par2_ok = 0
+
+git.check_repo_or_die()
+
+if not extra:
+    debug('fsck: No filenames given: checking all packs.\n')
+    extra = glob.glob(git.repo('objects/pack/*.pack'))
+
+code = 0
+count = 0
+outstanding = {}
+for name in extra:
+    if name.endswith('.pack'):
+        base = name[:-5]
+    elif name.endswith('.idx'):
+        base = name[:-4]
+    elif name.endswith('.par2'):
+        base = name[:-5]
+    elif os.path.exists(name + '.pack'):
+        base = name
+    else:
+        raise Exception('%s is not a pack file!' % name)
+    (dir,last) = os.path.split(base)
+    par2_exists = os.path.exists(base + '.par2')
+    if par2_exists and os.stat(base + '.par2').st_size == 0:
+        par2_exists = 0
+    sys.stdout.flush()
+    debug('fsck: checking %s (%s)\n' 
+          % (last, par2_ok and par2_exists and 'par2' or 'git'))
+    if not opt.verbose:
+        progress('fsck (%d/%d)\r' % (count, len(extra)))
+    
+    if not opt.jobs:
+        nc = do_pack(base, last)
+        code = code or nc
+        count += 1
+    else:
+        while len(outstanding) >= opt.jobs:
+            (pid,nc) = os.wait()
+            nc >>= 8
+            if pid in outstanding:
+                del outstanding[pid]
+                code = code or nc
+                count += 1
+        pid = os.fork()
+        if pid:  # parent
+            outstanding[pid] = 1
+        else: # child
+            try:
+                sys.exit(do_pack(base, last))
+            except Exception, e:
+                log('exception: %r\n' % e)
+                sys.exit(99)
+                
+while len(outstanding):
+    (pid,nc) = os.wait()
+    nc >>= 8
+    if pid in outstanding:
+        del outstanding[pid]
+        code = code or nc
+        count += 1
+    if not opt.verbose:
+        progress('fsck (%d/%d)\r' % (count, len(extra)))
+
+if not opt.verbose and istty:
+    log('fsck done.           \n')
+sys.exit(code)
+#!/usr/bin/env python
+import sys, os, struct, getopt, subprocess, signal
+from bup import options, ssh
+from bup.helpers import *
+
+optspec = """
+bup rbackup <hostname> index ...
+bup rbackup <hostname> save ...
+bup rbackup <hostname> split ...
+"""
+o = options.Options('bup rbackup', optspec, optfunc=getopt.getopt)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+if len(extra) < 2:
+    o.fatal('arguments expected')
+
+class SigException(Exception):
+    def __init__(self, signum):
+        self.signum = signum
+        Exception.__init__(self, 'signal %d received' % signum)
+def handler(signum, frame):
+    raise SigException(signum)
+
+signal.signal(signal.SIGTERM, handler)
+signal.signal(signal.SIGINT, handler)
+
+sp = None
+p = None
+ret = 99
+
+try:
+    hostname = extra[0]
+    argv = extra[1:]
+    p = ssh.connect(hostname, 'rbackup-server')
+
+    argvs = '\0'.join(['bup'] + argv)
+    p.stdin.write(struct.pack('!I', len(argvs)) + argvs)
+    p.stdin.flush()
+
+    main_exe = os.environ.get('BUP_MAIN_EXE') or sys.argv[0]
+    sp = subprocess.Popen([main_exe, 'server'], stdin=p.stdout, stdout=p.stdin)
+
+    p.stdin.close()
+    p.stdout.close()
+
+finally:
+    while 1:
+        # if we get a signal while waiting, we have to keep waiting, just
+        # in case our child doesn't die.
+        try:
+            ret = p.wait()
+            sp.wait()
+            break
+        except SigException, e:
+            log('\nbup rbackup: %s\n' % e)
+            os.kill(p.pid, e.signum)
+            ret = 84
+sys.exit(ret)
+#!/usr/bin/env python
+import sys, os, re
+from bup import options
+
+optspec = """
+bup newliner
+"""
+o = options.Options('bup newliner', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if extra:
+    o.fatal("no arguments expected")
+
+r = re.compile(r'([\r\n])')
+lastlen = 0
+all = ''
+while 1:
+    l = r.split(all, 1)
+    if len(l) <= 1:
+        try:
+            b = os.read(sys.stdin.fileno(), 4096)
+        except KeyboardInterrupt:
+            break
+        if not b:
+            break
+        all += b
+    else:
+        assert(len(l) == 3)
+        (line, splitchar, all) = l
+        #splitchar = '\n'
+        sys.stdout.write('%-*s%s' % (lastlen, line, splitchar))
+        if splitchar == '\r':
+            lastlen = len(line)
+        else:
+            lastlen = 0
+        sys.stdout.flush()
+
+if lastlen or all:
+    sys.stdout.write('%-*s\n' % (lastlen, all))
+#!/usr/bin/env python
+import sys
+from bup import options, git, _hashsplit
+from bup.helpers import *
+
+
+optspec = """
+bup margin
+"""
+o = options.Options('bup margin', optspec)
+(opt, flags, extra) = o.parse(sys.argv[1:])
+
+if extra:
+    o.fatal("no arguments expected")
+
+git.check_repo_or_die()
+#git.ignore_midx = 1
+
+mi = git.PackIdxList(git.repo('objects/pack'))
+last = '\0'*20
+longmatch = 0
+for i in mi:
+    if i == last:
+        continue
+    #assert(str(i) >= last)
+    pm = _hashsplit.bitmatch(last, i)
+    longmatch = max(longmatch, pm)
+    last = i
+print longmatch