#!/bin/sh
#
# This file is part of the CernVM File System
# This script takes care of creating, removing, and maintaining repositories
# on a Stratum 0/1 server

set -e # ESSENTIAL! Don't remove this!
       # Stops the server script in case anything unexpected occurs, so that
       # malfunctions cause as less damage as possible.
       # For example a crashing `cvmfs_server publish` is prevented from wiping
       # the scratch area, giving us a chance to fix and retry the process.

die() {
  echo -e $1 >&2
  exit 1
}

# set default locale
export LANG=C


################################################################################
#                                                                              #
#                              Environment Setup                               #
#                                                                              #
################################################################################


# setup server hooks: no-ops (overrideable by /etc/cvmfs/cvmfs_server_hooks.sh)
transaction_before_hook() { :; }
transaction_after_hook() { :; }
abort_before_hook() { :; }
abort_after_hook() { :; }
publish_before_hook() { :; }
publish_after_hook() { :; }

[ -f /etc/cvmfs/cvmfs_server_hooks.sh ] && . /etc/cvmfs/cvmfs_server_hooks.sh

# Find out about Apache's name and configuration Directory depending on the Distribution
if which httpd2 >/dev/null 2>&1; then #SLES/OpenSuSE
  APACHE_SERVICE="apache2"
  APACHE_CONF=${APACHE_SERVICE}
  APACHE_BIN=$(which httpd2)
elif which apache2 >/dev/null 2>&1; then # Debian based
  APACHE_SERVICE="apache2"
  APACHE_CONF=${APACHE_SERVICE}
  APACHE_BIN=$(which apache2)
else
  APACHE_SERVICE="httpd" # EL based
  APACHE_CONF=${APACHE_SERVICE}
  APACHE_BIN="/usr/sbin/httpd"
fi

# Find the service binary
if [ -x /sbin/service ]; then
  SERVICE_BIN="/sbin/service"
elif [ -x /usr/sbin/service ]; then
  SERVICE_BIN="/usr/sbin/service" # Ubuntu
elif [ -x /sbin/rc-service ]; then
  SERVICE_BIN="/sbin/rc-service" # OpenRC
fi
[ -z "$SERVICE_BIN" ] && die "Could not locate 'service' utility"

# Find the fuser binary
if [ -x /sbin/fuser ]; then
  fuser="/sbin/fuser" # RHEL
else
  fuser="/bin/fuser"  # Ubuntu, SuSe, Gentoo
fi

# standard values
CVMFS_DEFAULT_USE_FILE_CHUNKING=true
CVMFS_DEFAULT_MIN_CHUNK_SIZE=4194304
CVMFS_DEFAULT_AVG_CHUNK_SIZE=8388608
CVMFS_DEFAULT_MAX_CHUNK_SIZE=16777216
CVMFS_DEFAULT_CATALOG_ENTRY_WARN_THRESHOLD=500000


################################################################################
#                                                                              #
#                              Utility Functions                               #
#                                                                              #
################################################################################


cvmfs_mkfqrn() {
   local repo=$1

   if [ -z "$repo" ]; then
      echo
      return 0
   fi

   echo $repo | grep \\. || echo "${repo}.${CVMFS_DEFAULT_DOMAIN}"
   return 0
}


# checks if the given command name is a supported command of cvmfs_server
#
# @param subcommand   the subcommand to be called
# @return   0 if the command was recognized
is_subcommand() {
  local subcommand="$1"
  local supported_commands="mkfs add-replica import publish rollback rmfs alterfs \
    resign list info lstags check transaction abort snapshot skeleton migrate"

  for possible_command in $supported_commands; do
    if [ x"$possible_command" = x"$subcommand" ]; then
      return 0
    fi
  done

  return 1
}


# returns the version string of the current cvmfs installation
cvmfs_version_string() {
  local version_string
  if ! cvmfs_swissknife version > /dev/null 2>&1; then
    # Fallback: for CernVM-FS versions before 2.1.7
    # this is just a security measure... it should never happen, since this
    # function was introduced with CernVM-FS 2.1.7
    version_string=$(cvmfs_swissknife --version | sed -n '2{p;q}' | awk '{print $2}')
  else
    version_string=$(cvmfs_swissknife --version)
  fi
  echo $version_string
}
version_major() { echo $1 | cut --delimiter=. --fields=1; }
version_minor() { echo $1 | cut --delimiter=. --fields=2; }
version_patch() { echo $1 | cut --delimiter=. --fields=3; }
compare_versions() {
  local lv=$1
  local comparison_operator=$2
  local rv=$3
  [ $(version_major $lv) $comparison_operator $(version_major $rv) ] && \
  [ $(version_minor $lv) $comparison_operator $(version_minor $rv) ] && \
  [ $(version_patch $lv) $comparison_operator $(version_patch $rv) ]
}
version_greater_or_equal() {
  local needle=$1
  compare_versions $(cvmfs_version_string) -ge $needle
}
version_lower_or_equal() {
  local needle=$1
  compare_versions $(cvmfs_version_string) -le $needle
}
version_equal() {
  local needle=$1
  [ "$(cvmfs_version_string)" = "$needle" ]
}

# prints some help information optionally followed by an error message
# afterwards it aborts the script
#
# @param errormsg   an optional error message that is printed after the
#                   actual usage text
usage() {
  errormsg=$1

  echo "\
CernVM-FS Server Tool $(cvmfs_version_string)

Usage: cvmfs_server COMMAND [options] <parameters>

Supported Commands:
  mkfs          [-w stratum0 url] [-u upstream storage] [-o owner]
                [-m replicable] [-f union filesystem type] [-v volatile content]
                [-a hash algorithm (default: SHA-1)]
                <fully qualified repository name>
                Creates a new repository with a given name
  add-replica   [-u stratum1 upstream storage] [-o owner] [-n alias name]
                [-a silence apache warning]
                <stratum 0 url> <public key>
                Creates a Stratum 1 replica of a Stratum 0 repository
  import        [-w stratum0 url] [-o owner] [-u upstream storage]
                [-l import legacy repo (2.0.x)] [-s show migration statistics]
                [-c file ownership (UID:GID)] [-k path to keys] [-g chown backend]
                <fully qualified repository name>
                Imports an old CernVM-FS repository into a fresh 2.1.x repo
  publish       [-d debug mode | -D blocking debug mode] [-p pause for tweaks]
                [-a tag name] [-c tag channel] [ -t tag description] [ -h hash]
                [-r tag name] [-v be verbose]
                <fully qualified name>
                Make a new repository snapshot
  rmfs          [-f don't ask again]
                <fully qualified name>
                Remove the repository
  abort         [-f don't ask again]
                <fully qualified name>
                Abort transaction and return to the state before
  rollback      [-t tag] [-f don't ask again]
                <fully qualified name>
                Re-publishes the given tag as the new latest revision.
                All snapshots between trunk and the target tag become
                inaccessible.  Without a tag name, trunk-previous is used.
  resign        <fully qualified name>
                Re-sign the 30 day whitelist
  info          <fully qualified name>
                Print summary about the repository
  lstags        <fully qualified name>
                Print named tags (snapshots) of the repository
  check         [-c disable data chunk existence check]
                [-i check data integrity] (may take some time)]
                [-t tag (check given tag instead of trunk)]
                <fully qualified name>
                Checks if the repository is sane
  transaction   <fully qualified name>
                Start to edit a repository
  snapshot      <fully qualified name>
                Synchronize a Stratum 1 replica with the Stratum 0 source
  migrate       <fully qualified name>
                Migrates a repository to the current version of CernVM-FS
  list          List available repositories
"


  if [ x"$errormsg" != x ]; then
    echo "\
________________________________________________________________________

NOTE: $errormsg
"
    exit 3
  else
    exit 2
  fi
}

load_repo_config() {
  local name=$1
  . /etc/cvmfs/repositories.d/${name}/server.conf
}

# retrieves (or guesses) the version of CernVM-FS that was used to create the
# repository whose server.conf is currently sourced
# Note: this assumes that server.conf is already sourced!
repository_creator_version() {
  local version=$CVMFS_CREATOR_VERSION
  if [ x"$version" = x ]; then
    version="2.1.6" # 2.1.6 was the last version, that did not store the creator
                    # version... therefore this has to be handled as "<= 2.1.6"
                    # Note: see also `mangle_version_string()`
  fi
  echo $version
}

# whenever you print the version string you should use this function since
# a repository created before CernVM-FS 2.1.7 cannot be fingerprinted
# correctly...
# @param version_string  the plain version string
mangle_version_string() {
  local version_string=$1
  if [ x"$version_string" = x"2.1.6" ]; then
    echo "2.1.6 or lower"
  else
    echo $version_string
  fi
}

# only called by check_repository_compatibility()!
# @param creator  the creator version of the (incompatible) repository
# @param nokill   (optional) see check_repository_compatibility()
repo_is_incompatible() {
  local creator=$1
  # if 'nokill' is set, be silent and just return 1
  if [ $# -gt 1 ]; then
    return 1
  fi

  echo "\
This repository was created with CernVM-FS $(mangle_version_string $creator).
You are currently running CernVM-FS $(cvmfs_version_string), which is
incompatible to $(mangle_version_string $creator).

Please run \`cvmfs_server migrate\` to update your repository before proceeding."
  exit 1
}


# checks if the sourced server.conf is compatible with the running version of
# this script.
# Note: this assumes that server.conf was already sourced!
# @param nokill  (optional) if not set -> `exit 1` on incompatibility
check_repository_compatibility() {
  local creator=$(repository_creator_version)
  local nokill=$1
  if version_equal "$creator"; then
    return 0 # trivial case... no update of CernVM-FS taken place
  fi

  if version_lower_or_equal "$creator"; then
    if [ $# -gt 0 ]; then
      return 1 # nokill
    fi
    echo "This repository was created with CernVM-FS $creator which is newer
than the currently installed version $(cvmfs_version_string). Please install at
least CernVM-FS $creator to manipulate this repository."
    exit 1
  fi

  # Migration History:
  #   2.1.6 -> 2.1.7
  #     -> repository format changed
  #
  #   2.1.7+ -> 2.1.15
  #     -> config files changed (adding client.local)
  #     -> adjustments in /etc/fstab
  #     -> additional statistics counters in file catalogs
  #
  #   2.1.15+
  #     < nothing changed yet >
  #
  # Note: I tried to make this code as verbose as possible
  #
  if [ "$creator" = "2.1.6" ] && version_greater_or_equal "2.1.7"; then
    repo_is_incompatible "$creator" $nokill
    return $?
  fi

  if [ "$creator" = "2.1.7"  ] || [ "$creator" = "2.1.8"  ] || \
     [ "$creator" = "2.1.9"  ] || [ "$creator" = "2.1.10" ] || \
     [ "$creator" = "2.1.11" ] || [ "$creator" = "2.1.12" ] || \
     [ "$creator" = "2.1.13" ] || [ "$creator" = "2.1.14" ];
  then
    if version_greater_or_equal "2.1.15"; then
      repo_is_incompatible "$creator" $nokill
      return $?
    fi
  fi

  return 0
}


# checks if the given repository name already exists
#
# @param given_name   the name of the repository to be checked
# @return             0 if the repository was found
check_repository_existence() {
  local given_name="$1"
  local fqrn

  # empty name or wildcards are not allowed (and thus does not exist)
  if [ x"$given_name" = x ] || echo "$given_name" | grep -q "*"; then
    return 1
  fi

  # Check if exists
  fqrn=$(cvmfs_mkfqrn $given_name)
  [ -d /etc/cvmfs/repositories.d/$fqrn ]
}


# checks the existence of a list of repositories
# Note: the function echo's an error message and stops the execution of the
#       script by default.
#
# @param given_names   the list of repository names to be checked
# @param no_kill       (optional) skip the termination on error
# @return              0 if all listed repositories exist
check_multiple_repository_existence() {
  local given_names="$1"
  local no_kill=$2

  for name in $given_names; do
    if ! check_repository_existence $name; then
      if [ x"$no_kill" = x"" ]; then
        die "The repository $name does not exist."
      else
        return 1
      fi
    fi
  done
  return 0
}


# checks if the aufs kernel module is present
#
# @return   0 if the aufs kernel module is loaded
check_aufs() {
  /sbin/modprobe -q aufs || test -d /sys/fs/aufs
}


# checks if the overlayfs kernel module is present
#
# @return   0 if the overlayfs kernel module is loaded
check_overlayfs() {
  /sbin/modprobe -q overlayfs || test -d /sys/module/overlayfs
}


# checks if autofs is disabled on /cvmfs
#
# @return  0 if autofs is not used for /cvmfs
check_autofs_on_cvmfs() {
  cat /proc/mounts | grep -q "^/etc/auto.cvmfs /cvmfs "
}


# checks if apache is installed and running
#
# @return  0 if apache is installed and running
check_apache() {
  [ -d /etc/${APACHE_CONF} ] && ${SERVICE_BIN} ${APACHE_SERVICE} status >/dev/null
}


# retrieves the apache version string "2.x.xx"
get_apache_version() {
  ${APACHE_BIN} -v | head -n1 | \
    sed 's/^Server version: Apache\/\([0-9]\.[0-9]\.[0-9][0-9]*\).*$/\1/'
}


get_fd_modes() {
  local path=$1
  lsof -Fan 2>/dev/null | grep -B1 -e "^n$path" | grep -e '^a.*'
}

# gets the number of open read-only file descriptors beneath a given path
#
# @param path  the path to look at for open read-only fds
# @return      the number of open read-only file descriptors
count_rd_only_fds() {
  local path=$1
  local cnt=0
  for line in $(get_fd_modes $path); do
    if echo "$line" | grep -qe '^\ar\?$';  then cnt=$(( $cnt + 1 )); fi
  done
  echo $cnt
}

# returns 0 if the current working dir is somewhere under $path
#
# @param path  the path to look at
# @return      0 if cwd is on path or below, 1 otherwise
is_cwd_on_path() {
  local path=$1

  if [ "x$(pwd)" = "x${path}" ]; then
    return 0
  fi
  if echo "x$(pwd)" | grep -q "^x${path}/"; then
    return 0
  fi

  return 1
}

# gets the number of open writable file descriptors beneath a given path
#
# @param path  the path to look at for open writable fds
# @return      the number of open writable file descriptors
count_wr_fds() {
  local path=$1
  local cnt=0
  for line in $(get_fd_modes $path); do
    if echo "$line" | grep -qe '^\a[wu]$'; then cnt=$(( $cnt + 1 )); fi
  done
  echo $cnt
}


# figure out apache config file mode
#
# @return   apache config mode (stdout) (see globals below)
APACHE_CONF_MODE_OLD=1 # *.conf goes to ${APACHE_CONF}/conf.d
APACHE_CONF_MODE_NEW=2 # *.conf goes to ${APACHE_CONF}/conf-available
get_apache_conf_mode() {
  local minor_apache_version=$(version_minor "$(get_apache_version)")
  if [ $minor_apache_version -ge 4 ] || [ -d /etc/${APACHE_CONF}/conf-available ]; then
    echo $APACHE_CONF_MODE_NEW
  else
    echo $APACHE_CONF_MODE_OLD
  fi
}


# find location of apache configuration files
#
# @return   the location of apache configuration files (stdout)
get_apache_conf_path() {
  local res_path="/etc/${APACHE_CONF}"
  if [ x"$(get_apache_conf_mode)" = x"$APACHE_CONF_MODE_NEW" ]; then
    echo "${res_path}/conf-available"
  else
    echo "${res_path}/conf.d"
  fi
}


# returns the apache configuration string for 'allow from all'
# Note: this is necessary, since apache 2.4.x formulates that different
#
# @return   a configuration snippet to allow s'th from all hosts (stdout)
get_compatible_apache_allow_from_all_config() {
  if [ x"$(get_apache_conf_mode)" = x"$APACHE_CONF_MODE_NEW" ]; then
    echo "Require all granted"
  else
    local nl='
'
    echo "Order allow,deny${nl}    Allow from all"
  fi
}


# checks if cvmfs2 client is installed
#
# @return  0 if cvmfs2 client is installed
check_cvmfs2_client() {
  [ -x /usr/bin/cvmfs2 ]
}


# checks if the running user is root
#
# @return   0 if the current user is root
is_root() {
  [ $(id -u) -eq 0 ]
}


# checks if a given path is mounted
# Note: this takes care of symlink resolving and should be
#       used exclusively for mount checks
#
# @param mountpoint  the mountpoint to be checked
# @param regexp      additional regexp to be validated on the mountpoint record
#                    found in /proc/mounts
is_mounted() {
  local mountpoint="$1"
  local regexp="$2"

  local absolute_mnt="$(readlink --canonicalize $mountpoint)"
  local mnt_record="$(cat /proc/mounts 2>/dev/null | grep " $absolute_mnt ")"
  if [ x"$mnt_record" = x"" ]; then
    return 1
  fi

  [ x"$regexp" = x"" ] || echo "$mnt_record" | grep -q "$regexp"
}


# checks if a given repository is a stratum 0 repository
#
# @param name   the repository name to be checked
# @return       0 if it is a stratum 0 repository
is_stratum0() {
  local name=$1
  ! [ -f /etc/cvmfs/repositories.d/$name/replica.conf ]
}


# checks if a given repository is a stratum 1 repository
#
# @param name   the repository name to be checked
# @return       0 if it is a stratum 1 repository
is_stratum1() {
  local name=$1
  ! is_stratum0 $name
}

# checks if a given repository is replicable
#
# @param name   the repository name to be checked
# @return       0 if it is a stratum0 repository and replicable
is_master_replica() {
  local name=$1
  local is_master_replica

  if [ $(echo $name | cut --bytes=1-7) = "http://" ]; then
    is_master_replica=$(cvmfs_swissknife info -r $name -m 2>/dev/null)
  else
    is_stratum0 $name || return 1
    load_repo_config $name
    is_master_replica=$(cvmfs_swissknife info -r $CVMFS_STRATUM0 -m 2>/dev/null)
  fi

  [ "x$is_master_replica" = "xtrue" ]
}

# checks if a repository is currently in a transaction
#
# @param name  the repository name to be checked
# @return      0 if in a transaction
is_in_transaction() {
  local name=$1
  load_repo_config $name
  [ -d ${CVMFS_SPOOL_DIR}/in_transaction ]
}

open_transaction() {
  local name=$1
  load_repo_config $name
  mkdir ${CVMFS_SPOOL_DIR}/in_transaction > /dev/null 2>&1 || die "Failed to open transaction"
}

close_transaction() {
  local name=$1
  load_repo_config $name
  rmdir ${CVMFS_SPOOL_DIR}/in_transaction
}

# checks if a repository is currently runing a publish procedure
#
# @param name  the repository name to be checked
# @return      0 if a publishing procedure is running
is_publishing() {
  local name=$1
  load_repo_config $name
  [ -d ${CVMFS_SPOOL_DIR}/is_publishing ]
}

publishing_lock() {
  local name=$1
  load_repo_config $name
  mkdir ${CVMFS_SPOOL_DIR}/is_publishing > /dev/null 2>&1 || die "Failed to acquire publishing lock"
  trap "rmdir ${CVMFS_SPOOL_DIR}/is_publishing > /dev/null 2>&1" 0
}


# checks if a user exists in the system
#
# @param user   the name of the user to be checked
# @return       0 if user was found
check_user() {
  local user=$1
  id $user > /dev/null 2>&1
}


has_selinux() {
  [ -f /selinux/enforce ] && [ $(cat /selinux/enforce) -ne 0 ]
}


# checks if a given list of strings contains a specific item
#
# @param haystack   the list to be searched
# @param needle     the string item to be found in the haystack
# @return           0 if the item was found
contains() {
  local haystack="$1"
  local needle=$2

  for elem in $haystack; do
    if [ x"$elem" = x"$needle" ]; then
      return 0
    fi
  done

  return 1
}


_cleanup_tmrc() {
  local tmpdir=$1
  umount ${tmpdir}/c > /dev/null 2>&1 || umount -l > /dev/null 2>&1
  rm -fR ${tmpdir}   > /dev/null 2>&1
}

# for some reason `mount -o remount,(ro|rw) /cvmfs/$name` does not work on older
# platforms if we set the SELinux context=... parameter in /etc/fstab
# this dry-runs the whole mount, remount, unmount cycle to find out if it works
# correctly (aufs version)
# @returns  0 if the whole cycle worked as expected
try_mount_remount_cycle_aufs() {
  local tmpdir
  tmpdir=$(mktemp -d)
  mkdir ${tmpdir}/a ${tmpdir}/b ${tmpdir}/c
  mount -t aufs \
    -o br=${tmpdir}/a=ro:${tmpdir}/b=rw,ro,context=system_u:object_r:default_t:s0 \
    try_remount_aufs ${tmpdir}/c  > /dev/null 2>&1 || return 1
  mount -o remount,rw ${tmpdir}/c > /dev/null 2>&1 || { _cleanup_tmrc $tmpdir; return 2; }
  mount -o remount,ro ${tmpdir}/c > /dev/null 2>&1 || { _cleanup_tmrc $tmpdir; return 3; }
  _cleanup_tmrc $tmpdir
  return 0
}

# test the mount, remount, unmount cycle (overlayfs version)
# @returns  0 if the whole cycle worked as expected
try_mount_remount_cycle_overlayfs() {
  local tmpdir
  tmpdir=$(mktemp -d)
  mkdir ${tmpdir}/a ${tmpdir}/b ${tmpdir}/c
  mount -t overlayfs \
    -o upperdir=${tmpdir}/b,lowerdir=${tmpdir}/a,ro,context=system_u:object_r:default_t:s0 \
    try_remount_overlayfs ${tmpdir}/c  > /dev/null 2>&1 || return 1
  mount -o remount,rw ${tmpdir}/c > /dev/null 2>&1 || { _cleanup_tmrc $tmpdir; return 2; }
  mount -o remount,ro ${tmpdir}/c > /dev/null 2>&1 || { _cleanup_tmrc $tmpdir; return 3; }
  _cleanup_tmrc $tmpdir
  return 0
}


# download a given file from the backend storage
# @param noproxy  (optional)
get_item() {
  local url="$1"
  local noproxy="$2"

  if [ x"$noproxy" != x"" ]; then
    unset http_proxy && curl "$url" 2>/dev/null
  else
    curl "$url" 2>/dev/null
  fi
}


# checks if the right number of arguments was provided
# if the wrong number was provided it will kill the script after printing the
# usage text and an error message
#
# @param expected_parameter_count   number of expected parameters
# @param provided_parameter_count   number of provided parameters
check_parameter_count() {
  local expected_parameter_count=$1
  local provided_parameter_count=$2

  if [ $provided_parameter_count -lt $expected_parameter_count ]; then
    usage "Too few arguments provided"
  fi
  if [ $provided_parameter_count -gt $expected_parameter_count ]; then
    usage "Too many arguments provided"
  fi
}


# mangles the repository name into a fully qualified repository name
#
# @param repository_name       the repository name given by the user
# @return                      echoes the correct repository name to use
get_repository_name() {
  local repository_name=$1
  echo $(cvmfs_mkfqrn $repository_name)
}


# checks the parameter count for a situation where we might be able to guess
# the repository name based on the repositories present in the system
# Note: if the parameter count does not fit or if guessing is impossible,
#       this will print the usage string with an error message and exit
# Note: this method is commonly used right before invoking
#       `get_or_guess_repository_name` to check its preconditions and report
#       error before actually doing something wrong
#
# @param provided_parameter_count  number of parameters provided by the user
# @param allow_multiple_names      switches off the usage print for too many
#                                  detected script parameters (see next fn)
check_parameter_count_with_guessing() {
  local provided_parameter_count=$1
  local allow_multiple_names=$2

  if [ $provided_parameter_count -lt 1 ]; then
    # check if we have not _exactly_ one repository present
    if [ $(ls /etc/cvmfs/repositories.d/ | wc -l) -ne 1 ]; then
      usage "Please provide a repository name"
    fi
  fi

  if [ $provided_parameter_count -gt 1 ] && \
     [ x"$allow_multiple_names" = x"" ]; then
    usage "Too many arguments provided"
  fi

  return 0
}


# checks the parameter count when we accept more than one repository for the
# command.
# Note: this method prints an error message if appropriate and exists the script
#       execution
#
# @param provided_parameter_count  number of parameters provided by the user
check_parameter_count_for_multiple_repositories() {
  local provided_parameter_count=$1
  check_parameter_count_with_guessing $provided_parameter_count allow_multiple
  return $?
}


# mangles the repository name into a fully qualified repository name
# if there was no repository name given and there is only one repository present
# in the system, it automatically returns the name of this one.
#
# @param repository_name  the name of the repository to work on (might be empty)
# @return                 echoes a suitable repository name
get_or_guess_repository_name() {
  local repository_name=$1

  if [ "x$repository_name" = "x" ]; then
    echo $(get_repository_name $(ls /etc/cvmfs/repositories.d))
  else
    echo $(get_repository_name $repository_name)
  fi
}


# guesses a list of repository names based on file system wildcards
#
# @param ...    all repository hints provided by the user of the script
#               Like: test.local repo.* *.cern.ch
get_or_guess_multiple_repository_names() {
  local repo_dir="/etc/cvmfs/repositories.d"
  local repo_names=""

  if [ $# -eq 0 ]; then
    repo_names=$(get_or_guess_repository_name)
    echo $repo_names
    return 0;
  fi

  for input_pattern in $@; do
    local names="$(ls --directory $repo_dir/$input_pattern 2>/dev/null)"
    if [ x"$names" = x"" ]; then
      repo_names="$repo_names $input_pattern"
    else
      for name in $names; do
        if ! contains "$repo_names" $(basename $name); then
          repo_names="$repo_names $(basename $name)"
        fi
      done
    fi
  done

  echo "$repo_names"
}


# looks for traces of CernVM-FS 2.0.x which is incompatible with CernVM-FS 2.1.x
# and interferes with each other
foreclose_legacy_cvmfs() {
  local found_something=0

  # This can potentially prevent 2.0 to 2.1 migration
  #if [ $(ls /srv/cvmfs/ 2>/dev/null | wc -l) -eq 1 ]; then
  #  if [ -d /srv/cvmfs/*/pub ] || [ -d /srv/cvmfs/*/shadow ]; then
  #    echo "found legacy repo structure in /srv/cvmfs" 1>&2
  #    found_something=1
  #  fi
  #fi

  if [ -f /etc/cvmfs/server.conf ] || [ -f /etc/cvmfs/replica.conf ]; then
    echo "found legacy configuration files in /etc/cvmfs" 1>&2
    found_something=1
  fi

  if which cvmfs-sync     > /dev/null 2>&1 || \
     which cvmfs_scrub    > /dev/null 2>&1 || \
     which cvmfs_snapshot > /dev/null 2>&1 || \
     which cvmfs_zpipe    > /dev/null 2>&1 || \
     which cvmfs_pull     > /dev/null 2>&1 || \
     which cvmfs_unsign   > /dev/null 2>&1; then
    echo "found legacy CernVM-FS executables" 1>&2
    found_something=1
  fi

  if [ -f /lib/modules/*/extra/cvmfsflt/cvmfsflt.ko ]; then
    echo "found CernVM-FS 2.0.x kernel module" 1>&2
    found_something=1
  fi

  if [ $found_something -ne 0 ]; then
    echo "found traces of CernVM-FS 2.0.x! You should remove them before proceeding!"
    exit 1
  fi

  return $found_something
}


# checks and warns in inconsistent repository states.
#
# @param name  the FQRN of the repository to be checked
health_check() {
  local name=$1

  # for stratum 1 repositories there are no health checks
  if is_stratum1 $name; then
    return 0
  fi

  # check mounted union file system
  if ! is_mounted "/cvmfs/$name"; then
    die "/cvmfs/$name is not mounted properly."
  fi

  # check mounted read-only cvmfs client
  if ! is_mounted "/var/spool/cvmfs/$name/rdonly"; then
    die "/var/spool/cvmfs/$name/rdonly is not mounted properly."
  fi

  # check transaction status
  if is_in_transaction $name; then
    if ! is_mounted "/cvmfs/$name" "^.* rw[, ].*$"; then
      die "$name is in a transaction but /cvmfs/$name is not mounted read/write"
    fi
  else
    if ! is_mounted "/cvmfs/$name" "^.* ro[, ].*$"; then
      die "$name is not in a transaction but /cvmfs/$name is mounted read-only"
    fi
  fi
}


create_master_key() {
  local name=$1
  local user=$2

  master_key="/etc/cvmfs/keys/$name.masterkey"
  master_pub="/etc/cvmfs/keys/$name.pub"

  echo -n "Creating CernVM-FS master key for $name in $master_pub... "
  openssl genrsa -out $master_key 2048 > /dev/null 2>&1
  openssl rsa -in $master_key -pubout -out $master_pub > /dev/null 2>&1
  chmod 400 $master_key
  chmod 444 $master_pub
  chown $user $master_key $master_pub
  echo "done"
}


create_cert() {
  local name=$1
  local user=$2

  local key; key="/etc/cvmfs/keys/$name.key"
  local csr; csr="/etc/cvmfs/keys/$name.csr"
  local crt; crt="/etc/cvmfs/keys/$name.crt"

  # Create self-signed certificate
  echo -n "Creating self-signed certificate for $name in $crt... "
  openssl genrsa -out $key 2048 > /dev/null 2>&1
  openssl req -new -subj "/C=/ST=/L=/O=/OU=/CN=$name CernVM-FS Release Managers" -key $key -out $csr > /dev/null 2>&1
  openssl x509 -req -days 365 -in $csr -signkey $key -out $crt > /dev/null 2>&1
  rm -f $csr
  chmod 444 $crt
  chmod 400 $key
  chown $user $crt $key
  echo "done"
}


create_whitelist() {
  local name=$1
  local user=$2
  local spooler_definition=$3
  local temp_dir=$4

  local whitelist
  whitelist=${temp_dir}/whitelist.$name

  echo -n "Signing 30 day whitelist with master key... "
  echo `date -u "+%Y%m%d%H%M%S"` > ${whitelist}.unsigned
  echo "E`date -u --date='next month' "+%Y%m%d%H%M%S"`" >> ${whitelist}.unsigned
  echo "N$name" >> ${whitelist}.unsigned
  if [ "x$CVMFS_HASH_ALGORITHM" = "xrmd160" ]; then
    fingerprint="$(openssl x509 -fingerprint -rmd160 -in /etc/cvmfs/keys/${name}.crt | grep 'RIPEMD160 Fingerprint' | sed 's/RIPEMD160 Fingerprint=//')-RMD160"
    echo "$fingerprint" >> ${whitelist}.unsigned
  else
    openssl x509 -fingerprint -sha1 -in /etc/cvmfs/keys/${name}.crt | grep "SHA1 Fingerprint" | sed 's/SHA1 Fingerprint=//' >> ${whitelist}.unsigned
  fi

  local hash;
  if [ "x$CVMFS_HASH_ALGORITHM" = "xrmd160" ]; then
    hash="`openssl rmd160 < ${whitelist}.unsigned | tr -d '\n' | tail -c40`-rmd160"
  else
    hash=`openssl sha1 < ${whitelist}.unsigned | tr -d '\n' | tail -c40`
  fi
  echo "--" >> ${whitelist}.unsigned
  echo $hash >> ${whitelist}.unsigned
  echo -n $hash > ${whitelist}.hash
  openssl rsautl -inkey /etc/cvmfs/keys/${name}.masterkey -sign -in ${whitelist}.hash -out ${whitelist}.signature
  cat ${whitelist}.unsigned ${whitelist}.signature > $whitelist
  chown $user $whitelist

  rm -f ${whitelist}.unsigned ${whitelist}.signature ${whitelist}.hash
  cvmfs_swissknife upload -i $whitelist -o .cvmfswhitelist -r $spooler_definition
  rm -f $whitelist
  echo "done"
}


# figures out the time to expiry of the repository's whitelist
#
# @param stratum0  path/URL to stratum0 storage
# @return          number of seconds until expiry (negativ if already expired)
get_expiry() {
  local stratum0=$1

  local expires=$(get_item $stratum0/.cvmfswhitelist 'noproxy' | head -2 | tail -1 | tail -c15)
  if echo $expires | grep -q -E --invert-match '^[0-9]{14}$'; then
    echo -1
    return 1
  fi
  local year=$(echo $expires | head -c4)
  local month=$(echo $expires | head -c6 | tail -c2)
  local day=$(echo $expires | head -c8 | tail -c2)
  local hour=$(echo $expires | head -c10 | tail -c2)
  local minute=$(echo $expires | head -c12 | tail -c2)
  local second=$(echo $expires | head -c14 | tail -c2)
  local expires_fmt="${year}-${month}-${day} ${hour}:${minute}:${second}"
  local expires_num=$(date -u -d "$expires_fmt" +%s)

  local now=$(/bin/date -u +%s)
  local valid_countdown=$(( $expires_num-$now ))
  echo $valid_countdown
}


# checks if the repository's whitelist is valid
#
# @param stratum0  path/URL to stratum0 storage
# @return          0 if whitelist is still valid
check_expiry() {
  local stratum0=$1
  local expiry="-1"

  expiry=$(get_expiry $stratum0)
  if [ $? -ne 0 ]; then
    echo "Failed to retrieve repository expiry date" >&2
    return 1
  fi

  [ $expiry -ge 0 ]
}


check_upstream_validity() {
  local upstream=$1
  local silent=0
  if [ $# -gt 1 ]; then
    silent=1;
  fi

  # checks if $upstream contains _exactly three_ comma separated data fields
  if echo $upstream | grep -q "^[^,]*,[^,]*,[^,]*$"; then
    return 0
  fi

  if [ $silent -ne 1 ]; then
    usage "The given upstream definition (-u) is invalid. Should look like:
      <spooler type> , <tmp directory> , <spooler configuration>"
  fi
  return 1
}

check_upstream_type() {
  local upstream=$1
  local needle_type=$2

  if [ x$(echo "$upstream" | cut -d, -f1) = x"$needle_type" ]; then
    return 0
  else
    return 1
  fi
}

is_local_upstream() {
  local upstream=$1
  check_upstream_type $upstream "local"
  return $?
}

is_riak_upstream() {
  local upstream=$1
  check_upstream_type $upstream "riak"
  return $?
}

get_upstream_config() {
  local upstream=$1
  echo "$upstream" | cut -d, -f3-
}

make_upstream() {
  local type_name=$1
  local tmp_dir=$2
  local config_string=$3
  echo "$type_name,$tmp_dir,$config_string"
}


reload_apache() {
   echo -n "Reloading Apache... "
   ${SERVICE_BIN} ${APACHE_SERVICE} reload > /dev/null
   echo "done"
}

restart_apache() {
  ${SERVICE_BIN} ${APACHE_SERVICE} restart > /dev/null
}


# lowers restrictions of hardlink creation if needed
# allows AUFS to properly whiteout files without root privileges
# Note: this function requires sudo
lower_hardlink_restrictions() {
  if [ -f /proc/sys/kernel/yama/protected_nonaccess_hardlinks ] && \
     [ $(cat /proc/sys/kernel/yama/protected_nonaccess_hardlinks) -ne 0 ]; then
    # disable hardlink restrictions at runtime
    sysctl -w kernel.yama.protected_nonaccess_hardlinks=0 > /dev/null 2>&1 || return 1

    # change sysctl.conf to make the change persist reboots
    cat >> /etc/sysctl.conf << EOF

# added by CVMFS to allow proper whiteout of files in AUFS
# when creating or altering repositories on this machine.
kernel.yama.protected_nonaccess_hardlinks=0
EOF
    echo "Note: permanently disabled kernel option: kernel.yama.protected_nonaccess_hardlinks"
  fi

  return 0
}


# cvmfs requires a couple of apache modules to be enabled when running on
# an ubuntu machine. This enables these modules on an ubuntu installation
# Note: this function requires sudo
ensure_enabled_apache_modules() {
  which a2enmod > /dev/null 2>&1    || return 0
  which apache2ctl > /dev/null 2>&1 || return 0

  local restart=0
  local retcode=0
  local modules="headers expires"

  for module in $modules; do
    apache2ctl -M 2>/dev/null | grep -q "$module" && continue
    a2enmod $module > /dev/null 2>&1 || { echo "Warning: failed to enable apache2 module $module"; retcode=1; }
    restart=1
  done

  # restart apache if needed
  if [ $restart -ne 0 ]; then
    restart_apache 2>/dev/null | { echo "Warning: Failed to restart apache after enabling necessary modules"; retcode=2; }
  fi

  return $retcode
}


create_repository_skeleton() {
  local directory=$1
  local user=$2

  echo -n "Creating repository skeleton in ${directory}..."
  mkdir -p ${directory}/data
  local i=0
  while [ $i -lt 256 ]
  do
    mkdir -p ${directory}/data/$(printf "%02x" $i)
    i=$(($i+1))
  done
  mkdir -p ${directory}/data/txn
  if [ x$(id -un) != x$user ]; then
    chown -R $user ${directory}/
  fi
  if has_selinux; then
    chcon -Rv --type=httpd_sys_content_t ${directory}/ > /dev/null
  fi
  echo "done"
}


get_cvmfs_owner() {
  local name=$1
  local owner=$2
  local cvmfs_owner

  if [ "x$owner" = "x" ]; then
    read -p "Owner of $name [$(whoami)]: " cvmfs_owner
    [ x"$cvmfs_owner" = x ] && cvmfs_owner=$(whoami)
  else
    cvmfs_owner=$owner
  fi
  check_user $cvmfs_user || return 1
  echo $cvmfs_owner
}


set_ro_root_hash() {
  local name=$1
  local root_hash=$2
  local client_config=/var/spool/cvmfs/${name}/client.local

  if grep -q ^CVMFS_ROOT_HASH= ${client_config}; then
    sed -i -e "s/CVMFS_ROOT_HASH=.*/CVMFS_ROOT_HASH=${root_hash}/" $client_config
  else
    echo "CVMFS_ROOT_HASH=${root_hash}" >> $client_config
  fi
}


_process_dirtab_is_readable() {
  local dirtab_entry="$1"
  for candidate in $dirtab_entry; do
    if [ ! -r "$candidate" ]; then
      echo "WARNING: cannot apply .cvmfsdirtab entry $candidate" >&2
      return 1
    fi
  done
}

_process_dirtab_is_exclusion() {
  local dirtab_entry="$1"
  echo "$dirtab_entry" | grep -q '^!.*'
}

_process_dirtab_is_excluded() {
  local dirtab_path="$1"
  local candidate_path="$2"
  local old_ifs="$IFS"
  local exclude=0
  IFS=$'
'
  for dirtab_entry in $(cat "$dirtab_path"); do
    if _process_dirtab_is_exclusion "$dirtab_entry"; then
      local pattern="$(echo "$dirtab_entry" | sed -e 's/^!\s*\/\?\(.*\)$/\1/')"
      pattern="$(dirname $dirtab_path)/$pattern"
      case "$candidate_path" in
        $pattern) exclude=1; break;;
      esac
    fi
  done
  IFS="$old_ifs"
  [ $exclude -eq 1 ]
}

process_dirtab() {
  local name=$1
  local verbose="$2"
  local base_path="/cvmfs/${name}"
  local dirtab_path="${base_path}/.cvmfsdirtab"
  local old_ifs="$IFS"

  if [ ! -f $dirtab_path ]; then
    return 0
  fi

  echo "Auto-creating nested catalogs (${dirtab_path})... "
  IFS=$'
'
  for dirtab_entry in $(cat "$dirtab_path"); do
    _process_dirtab_is_exclusion "$dirtab_entry" && continue

    local dirtab_entry_path="$base_path$dirtab_entry"
    _process_dirtab_is_readable $dirtab_entry_path || continue
    for candidate in $dirtab_entry_path; do
      [ -d $candidate ]                 || continue
      [ ! -f $candidate/.cvmfscatalog ] || continue

      if _process_dirtab_is_excluded $dirtab_path $candidate; then
        [ x"$verbose" != x"" ] && echo "Ignoring $candidate"
      else
        echo "Auto-creating nested catalog in $candidate"
        touch "$candidate/.cvmfscatalog"
      fi
    done
  done
  IFS="$old_ifs"
}

migrate_legacy_dirtab() {
  local name=$1
  local dirtab_path="/cvmfs/${name}/.cvmfsdirtab"
  local tmp_dirtab=$(mktemp)

  cp -f "$dirtab_path" "$tmp_dirtab"                           || return 1
  transaction $name > /dev/null                                || return 2
  cat "$tmp_dirtab" | sed -e 's/\(.*\)/\1\/\*/' > $dirtab_path || return 3
  publish $name > /dev/null                                    || return 4
  rm -f "$tmp_dirtab"                                          || return 5
}


# writes apache configuration file
# This figures out where to put the apache configuration file depending
# on the running apache version
# Note: Configuration file content is expected to come through stdin
#
# @param   file_name  the name of the apache config file (no path!)
# @return             0 on succes
create_apache_config_file() {
  local file_name=$1
  local conf_path
  conf_path="$(get_apache_conf_path)"

  # create (or append) the conf file
  cat - >> ${conf_path}/${file_name} || return 1

  # the new apache requires the enable the config afterwards
  if [ x"$(get_apache_conf_mode)" = x"$APACHE_CONF_MODE_NEW" ]; then
    a2enconf $file_name > /dev/null || return 2
  fi

  return 0
}


# removes apache config files dependent on the apache version in place
# Note: As of apache 2.4.x `a2disconf` needs to be called before removal
#
# @param   file_name  the name of the conf file to be removed (no path!)
# @return  0 on successful removal
remove_apache_config_file() {
  local file_name=$1
  local conf_path
  conf_path="$(get_apache_conf_path)/${file_name}"

  # disable configuration on newer apache versions
  if [ x"$(get_apache_conf_mode)" = x"$APACHE_CONF_MODE_NEW" ]; then
    a2disconf $file_name > /dev/null 2>&1 || return 1
  fi

  # remove configuration file
  rm -f $conf_path
}


# puts all configuration files in place that are need for a stratum0 repository
#
# @param name        the name of the repository
# @param upstream    the upstream definition of the future repository
# @param stratum0    the URL of the stratum0 http entry point
# @param cvmfs_user  the owning user of the repository
create_config_files_for_new_repository() {
  local name=$1
  local upstream=$2
  local stratum0=$3
  local cvmfs_user=$4
  local unionfs=$5
  local hash_algo=$6

  # other configurations
  local spool_dir="/var/spool/cvmfs/${name}"
  local scratch_dir="${spool_dir}/scratch"
  local rdonly_dir="${spool_dir}/rdonly"
  local temp_dir="${spool_dir}/tmp"
  local cache_dir="${spool_dir}/cache"

  mkdir -p /etc/cvmfs/repositories.d/${name}
  cat > /etc/cvmfs/repositories.d/${name}/server.conf << EOF
# Created by cvmfs_server.
CVMFS_CREATOR_VERSION=$(cvmfs_version_string)
CVMFS_REPOSITORY_NAME=$name
CVMFS_REPOSITORY_TYPE=stratum0
CVMFS_USER=$cvmfs_user
CVMFS_UNION_DIR=/cvmfs/$name
CVMFS_SPOOL_DIR=$spool_dir
CVMFS_STRATUM0=$stratum0
CVMFS_UPSTREAM_STORAGE=$upstream
CVMFS_USE_FILE_CHUNKING=$CVMFS_DEFAULT_USE_FILE_CHUNKING
CVMFS_MIN_CHUNK_SIZE=$CVMFS_DEFAULT_MIN_CHUNK_SIZE
CVMFS_AVG_CHUNK_SIZE=$CVMFS_DEFAULT_AVG_CHUNK_SIZE
CVMFS_MAX_CHUNK_SIZE=$CVMFS_DEFAULT_MAX_CHUNK_SIZE
CVMFS_CATALOG_ENTRY_WARN_THRESHOLD=$CVMFS_DEFAULT_CATALOG_ENTRY_WARN_THRESHOLD
CVMFS_UNION_FS_TYPE=$unionfs
CVMFS_HASH_ALGORITHM=$hash_algo
EOF

  # make sure that the config file does not exist, yet
  remove_apache_config_file "cvmfs.${name}.conf" || true

  create_apache_config_file "cvmfs.${name}.conf" << EOF
# Created by cvmfs_server.  Don't touch.
EOF

  # ONLY FOR LOCAL UPSTREAM
  if is_local_upstream $upstream; then
    local repository_dir=$(get_upstream_config $upstream)
    create_apache_config_file "cvmfs.${name}.conf" << EOF
# Translation URL to real pathname
Alias /cvmfs/$name ${repository_dir}
<Directory "${repository_dir}">
    Options -MultiViews
    AllowOverride All
    $(get_compatible_apache_allow_from_all_config)

    EnableMMAP Off
    EnableSendFile Off

    AddType application/x-cvmfs .cvmfspublished .cvmfswhitelist

    Header unset Last-Modified
    FileETag None

    ExpiresActive On
    ExpiresDefault "access plus 3 days"
    ExpiresByType text/html "access plus 5 minutes"
    ExpiresByType application/x-cvmfs "access plus 2 minutes"
</Directory>
EOF

  # ONLY FOR RIAK UPSTREAM
  elif is_riak_upstream $upstream; then
    local riak_urls=$(get_upstream_config $upstream)
    cat > /etc/cvmfs/repositories.d/${name}/riak.conf << EOF
# Created by cvmfs_server.
CVMFS_RIAK_URLS=$riak_urls
EOF
  fi

  cat > /etc/cvmfs/repositories.d/${name}/client.conf << EOF
# Created by cvmfs_server.  Don't touch.
CVMFS_CACHE_BASE=$cache_dir
CVMFS_RELOAD_SOCKETS=$cache_dir
CVMFS_QUOTA_LIMIT=4000
CVMFS_SERVER_URL=$stratum0
CVMFS_HTTP_PROXY=DIRECT
CVMFS_PUBLIC_KEY=/etc/cvmfs/keys/${name}.pub
CVMFS_TRUSTED_CERTS=/etc/cvmfs/repositories.d/${name}/trusted_certs
CVMFS_CHECK_PERMISSIONS=yes
CVMFS_IGNORE_SIGNATURE=no
CVMFS_AUTO_UPDATE=no
CVMFS_NFS_SOURCE=no
EOF
}


create_spool_area_for_new_repository() {
  local name=$1
  local create_skeleton=0

  if [ $# -gt 1 ]; then
    create_skeleton=1
  fi

  # gather repository information from configuration file
  load_repo_config $name
  local spool_dir=$CVMFS_SPOOL_DIR
  local scratch_dir="${spool_dir}/scratch"
  local rdonly_dir="${spool_dir}/rdonly"
  local temp_dir="${spool_dir}/tmp"
  local cache_dir="${spool_dir}/cache"

  mkdir -p /cvmfs/$name $scratch_dir $rdonly_dir $temp_dir $cache_dir
  chown -R $CVMFS_USER /cvmfs/$name/ $spool_dir/
  if [ $create_skeleton -eq 1 ] && is_local_upstream $CVMFS_UPSTREAM_STORAGE; then
    local repository_dir
    repository_dir=$(get_upstream_config $CVMFS_UPSTREAM_STORAGE)
    create_repository_skeleton $repository_dir $CVMFS_USER > /dev/null
  fi
}


setup_and_mount_new_repository() {
  local name=$1
  local unionfs=$2

  # get repository information
  load_repo_config $name
  local rdonly_dir="${CVMFS_SPOOL_DIR}/rdonly"
  local scratch_dir="${CVMFS_SPOOL_DIR}/scratch"

  local selinux_context=""
  if [ $unionfs = "overlayfs" ]; then
      echo -n "(overlayfs) "
      if has_selinux && try_mount_remount_cycle_overlayfs; then
        selinux_context="context=\"system_u:object_r:default_t:s0\""
      fi
      cat >> /etc/fstab << EOF
cvmfs2#$name $rdonly_dir fuse allow_other,config=/etc/cvmfs/repositories.d/${name}/client.conf:${CVMFS_SPOOL_DIR}/client.local,cvmfs_suid 0 0 # added by CernVM-FS for $name
overlayfs_$name /cvmfs/$name overlayfs upperdir=${scratch_dir},lowerdir=${rdonly_dir},ro,$selinux_context 0 0 # added by CernVM-FS for $name
EOF
  else
      echo -n "(aufs) "
      if has_selinux && try_mount_remount_cycle_aufs; then
        selinux_context="context=\"system_u:object_r:default_t:s0\""
      fi
      cat >> /etc/fstab << EOF
cvmfs2#$name $rdonly_dir fuse allow_other,config=/etc/cvmfs/repositories.d/${name}/client.conf:${CVMFS_SPOOL_DIR}/client.local,cvmfs_suid 0 0 # added by CernVM-FS for $name
aufs_$name /cvmfs/$name aufs br=${scratch_dir}=rw:${rdonly_dir}=rr,udba=none,ro,$selinux_context 0 0 # added by CernVM-FS for $name
EOF
  fi
  sudo -H -u $cvmfs_user sh -c "touch ${CVMFS_SPOOL_DIR}/client.local"
  mount $rdonly_dir > /dev/null || return 1
  mount /cvmfs/$name
}


print_new_repository_notice() {
  local name=$1
  local cvmfs_user=$2

  echo "\

Before you can install anything, call \`cvmfs_server transaction\`
to enable write access on your repository. Then install your
software in /cvmfs/$name as user $cvmfs_user.
Once you're happy, publish using \`cvmfs_server publish\`

For client configuration, have a look at 'cvmfs_server info'

If you go for production, backup you software signing keys in /etc/cvmfs/keys/!"
}


file_descriptor_warning_and_question() {
  local name=$1
  echo "\

WARNING! There are open read-only file descriptors in /cvmfs/$name
  --> This is potentially harmful and might cause problems later on.
      We can anyway perform the requested operation, but this will most likely
      break other processes with open file descriptors on /cvmfs/$name!

      The following fuser report might show the processes with open file handles
      "

  fuser -v -m /cvmfs/$name 2>&1 | grep -v "^Cannot stat file" || true

  echo -n "\

         Do you want to proceed anyway? (y/N) "

  local reply="n"
  read reply
  if [ "$reply" != "y" ] && [ "$reply" != "Y" ]; then
    echo "aborted."
    exit 1
  fi

  return 0
}


handle_read_only_file_descriptors_on_mount_point() {
  local name=$1

  if [ $(count_rd_only_fds /cvmfs/$name) -eq 0 ]; then
    return 0
  else
    file_descriptor_warning_and_question $name # might abort...
    return 1
  fi
}


################################################################################
#                                                                              #
#                                Sub Commands                                  #
#                                                                              #
################################################################################


alterfs() {
  local master_replica=-1
  local name

  # parameter handling
  OPTIND=1
  while getopts "m:" option; do
    case $option in
      m)
        if [ x$OPTARG = "xon" ]; then
          master_replica=1
        elif [ x$OPTARG = "xoff" ]; then
          master_replica=0
        else
          usage "Command alterfs: parameter -m expects 'on' or 'off'"
        fi
      ;;
      ?)
        shift $(($OPTIND-2))
        usage "Command alterfs: Unrecognized option: $1"
      ;;
    esac
  done

  # get repository name
  shift $(($OPTIND-1))
  check_parameter_count_with_guessing $#
  name=$(get_or_guess_repository_name $1)

  # sanity checks
  check_repository_existence $name || die "The repository $name does not exist"
  [ $master_replica -ne -1 ] || usage "Command alterfs: What should I change?"
  is_root || die "Only root can alter a repository"

  # gather repository information
  load_repo_config $name
  local temp_dir="${CVMFS_SPOOL_DIR}/tmp"

  # do what you've been asked for
  local success=1
  if is_master_replica $name && [ $master_replica -eq 0 ]; then
    echo -n "Disallowing Replication of this Repository... "
    cvmfs_swissknife remove -o ".cvmfs_master_replica" -r $CVMFS_UPSTREAM_STORAGE > /dev/null || success=0
    if [ $success -ne 1 ]; then
      echo "fail!"
      return 1
    else
      echo "done"
    fi
  elif ! is_master_replica $name && [ $master_replica -eq 1 ]; then
    echo -n "Allowing Replication of this Repository... "
    local master_replica="${temp_dir}/.cvmfs_master_replica"
    touch $master_replica
    cvmfs_swissknife upload -i $master_replica -o $(basename $master_replica) -r $CVMFS_UPSTREAM_STORAGE > /dev/null || success=0
    if [ $success -ne 1 ]; then
      echo "fail!"
      return 1
    else
      echo "done"
    fi
    rm -f $master_replica
  fi
}


################################################################################


mkfs() {
  local name
  local stratum0
  local upstream
  local owner
  local replicable=1
  local volatile_content=0
  local unionfs
  local hash_algo

  # parameter handling
  OPTIND=1
  while getopts "w:u:o:mf:a:v" option; do
    case $option in
      w)
        stratum0=$OPTARG
      ;;
      u)
        upstream=$OPTARG
      ;;
      o)
        owner=$OPTARG
      ;;
      m)
        replicable=1
      ;;
      f)
        unionfs=$OPTARG
      ;;
      a)
        hash_algo=$OPTARG
      ;;
      v)
        volatile_content=1
      ;;
      ?)
        shift $(($OPTIND-2))
        usage "Command mkfs: Unrecognized option: $1"
      ;;
    esac
  done

  # get repository name
  shift $(($OPTIND-1))
  check_parameter_count 1 $#
  name=$(get_repository_name $1)

  # default values
  [ x"$stratum0" = x ] && stratum0="http://localhost/cvmfs/$name"
  [ x"$upstream" = x ] && upstream=$(make_upstream "local" "/srv/cvmfs/$name/data/txn" "/srv/cvmfs/$name")
  [ x"$unionfs" = x ] && unionfs=aufs
  [ x"$hash_algo" = x ] && hash_algo=sha1

  # sanity checks
  check_repository_existence $name  && die "The repository $name already exists"
  is_root                           || die "Only root can create a new repository"
  check_upstream_validity $upstream
  is_local_upstream $upstream       || die "Import is only supported for local storage"
  if [ $unionfs = "overlayfs" ]; then
    check_overlayfs                 || die "overlayfs kernel module missing"
    echo "Warning: CernVM-FS filesystems using overlayfs may not enforce hard link semantics during publishing."
  else
    check_aufs                      || die "aufs kernel module missing"
  fi
  check_cvmfs2_client               || die "cvmfs client missing"
  check_autofs_on_cvmfs             && die "Autofs on /cvmfs has to be disabled"
  check_apache                      || die "Apache must be installed and running"
  lower_hardlink_restrictions
  ensure_enabled_apache_modules

  # repository owner dialog
  local cvmfs_user=$(get_cvmfs_owner $name $owner)
  check_user $cvmfs_user || die "No user $cvmfs_user"

  # create system-wide configuration
  echo -n "Creating configuration files... "
  create_config_files_for_new_repository $name $upstream $stratum0 $cvmfs_user $unionfs $hash_algo
  echo "done"

  # create security keys and certificates
  mkdir -p /etc/cvmfs/keys
  create_master_key $name $cvmfs_user
  create_cert $name $cvmfs_user

  # create storage and mountpoints
  echo -n "Create CernVM-FS Storage... "
  create_spool_area_for_new_repository $name "with storage skeleton"
  reload_apache > /dev/null
  echo "done"

  # get information about new repository
  load_repo_config $name
  local temp_dir="${CVMFS_SPOOL_DIR}/tmp"
  local rdonly_dir="${CVMFS_SPOOL_DIR}/rdonly"
  local scratch_dir="${CVMFS_SPOOL_DIR}/scratch"

  echo -n "Create Initial Repository... "
  create_whitelist $name $cvmfs_user $upstream $temp_dir > /dev/null
  local volatile_opt=
  if [ $volatile_content -eq 1 ]; then
    volatile_opt="-v"
    echo -n "(repository flagged volatile)... "
  fi
  sudo -H -u $cvmfs_user sh -c "cvmfs_swissknife create \
    -t $temp_dir \
    -r $upstream \
    -a $hash_algo $volatile_opt \
    -o ${temp_dir}/new_manifest" > /dev/null || die "fail! (cannot init repo)"
  sudo -H -u $cvmfs_user sh -c "cvmfs_swissknife sign \
    -c /etc/cvmfs/keys/${name}.crt \
    -k /etc/cvmfs/keys/${name}.key \
    -n $name \
    -m ${temp_dir}/new_manifest \
    -t $temp_dir \
    -r $upstream" > /dev/null || die "fail! (cannot sign repo)"
  echo "done"

  echo -n "Mounting CernVM-FS Storage... "
  setup_and_mount_new_repository $name $unionfs || die "fail!"
  echo "done"

  if [ $replicable -eq 1 ]; then
    alterfs -m on $name
  fi

  echo -n "Initial commit... "
  transaction $name > /dev/null
  echo "New CernVM-FS repository for $name" > /cvmfs/${name}/new_repository
  chown $cvmfs_user /cvmfs/${name}/new_repository
  publish $name > /dev/null
  cat $rdonly_dir/new_repository

  print_new_repository_notice $name $cvmfs_user
}


################################################################################


add_replica() {
  local name
  local alias_name
  local stratum0
  local public_key
  local upstream
  local owner
  local silence_httpd_warning=0

  # optional parameter handling
  OPTIND=1
  while getopts "o:u:n:a" option
  do
    case $option in
      u)
        upstream=$OPTARG
      ;;
      o)
        owner=$OPTARG
      ;;
      n)
        alias_name=$OPTARG
      ;;
      a)
        silence_httpd_warning=1
      ;;
      ?)
        shift $(($OPTIND-2))
        usage "Command add-replica: Unrecognized option: $1"
      ;;
    esac
  done

   # get stratum0 url and path of public key
  shift $(($OPTIND-1))
  check_parameter_count 2 $#

  stratum0=$1
  public_key=$2

  # get the name of the repository pointed to by $stratum0
  name=$(cvmfs_swissknife info -r $stratum0 -n 2>/dev/null) || die "Failed to access Stratum0 repository at $stratum0"
  if [ x$alias_name = x"" ]; then
    alias_name=$name
  else
    alias_name=$(get_repository_name $alias_name)
  fi

  # sanity checks
  is_master_replica $stratum0 || die "The repository URL $stratum0 does not point to a replicable master copy of $name"
  if check_repository_existence $alias_name; then
    if is_stratum0 $alias_name; then
      die "Repository $alias_name already exists as a Stratum0 repository.\nUse -n to create an aliased Stratum1 replica for $name on this machine."
    else
      die "There is already a Stratum1 repository $alias_name"
    fi
  fi

  # default values
  [ x"$upstream" = x ] && upstream=$(make_upstream "local" "/srv/cvmfs/$alias_name/data/txn" "/srv/cvmfs/$alias_name")

  # additional configuration
  local cvmfs_user=`get_cvmfs_owner $alias_name $owner`
  local spool_dir="/var/spool/cvmfs/${alias_name}"
  local temp_dir="${spool_dir}/tmp"
  local repository_dir;
  if is_local_upstream $upstream; then
    repository_dir=$(get_upstream_config $upstream)
  fi

  # additional sanity checks
  is_root || die "Only root can create a new repository"
  check_user $cvmfs_user || die "No user $cvmfs_user"
  if is_local_upstream $upstream && ! check_apache; then
    if [ $silence_httpd_warning -eq 1 ]; then
      echo "Warning: Apache is needed to access this CVMFS replication"
    else
      die "Apache must be installed and running"
    fi
  fi
  check_upstream_validity $upstream

  echo -n "Creating configuration files... "
  mkdir -p /etc/cvmfs/repositories.d/${alias_name}
  cat > /etc/cvmfs/repositories.d/${alias_name}/server.conf << EOF
# Created by cvmfs_server.
CVMFS_CREATOR_VERSION=$(cvmfs_version_string)
CVMFS_REPOSITORY_NAME=$name
CVMFS_REPOSITORY_TYPE=stratum1
CVMFS_USER=$cvmfs_user
CVMFS_SPOOL_DIR=$spool_dir
CVMFS_STRATUM0=$stratum0
CVMFS_UPSTREAM_STORAGE=$upstream
EOF
  cat > /etc/cvmfs/repositories.d/${alias_name}/replica.conf << EOF
# Created by cvmfs_server.
CVMFS_NUM_WORKERS=16
CVMFS_PUBLIC_KEY=$public_key
CVMFS_HTTP_TIMEOUT=10
CVMFS_HTTP_RETRIES=3
EOF
  if is_local_upstream $upstream; then
    create_apache_config_file "cvmfs.${alias_name}.conf" << EOF
# Translation URL to real pathname
Alias /cvmfs/$alias_name ${repository_dir}
<Directory "${repository_dir}">
    Options -MultiViews
    AllowOverride All
    $(get_compatible_apache_allow_from_all_config)

    EnableMMAP Off
    EnableSendFile Off

    AddType application/x-cvmfs .cvmfspublished .cvmfswhitelist

    Header unset Last-Modified
    FileETag None

    ExpiresActive On
    ExpiresDefault "access plus 3 days"
    ExpiresByType text/html "access plus 5 minutes"
    ExpiresByType application/x-cvmfs "access plus 2 minutes"
</Directory>
EOF
  fi
  echo "done"

  echo -n "Create CernVM-FS Storage... "
  mkdir -p $spool_dir
  if [ x"$repository_dir" != x ]; then
    create_repository_skeleton $repository_dir $cvmfs_user > /dev/null
    ln -s $repository_dir/data/txn $temp_dir
  else
    mkdir -p $temp_dir
  fi
  chown -R $cvmfs_user $spool_dir
  reload_apache > /dev/null
  echo "done"

  echo "\

Use 'cvmfs_server snapshot' to replicate $alias_name.
Make sure to install the repository public key in /etc/cvmfs/keys/
You might have to add the key in /etc/cvmfs/repositories.d/${alias_name}/replica.conf"
}


################################################################################


import() {
  local name
  local stratum0
  local keys_location="/etc/cvmfs/keys"
  local upstream
  local owner
  local file_ownership
  local is_legacy=0
  local show_statistics=0
  local replicable=0
  local chown_backend=0

  # parameter handling
  OPTIND=1
  while getopts "w:o:c:u:k:l:smg" option; do
    case $option in
      w)
        stratum0=$OPTARG
      ;;
      o)
        owner=$OPTARG
      ;;
      c)
        file_ownership=$OPTARG
      ;;
      u)
        upstream=$OPTARG
      ;;
      k)
        keys_location=$OPTARG
      ;;
      l)
        is_legacy=1
        ;;
      s)
        show_statistics=1
      ;;
      m)
        replicable=1
      ;;
      g)
        chown_backend=1
      ;;
      ?)
        shift $(($OPTIND-2))
        usage "Command import: Unrecognized option: $1"
      ;;
    esac
  done

  # get repository name
  shift $(($OPTIND-1))
  check_parameter_count 1 $#
  name=$(get_repository_name $1)

  # default values
  [ x"$stratum0" = x ] && stratum0="http://localhost/cvmfs/$name"
  [ x"$upstream" = x ] && upstream=$(make_upstream "local" "/srv/cvmfs/$name/data/txn" "/srv/cvmfs/$name")

  # security key pathes
  local private_key="${name}.key"
  local certificate="${name}.crt"
  local public_key="${name}.pub"
  local pki_keys="$private_key $certificate $public_key"

  # sanity checks
  check_repository_existence $name  && die "The repository $name already exists"
  is_root                           || die "Only root can create a new repository"
  check_upstream_validity $upstream
  # import from 2.0 -> 2.1 only supports aufs, not overlayfs
  check_aufs                        || die "aufs kernel module missing"
  check_cvmfs2_client               || die "cvmfs client missing"
  check_autofs_on_cvmfs             && die "Autofs on /cvmfs has to be disabled"
  check_apache                      || die "Apache must be installed and running"
  is_local_upstream $upstream       || die "Import only works locally for the moment"
  lower_hardlink_restrictions
  ensure_enabled_apache_modules
  for pki_file in $pki_keys; do
    [ -f "${keys_location}/$pki_file" ] || die "Cannot find $pki_file in $keys_location"
  done
  [ x"$keys_location" = "x" ] && die "Please provide the location of the repository security keys (-k)"

  # investigate the given repository storage for sanity
  local storage_location=$(get_upstream_config $upstream)
  [ -d $storage_location ] || die "Did not find repository storage to import at $storage_location"
  [ -f "${storage_location}/.cvmfspublished" ] && \
  [ -d "${storage_location}/data" ] || die "$storage_location does not seem to be a repository storage"
  [ -f "${storage_location}/.cvmfswhitelist" ] || die "didn't find ${storage_location}/.cvmfswhitelist"

  # repository owner dialog
  local cvmfs_user=$(get_cvmfs_owner $name $owner)
  check_user $cvmfs_user || die "No user $cvmfs_user"
  [ x"$file_ownership" = x ] && file_ownership="$(id -u $cvmfs_user):$(id -g $cvmfs_user)"
  echo $file_ownership | grep -q "^[0-9][0-9]*:[0-9][0-9]*$" || die "Unrecognized file ownership: $file_ownership | expected: <uid>:<gid>"
  local cvmfs_uid=$(echo $file_ownership | cut -d: -f1)
  local cvmfs_gid=$(echo $file_ownership | cut -d: -f2)

  # create the configuration for the new repository
  echo -n "Creating configuration files... "
  create_config_files_for_new_repository $name $upstream $stratum0 $cvmfs_user aufs
  echo "done"

  # import the old repository security keys
  echo -n "Importing the given key files... "
  local global_key_dir="/etc/cvmfs/keys"
  mkdir -p $global_key_dir
  for pki_file in $pki_keys; do
    if [ ! -f "${global_key_dir}/$pki_file" ]; then
      cp "${keys_location}/$pki_file" $global_key_dir  || die "fail! (cannot copy $pki_file)"
    fi
    chmod 444 "${global_key_dir}/${pki_file}"          || die "fail! (cannot chmod $pki_file)"
    chown $cvmfs_user "${global_key_dir}/${pki_file}"  || die "fail! (cannot chown $pki_file)"
  done
  echo "done"

  # create storage
  echo -n "Creating CernVM-FS Repository Infrastructure... "
  create_spool_area_for_new_repository $name
  reload_apache > /dev/null
  echo "done"

  # load repository configuration file
  load_repo_config $name
  local temp_dir="${CVMFS_SPOOL_DIR}/tmp"

  # import storage location
  if [ $chown_backend -ne 0 ]; then
    echo -n "Importing CernVM-FS storage... "
    chown -R $cvmfs_user $storage_location || die "fail!"
    if has_selinux; then
      chcon -Rv --type=httpd_sys_content_t $storage_location > /dev/null || die "fail!"
    fi
    echo "done"
  fi

  # migrate old catalogs
  if [ $is_legacy -ne 0 ]; then
    echo "Migrating old catalogs (may take a while)... "
    local new_manifest="${temp_dir}/new_manifest"
    local statistics_flag
    if [ $show_statistics -ne 0 ]; then
      statistics_flag="-s"
    fi
    cvmfs_swissknife migrate \
      -v "2.0.x" \
      -r $storage_location \
      -n $name \
      -u $upstream \
      -t $temp_dir \
      -k "${global_key_dir}/$public_key" \
      -o $new_manifest \
      -p $cvmfs_uid \
      -g $cvmfs_gid \
      -f \
      $statistics_flag || die "fail!"
    chown $cvmfs_user $new_manifest

    # sign new (migrated) repository revision
    echo -n "Signing newly imported Repository... "
    sudo -H -u $cvmfs_user sh -c "cvmfs_swissknife sign \
      -c ${global_key_dir}/${certificate} \
      -k ${global_key_dir}/${private_key} \
      -n $name \
      -m $new_manifest \
      -t $temp_dir \
      -r $upstream" > /dev/null || die "fail! (cannot sign repo)"
    echo "done"
  fi

  # do final setup
  echo -n "Mounting CernVM-FS Storage... "
  setup_and_mount_new_repository $name aufs || die "fail!"
  echo "done"

  # the .cvmfsdirtab semantics might need an update
  if [ $is_legacy -ne 0 ] && [ -f /cvmfs/${name}/.cvmfsdirtab ]; then
    echo -n "Migrating .cvmfsdirtab... "
    migrate_legacy_dirtab $name || die "fail!"
    echo "done"
  fi

  # make stratum0 repository replicable if requested
  if [ $replicable -eq 1 ]; then
    alterfs -m on $name
  fi

  print_new_repository_notice $name $cvmfs_user
}


################################################################################


rmfs() {
  local names
  local spool_dir
  local upstream
  local type
  local force=0
  local retcode=0

  # optional parameter handling
  OPTIND=1
  while getopts "f" option
  do
    case $option in
      f)
        force=1
      ;;
      ?)
        shift $(($OPTIND-2))
        usage "Command rmfs: Unrecognized option: $1"
      ;;
    esac
  done

  # sanity checks
  is_root || die "Only root can remove a repository"
  ensure_enabled_apache_modules

  # get repository names
  shift $(($OPTIND-1))
  check_parameter_count_for_multiple_repositories $#
  names=$(get_or_guess_multiple_repository_names $@)
  check_multiple_repository_existence "$names"

  for name in $names; do

    # better ask the user again!
    if [ $force -ne 1 ]; then
      local reply
      read -p "You are about to WIPE OUT THE CERNVM-FS REPOSITORY $name INCLUDING SIGNING KEYS!  Are you sure (y/N)? " reply
      if [ "$reply" != "y" ] && [ "$reply" != "Y" ]; then
        continue
      fi
    fi

    # get information about repository
    load_repo_config $name
    spool_dir=$CVMFS_SPOOL_DIR
    upstream=$CVMFS_UPSTREAM_STORAGE
    type=$CVMFS_REPOSITORY_TYPE

    # check if repository is compatible to the installed CernVM-FS version
    check_repository_compatibility

    # sanity checks
    [ x"$spool_dir" = x ] && { echo "Spool directory for $name is undefined"; retcode=1; continue;  }
    [ x"$upstream" = x ]  && { echo "Upstream storage for $name is undefined"; retcode=1; continue; }
    [ x"$type" = x ]      && { echo "Repository type for $name is undefined"; retcode=1; continue;  }

    # do it!
    if [ "$type" = "stratum0" ]; then
      echo -n "Unmounting CernVM-FS Area... "
      sed -i -e "/added by CernVM-FS for ${name}/d" /etc/fstab
      is_mounted "/cvmfs/$name"        && umount /cvmfs/$name
      is_mounted "${spool_dir}/rdonly" && umount ${spool_dir}/rdonly
      if [ -d /cvmfs/$name ]; then
        rmdir /cvmfs/$name
      fi
      echo "done"
    fi

    echo -n "Removing spool area... "
    rm -rf $spool_dir
    echo done

    if is_local_upstream $upstream; then
      local repository_dir=$(get_upstream_config $upstream)
      if [ "x"$repository_dir != x ]; then
        echo -n "Removing repository storage... "
        rm -rf $repository_dir
        echo "done"
      fi
    elif is_riak_upstream $upstream; then
      echo "currently Riak Storage is not wiped! TBD."
    fi

    echo -n "Removing keys and configuration... "
    if [ "$type" = stratum0 ]; then
      rm -f /etc/cvmfs/keys/$name.masterkey \
          /etc/cvmfs/keys/$name.pub \
          /etc/cvmfs/keys/$name.key \
          /etc/cvmfs/keys/$name.crt
    fi
    if is_local_upstream $upstream; then
      remove_apache_config_file "cvmfs.${name}.conf"
      reload_apache > /dev/null
    fi
    sed -i -e "/added by CernVM-FS for ${name}/d" /etc/sudoers
    rm -rf /etc/cvmfs/repositories.d/$name
    echo "done"

    echo "CernVM-FS repository $name wiped out!"

  done

  return $retcode
}


################################################################################


resign() {
  local names
  local retcode=0

  # get repository names
  check_parameter_count_for_multiple_repositories $#
  names=$(get_or_guess_multiple_repository_names $@)
  check_multiple_repository_existence "$names"

  # sanity checks
  is_root || die "Only root can resign repositories"

  for name in $names; do

    # sanity checks
    is_stratum0 $name || { echo "Repository $name is not a stratum 0 repository"; retcode=1; continue; }
    health_check $name

    # get repository information
    load_repo_config $name

    # check if repository is compatible to the installed CernVM-FS version
    check_repository_compatibility

    # do it!
    create_whitelist $name $CVMFS_USER \
        ${CVMFS_UPSTREAM_STORAGE} \
        ${CVMFS_SPOOL_DIR}/tmp

  done

  return $retcode
}


################################################################################


info() {
  local name
  local stratum0

  # get repository name
  check_parameter_count_with_guessing $#
  name=$(get_or_guess_repository_name $1)

  # sanity checks
  check_repository_existence $name || die "The repository $name does not exist"
  is_stratum0 $name || die "This is not a stratum 0 repository"

  # get repository information
  load_repo_config $name
  stratum0=$CVMFS_STRATUM0

  # do it!
  echo "Repository name: $name"
  echo "Created by CernVM-FS $(mangle_version_string $(repository_creator_version))"
  local replication_allowed="yes"
  is_master_replica $name || replication_allowed="no"
  echo "Stratum1 Replication Allowed: $replication_allowed"
  local expire_countdown=$(get_expiry $stratum0)
  if [ $expire_countdown -le 0 ]; then
    echo "Whitelist is expired"
  else
    local valid_time=$(( $expire_countdown/(3600*24) ))
    echo "Whitelist is valid for another $valid_time days"
  fi
  echo

  echo "\
Client configuration:
Add $name to CVMFS_REPOSITORIES in /etc/cvmfs/default.local
Create /etc/cvmfs/config.d/${name}.conf and set
  CVMFS_SERVER_URL=$stratum0
  CVMFS_PUBLIC_KEY=/etc/cvmfs/keys/${name}.pub
Copy /etc/cvmfs/keys/${name}.pub to the client"
}


################################################################################


lstags() {
  local name

  # get repository name
  check_parameter_count_with_guessing $#
  name=$(get_or_guess_repository_name $1)

  # sanity checks
  check_repository_existence $name || die "The repository $name does not exist"
  is_stratum0 $name || die "This is not a stratum 0 repository"

  # get repository information
  load_repo_config $name
  local base_hash=$(attr -qg root_hash ${CVMFS_SPOOL_DIR}/rdonly)
  cvmfs_swissknife tag -r $CVMFS_STRATUM0 -b $base_hash -t 0000000000000000000000000000000000000000 \
    -i 0 -s 0 -n ${name} -o ${CVMFS_SPOOL_DIR}/show_history \
    -k /etc/cvmfs/keys/${name}.pub \
    -z /etc/cvmfs/repositories.d/${name}/trusted_certs -l
  rm -f ${CVMFS_SPOOL_DIR}/show_history
}


################################################################################


check() {
  local name
  local upstream
  local repository_dir
  local check_chunks=1
  local check_integrity=0
  local tag=

  # optional parameter handling
  OPTIND=1
  while getopts "cit:" option
  do
    case $option in
      c)
        check_chunks=0
      ;;
      i)
        check_integrity=1
      ;;
      t)
        tag="-t $OPTARG"
      ;;
      ?)
        shift $(($OPTIND-2))
        usage "Command check: Unrecognized option: $1"
      ;;
    esac
  done

  # get repository name
  shift $(($OPTIND-1))
  check_parameter_count_with_guessing $#
  name=$(get_or_guess_repository_name $1)

  # sanity checks
  check_repository_existence $name || die "The repository $name does not exist"
  health_check $name

  # get repository information
  load_repo_config $name

  # check if repository is compatible to the installed CernVM-FS version
  check_repository_compatibility

  # more sanity checks
  if is_riak_upstream $upstream; then
    echo "checking of Riak storage is not supported. TBD"
    return
  fi

  upstream=$CVMFS_UPSTREAM_STORAGE
  repository_dir=$(get_upstream_config $upstream)

  # do it!
  if [ $check_integrity -ne 0 ]; then
    echo
    echo "Checking Storage Integrity of $name ... (may take a while)"
    cvmfs_swissknife scrub -r ${repository_dir}/data || die "FAIL!"
  fi

  [ "x$CVMFS_LOG_LEVEL" != x ] && log_level_param="-l $CVMFS_LOG_LEVEL"
  [ $check_chunks -ne 0 ]      && check_chunks_param="-c"

  echo "Verifying Catalog Integrity of $name ..."
  cvmfs_swissknife check $tag $check_chunks_param $log_level_param -r $repository_dir
}


################################################################################


list() {
  for repository in /etc/cvmfs/repositories.d/*; do
    if [ "x$repository" = "x/etc/cvmfs/repositories.d/*" ]; then
      return 0
    fi
    if [ -f $repository ]; then
      echo "Warning: unexpected file '$repository' in directory /etc/cvmfs/repositories.d/"
      continue
    fi
    local name=$(basename $repository)
    load_repo_config $name

    # figure out the schema version of the repository
    local version_info=""
    local creator_version=$(repository_creator_version)
    if ! version_equal $creator_version; then
      local compatible=""
      if ! check_repository_compatibility "nokill"; then
        compatible=" INCOMPATIBLE"
      fi
      version_info="(created by$compatible CernVM-FS $(mangle_version_string $creator_version))"
    else
      version_info=""
    fi

    # collect additional information about aliased stratum1 repos
    local stratum1_info=""
    if is_stratum1 $name; then
      if [ "$CVMFS_REPOSITORY_NAME" != "$name" ]; then
        stratum1_info="-> $CVMFS_REPOSITORY_NAME"
      fi
    fi

    # find out if the repository is currently in a transaction
    local transaction_info=""
    if is_stratum0 $name && is_in_transaction $name; then
      transaction_info=" - in transaction"
    fi

    # check if the repository whitelist is expired
    local whitelist_info=""
    if is_stratum0 $name && ! check_expiry $CVMFS_STRATUM0; then
      whitelist_info=" - whitelist expired"
    fi

    # print out repository information list
    echo "$name ($CVMFS_REPOSITORY_TYPE$transaction_info$whitelist_info) $stratum1_info $version_info"
    CVMFS_CREATOR_VERSION=""
  done
}


################################################################################


transaction() {
  local names
  local spool_dir
  local stratum0
  local base_hash
  local remote_hash
  local force=0
  local retcode=0

  # optional parameter handling
  OPTIND=1
  while getopts "f" option
  do
    case $option in
      f)
        force=1
      ;;
      ?)
        shift $(($OPTIND-2))
        usage "Command transaction: Unrecognized option: $1"
      ;;
    esac
  done

  # get repository names
  shift $(($OPTIND-1))
  check_parameter_count_for_multiple_repositories $#
  names=$(get_or_guess_multiple_repository_names $@)
  check_multiple_repository_existence "$names"

  # go through the repositories
  for name in $names; do

    # sanity checks
    is_stratum0 $name || { echo "Repository $name is not a stratum 0 repository"; retcode=1; continue; }
    health_check $name

    # get repository information
    load_repo_config $name
    spool_dir=$CVMFS_SPOOL_DIR
    stratum0=$CVMFS_STRATUM0
    base_hash=$(attr -qg root_hash ${spool_dir}/rdonly)
    remote_hash=$(cvmfs_swissknife info -r $stratum0 -c)

    # more sanity checks
    check_repository_compatibility
    if [ $force -eq 0 ]; then
      is_in_transaction $name && { echo "Repository $name is already in a transaction"; continue; }
    fi
    check_expiry $stratum0 || { echo "Repository whitelist for $name is expired!"; retcode=1; continue; }
    [ $(get_expiry $stratum0) -le $(( 12 * 60 * 60 )) ] && { echo "Warning: Repository whitelist stays valid for less than 12 hours!"; }

    # do it!
    transaction_before_hook $name
    if [ "$base_hash" != "$remote_hash" ]; then
      echo "Repository $name has changed!  Remounting remote hash $remote_hash"
      cvmfs_suid_helper rw_umount $name
      cvmfs_suid_helper rdonly_umount $name
      set_ro_root_hash $name $remote_hash
      cvmfs_suid_helper rdonly_mount $name
      cvmfs_suid_helper rw_mount $name
    fi
    cvmfs_suid_helper open $name
    open_transaction       $name
    transaction_after_hook $name

  done

  return $retcode
}


################################################################################


abort() {
  local names
  local user
  local spool_dir
  local force=0
  local retcode=0

  # optional parameter handling
  OPTIND=1
  while getopts "f" option
  do
    case $option in
      f)
        force=1
      ;;
      ?)
        shift $(($OPTIND-2))
        usage "Command abort: Unrecognized option: $1"
      ;;
    esac
  done

  # get repository names
  shift $(($OPTIND-1))
  check_parameter_count_for_multiple_repositories $#
  names=$(get_or_guess_multiple_repository_names $@)
  check_multiple_repository_existence "$names"

  for name in $names; do

    # sanity checks
    is_stratum0 $name   || { echo "Repository $name is not a stratum 0 repository"; retcode=1; continue; }
    is_publishing $name && { echo "Repository $name is currently published (aborting abort)"; retcode=1; continue; }

    # get repository information
    load_repo_config $name
    user=$CVMFS_USER
    spool_dir=$CVMFS_SPOOL_DIR

    # more sanity checks
    check_repository_compatibility
    is_in_transaction $name || { echo "Repository $name is not in a transaction"; continue; }
    [ $(count_wr_fds /cvmfs/$name) -eq 0 ] || { echo "Open writable file descriptors on $name"; retcode=1; continue; }
    is_cwd_on_path "/cvmfs/$name" && { echo "Current working directory is in /cvmfs/$name.  Please release, e.g. by 'cd \$HOME'."; retcode=1; continue; } || true

    # better ask the user once again!
    if [ $force -ne 1 ]; then
      local reply
      read -p "You are about to DISCARD ALL CHANGES OF THE CURRENT TRANSACTION for $name!  Are you sure (y/N)? " reply
      if [ "$reply" != "y" ] && [ "$reply" != "Y" ]; then
        continue
      fi
    fi

    # check if we have open file descriptors on /cvmfs/<name>
    local use_fd_fallback=0
    handle_read_only_file_descriptors_on_mount_point $name || use_fd_fallback=1

    abort_before_hook $name
    sync
    if [ $use_fd_fallback -eq 0 ]; then
      cvmfs_suid_helper rw_umount $name
    else
      cvmfs_suid_helper rw_lazy_umount     $name
      cvmfs_suid_helper kill_cvmfs         $name
      cvmfs_suid_helper rdonly_lazy_umount $name
      cvmfs_suid_helper rdonly_mount       $name > /dev/null
    fi
    rm -rf ${spool_dir}/tmp/*
    cvmfs_suid_helper clear_scratch $name
    cvmfs_suid_helper rw_mount $name
    close_transaction $name
    abort_after_hook $name

  done

  return $retcode
}


################################################################################


publish() {
  local names
  local user
  local spool_dir
  local stratum0
  local upstream
  local debug=0
  local tweaks_option=
  local tag_name=
  local tag_channel=00
  local tag_description=
  local tag_hash=
  local add_tag=
  local remove_tag=
  local retcode=0
  local verbosity=""

  # optional parameter handling
  OPTIND=1
  while getopts "dDpa:h:c:t:r:v" option
  do
    case $option in
      d)
        debug=1
      ;;
      D)
        debug=2
      ;;
      p)
        tweaks_option="-d"
      ;;
      a)
        add_tag="-a"
        tag_name="$OPTARG"
      ;;
      h)
        add_tag="-a"
        tag_hash="-h $OPTARG"
      ;;
      c)
        add_tag="-a"
        tag_channel="$OPTARG"
      ;;
      t)
        add_tag="-a"
        tag_description="$OPTARG"
      ;;
      r)
        remove_tag="-d $OPTARG"
        if [ "x$OPTARG" = "xtrunk" -o "x$OPTARG" = "xtrunk-previous" ]; then
          echo "Warning: won't delete $OPTARG tag"
        fi
      ;;
      v)
        verbosity="-x"
      ;;
      ?)
        shift $(($OPTIND-2))
        usage "Command publish: Unrecognized option: $1"
      ;;
    esac
  done

  # get repository names
  shift $(($OPTIND-1))
  check_parameter_count_for_multiple_repositories $#
  names=$(get_or_guess_multiple_repository_names $@)
  check_multiple_repository_existence "$names"

  # sanity checks
  if [ "x$add_tag" != "x" ]; then
    [ "x$tag_name" != "x" ]               || die "Tag name missing"
    echo $tag_name | grep -q -v " "       || die "Spaces are not allowed in tag names"
    if lstags $name | cut --delimiter=' ' --fields=1 | grep -q "^$tag_name$" &&
       [ x"$tag_hash" = "x" ]; then
      die "Tag name '$tag_name' is already in use. Maybe you wanted to specify -h to move it?"
    fi
    add_tag="-a \"${tag_name}@${tag_channel}@${tag_description}\""
  fi

  for name in $names; do

    # sanity checks
    is_stratum0 $name   || die "This is not a stratum 0 repository"
    health_check $name
    is_publishing $name && die "Another publish process is active for $name"

    # get repository information
    load_repo_config $name
    user=$CVMFS_USER
    spool_dir=$CVMFS_SPOOL_DIR
    stratum0=$CVMFS_STRATUM0
    upstream=$CVMFS_UPSTREAM_STORAGE
    hash_algo=$CVMFS_HASH_ALGORITHM
    if [ x"$hash_algo" != "x" ]; then
      hash_algo="-e $hash_algo"
    fi

    # more sanity checks
    check_repository_compatibility
    check_expiry $stratum0         || { echo "Repository whitelist for $name is expired!"; retcode=1; continue; }
    is_in_transaction $name        || { echo "Repository $name is not in a transaction"; retcode=1; continue; }
    [ $(count_wr_fds /cvmfs/$name) -eq 0 ] || { echo "Open writable file descriptors on $name"; retcode=1; continue; }
    is_cwd_on_path "/cvmfs/$name" && { echo "Current working directory is in /cvmfs/$name.  Please release, e.g. by 'cd \$HOME'."; retcode=1; continue; } || true
    if [ "x$add_tag" != "x" ] && \
       lstags $name | cut --delimiter=' ' --fields=1 | grep -q "^$tag_name$" &&
       [ x"$tag_hash" = "x" ]; then
      echo "Tag name '$tag_name' is already in use for repository $name. Maybe you wanted to specify -h to move it?"
      retcode=1
      continue
    fi

    # do it!
    local swissknife="cvmfs_swissknife"

    # enable the debug mode?
    if [ $debug -ne 0 ]
    then
      if [ -f /usr/bin/cvmfs_swissknife_debug ]; then
        case $debug in
          1)
            # in case something breaks we are provided with a GDB prompt.
            swissknife="gdb --quiet --eval-command=run --eval-command=quit --args cvmfs_swissknife_debug"
          ;;
          2)
            # attach gdb and provide a prompt WITHOUT actual running the program
            swissknife="gdb --quiet --args cvmfs_swissknife_debug"
          ;;
        esac
      else
        echo -e "WARNING: compile with CVMFS_SERVER_DEBUG to allow for debug mode!\nFalling back to release mode...."
      fi
    fi

    local user_shell="sh -c"
    [ $(whoami) != $user ] && user_shell="sudo -E -H -u $user sh -c"

    # check if we have open file descriptors on /cvmfs/<name>
    local use_fd_fallback=0
    handle_read_only_file_descriptors_on_mount_point $name || use_fd_fallback=1

    process_dirtab $name $verbosity || die "Synchronization Failed! Please repair your .cvmfsdirtab file!"
    publish_before_hook $name
    publishing_lock $name
    cvmfs_suid_helper lock $name
    local base_hash=$(attr -qg root_hash ${spool_dir}/rdonly)
    local log_level=
    [ "x$CVMFS_LOG_LEVEL" != x ] && log_level="-z $CVMFS_LOG_LEVEL"

    local sync_command="$swissknife sync $verbosity -u /cvmfs/$name \
      -s ${spool_dir}/scratch \
      -c ${spool_dir}/rdonly \
      -t ${spool_dir}/tmp \
      -b $base_hash \
      -r ${upstream} \
      -w $stratum0 \
      -o ${spool_dir}/tmp/manifest \
      $hash_algo $log_level $tweaks_option"
    if [ "x$CVMFS_UNION_FS_TYPE" != "x" ]; then
      sync_command="$sync_command -f $CVMFS_UNION_FS_TYPE"
    fi
    if [ "x$CVMFS_USE_FILE_CHUNKING" = "xtrue" ]; then
      sync_command="$sync_command -p \
       -l $CVMFS_MIN_CHUNK_SIZE \
       -a $CVMFS_AVG_CHUNK_SIZE \
       -h $CVMFS_MAX_CHUNK_SIZE"
    fi
    if [ "x$CVMFS_IGNORE_XDIR_HARDLINKS" = "xtrue" ]; then
      sync_command="$sync_command -i"
    fi
    if [ "x$CVMFS_CATALOG_ENTRY_WARN_THRESHOLD" != "x" ]; then
      sync_command="$sync_command -j $CVMFS_CATALOG_ENTRY_WARN_THRESHOLD"
    fi
    local tag_command="$swissknife tag -r $stratum0 \
      -b $base_hash \
      -n $name \
      -o ${spool_dir}/tmp/history \
      -k /etc/cvmfs/keys/${name}.pub \
      -z /etc/cvmfs/repositories.d/${name}/trusted_certs \
      $add_tag $remove_tag"
    local sign_command="$swissknife sign -c /etc/cvmfs/keys/${name}.crt \
      -k /etc/cvmfs/keys/${name}.key \
      -n $name \
      -m ${spool_dir}/tmp/manifest \
      -h ${spool_dir}/tmp/history \
      -t ${spool_dir}/tmp \
      -r ${upstream}"

    $user_shell "$sync_command" || \
      (cvmfs_suid_helper open $name && die "Synchronization failed (/cvmfs/$name remounted read/write so changes can be made to transaction) \n\nExecuted Command:\n$sync_command" || die "Synchronization failed\n\nExecuted Command:\n$sync_command")
    if [ -f ${spool_dir}/tmp/manifest ]; then
      local trunk_hash=$(grep "^C" ${spool_dir}/tmp/manifest | tr -d C)
      local trunk_revision=$(grep "^S" ${spool_dir}/tmp/manifest | tr -d S)
      local trunk_size=$(grep "^B" ${spool_dir}/tmp/manifest | tr -d B)
      tag_command="$tag_command -t $trunk_hash -s $trunk_size -i $trunk_revision $tag_hash"
      echo "Tagging $name"
      $user_shell "$tag_command" || die "Tagging failed\n\nExecuted Command:\n$tag_command"
      $user_shell "$sign_command" || die "Signing failed\n\nExecuted Command:\n$sign_command"
      echo "Remounting newly created repository revision"
      sync
      if [ $use_fd_fallback -eq 1 ]; then
        cvmfs_suid_helper rw_lazy_umount     $name
        cvmfs_suid_helper kill_cvmfs         $name
        cvmfs_suid_helper rdonly_lazy_umount $name
      else
        cvmfs_suid_helper rw_umount $name
        cvmfs_suid_helper rdonly_umount $name
      fi
      set_ro_root_hash $name $trunk_hash
      cvmfs_suid_helper clear_scratch $name
      rm -rf ${spool_dir}/tmp/*
      cvmfs_suid_helper rdonly_mount $name > /dev/null
      cvmfs_suid_helper rw_mount $name
      close_transaction $name
      publish_after_hook $name
    else
      exit 1
    fi

  done

  return $retcode
}


################################################################################


rollback() {
  local name
  local user
  local spool_dir
  local stratum0
  local upstream
  local target_tag="trunk-previous"
  local force=0

  # optional parameter handling
  OPTIND=1
  while getopts "t:f" option
  do
    case $option in
      t)
        target_tag=$OPTARG
      ;;
      f)
        force=1
      ;;
      ?)
        shift $(($OPTIND-2))
        usage "Command rollback: Unrecognized option: $1"
      ;;
    esac
  done

  # get repository name
  shift $(($OPTIND-1))
  check_parameter_count_with_guessing $#
  name=$(get_or_guess_repository_name $1)

  # sanity checks
  check_repository_existence $name || die "The repository $name does not exist"
  is_stratum0 $name                || die "This is not a stratum 0 repository"
  health_check $name
  is_publishing $name              && die "Repository $name is currently being published"

  # get repository information
  load_repo_config $name
  user=$CVMFS_USER
  spool_dir=$CVMFS_SPOOL_DIR
  stratum0=$CVMFS_STRATUM0
  upstream=$CVMFS_UPSTREAM_STORAGE

  # more sanity checks
  check_repository_compatibility
  check_expiry $stratum0  || die "Repository whitelist is expired!"
  is_in_transaction $name || die "Not in a transaction"
  [ $(count_wr_fds /cvmfs/$name) -eq 0 ] || die "Open writable file descriptors on $name"
  is_cwd_on_path "/cvmfs/$name" && die "Current working directory is in /cvmfs/$name.  Please release, e.g. by 'cd \$HOME'." || true

  if [ $force -ne 1 ]; then
    local reply
    read -p "You are about to IRREVERSIBLY ROLLBACK AND REPUBLISH TAG $target_tag AS THE LATEST REVISION!  Are you sure (y/N)? " reply
    if [ "$reply" != "y" ] && [ "$reply" != "Y" ]; then
      return 1
    fi
  fi

  # check if we have open file descriptors on /cvmfs/<name>
  local use_fd_fallback=0
  handle_read_only_file_descriptors_on_mount_point $name || use_fd_fallback=1

  # do it!
  local swissknife="cvmfs_swissknife"

  local user_shell="sh -c"
  [ $(whoami) != $user ] && user_shell="sudo -E -H -u $user sh -c"

  publish_before_hook
  publishing_lock $name
  cvmfs_suid_helper lock $name
  local base_hash=$(attr -qg root_hash ${spool_dir}/rdonly)

  local rollback_command="$swissknife rollback -u $stratum0 \
    -r $upstream \
    -b $base_hash \
    -n $name \
    -k /etc/cvmfs/keys/${name}.pub \
    -z /etc/cvmfs/repositories.d/${name}/trusted_certs \
    -o ${spool_dir}/tmp/history \
    -m ${spool_dir}/tmp/manifest \
    -d ${spool_dir}/tmp \
    -t $target_tag"
  local sign_command="$swissknife sign -c /etc/cvmfs/keys/${name}.crt \
    -k /etc/cvmfs/keys/${name}.key \
    -n $name \
    -m ${spool_dir}/tmp/manifest \
    -h ${spool_dir}/tmp/history \
    -t ${spool_dir}/tmp \
    -r ${upstream}"

  $user_shell "$rollback_command" || die "Rollback failed\n\nExecuted Command:\n$rollback_command"
  local trunk_hash=$(grep "^C" ${spool_dir}/tmp/manifest | tr -d C)
  $user_shell "$sign_command" || die "Signing failed\n\nExecuted Command:\n$sign_command"
  echo "Remounting newly created repository revision"
  sync
  if [ $use_fd_fallback -eq 1 ]; then
    cvmfs_suid_helper rw_lazy_umount     $name
    cvmfs_suid_helper kill_cvmfs         $name
    cvmfs_suid_helper rdonly_lazy_umount $name
  else
    cvmfs_suid_helper rw_umount $name
    cvmfs_suid_helper rdonly_umount $name
  fi
  set_ro_root_hash $name $trunk_hash
  cvmfs_suid_helper clear_scratch $name
  rm -rf ${spool_dir}/tmp/*
  cvmfs_suid_helper rdonly_mount $name > /dev/null
  cvmfs_suid_helper rw_mount $name
  close_transaction $name
  publish_after_hook $name
}


################################################################################


snapshot() {
  local alias_names
  local name
  local user
  local spool_dir
  local stratum0
  local upstream
  local num_workers
  local public_key
  local timeout
  local retries
  local retcode=0

  # get repository names
  check_parameter_count_for_multiple_repositories $#
  alias_names=$(get_or_guess_multiple_repository_names $@)
  check_multiple_repository_existence "$alias_names"

  for alias_name in $alias_names; do

    # sanity checks
    is_stratum1 $alias_name || { echo "Repository $alias_name is not a stratum 1 repository"; retcode=1; continue; }

    # get repository information
    load_repo_config $alias_name
    . /etc/cvmfs/repositories.d/$alias_name/replica.conf
    name=$CVMFS_REPOSITORY_NAME
    user=$CVMFS_USER
    spool_dir=$CVMFS_SPOOL_DIR
    stratum0=$CVMFS_STRATUM0
    upstream=$CVMFS_UPSTREAM_STORAGE
    num_workers=$CVMFS_NUM_WORKERS
    public_key=$CVMFS_PUBLIC_KEY
    timeout=$CVMFS_HTTP_TIMEOUT
    retries=$CVMFS_HTTP_RETRIES

    # more sanity checks
    check_repository_compatibility

    # do it!
    local user_shell="sh -c"
    [ $(whoami) != $user ] && user_shell="sudo -E -H -u $user sh -c"

    local log_level=
    [ "x$CVMFS_LOG_LEVEL" != x ] && log_level="-l $CVMFS_LOG_LEVEL"
    local with_history=
    if $user_shell "cvmfs_swissknife peek -d .cvmfs_last_snapshot -r ${upstream}" | grep -q "available"; then
      with_history="-p"
    else
      echo "Initial snapshot"
    fi

    # put a magic file in the repository root to signal a snapshot in progress
    $user_shell "sh -c \"date > ${spool_dir}/tmp/snapshotting\""
    $user_shell "cvmfs_swissknife upload -r ${upstream} \
      -i ${spool_dir}/tmp/snapshotting \
      -o .cvmfs_is_snapshotting"

    # command to remove the magic file when finished (or aborted)
    delete_command="cvmfs_swissknife remove \
                      -r ${upstream} \
                      -o .cvmfs_is_snapshotting"

    # do the actual snapshot actions
    $user_shell "trap \"$delete_command\" HUP INT TERM QUIT && \
      cvmfs_swissknife pull -m $name \
        -u $stratum0 \
        -r ${upstream} \
        -x ${spool_dir}/tmp \
        -k $public_key \
        -n $num_workers \
        -t $timeout \
        -a $retries $with_history $log_level"
    $user_shell "sh -c \"date > ${spool_dir}/tmp/last_snapshot\""
    $user_shell "cvmfs_swissknife upload -r ${upstream} \
      -i ${spool_dir}/tmp/last_snapshot \
      -o .cvmfs_last_snapshot"

    # remove magic file after successful replication
    $user_shell "$delete_command"

  done

  return $retcode
}


################################################################################


migrate_2_1_6() {
  local name=$1

  # get repository information
  load_repo_config $name

  echo "Migrating repository '$name' from CernVM-FS $(mangle_version_string '2.1.6') to $(mangle_version_string '2.1.7')"

  echo "--> generating new upstream descriptor"
  # before 2.1.6 there were only local backends... no need to differentiate here
  local storage_path=$(echo $CVMFS_UPSTREAM_STORAGE | cut --delimiter=: --fields=2)
  local new_upstream="local,${storage_path}/data/txn,${storage_path}"

  echo "--> removing spooler pipes"
  local pipe_pathes="${CVMFS_SPOOL_DIR}/paths"
  local pipe_digests="${CVMFS_SPOOL_DIR}/digests"
  rm -f $pipe_pathes > /dev/null 2>&1 || echo "Warning: not able to delete $pipe_pathes"
  rm -f $pipe_digests > /dev/null 2>&1 || echo "Warning: not able to delete $pipe_digests"

  if is_stratum0 $name; then
    echo "--> create temp directory in upstream storage"
    local tmp_dir=${storage_path}/data/txn
    mkdir $tmp_dir > /dev/null 2>&1 || echo "Warning: not able to create $tmp_dir"
    chown -R $CVMFS_USER $tmp_dir > /dev/null 2>&1 || echo "Warning: not able to chown $tmp_dir to $CVMFS_USER"
    if has_selinux; then
      chcon -Rv --type=httpd_sys_content_t $tmp_dir > /dev/null 2>&1 || echo "Warning: not able to chcon $tmp_dir to httpd_sys_content_t"
    fi

    echo "--> updating server.conf"
    mv /etc/cvmfs/repositories.d/${name}/server.conf /etc/cvmfs/repositories.d/${name}/server.conf.old
    cat > /etc/cvmfs/repositories.d/${name}/server.conf << EOF
# created by cvmfs_server.
# migrated from version $(mangle_version_string "2.1.6").
CVMFS_CREATOR_VERSION=2.1.7
CVMFS_REPOSITORY_NAME=$CVMFS_REPOSITORY_NAME
CVMFS_REPOSITORY_TYPE=$CVMFS_REPOSITORY_TYPE
CVMFS_USER=$CVMFS_USER
CVMFS_UNION_DIR=$CVMFS_UNION_DIR
CVMFS_SPOOL_DIR=$CVMFS_SPOOL_DIR
CVMFS_STRATUM0=$CVMFS_STRATUM0
CVMFS_UPSTREAM_STORAGE=$new_upstream
CVMFS_USE_FILE_CHUNKING=$CVMFS_DEFAULT_USE_FILE_CHUNKING
CVMFS_MIN_CHUNK_SIZE=$CVMFS_DEFAULT_MIN_CHUNK_SIZE
CVMFS_AVG_CHUNK_SIZE=$CVMFS_DEFAULT_AVG_CHUNK_SIZE
CVMFS_MAX_CHUNK_SIZE=$CVMFS_DEFAULT_MAX_CHUNK_SIZE
EOF
  fi

  if is_stratum1 $name; then
    echo "--> updating server.conf"
    mv /etc/cvmfs/repositories.d/${name}/server.conf /etc/cvmfs/repositories.d/${name}/server.conf.old
    cat > /etc/cvmfs/repositories.d/${name}/server.conf << EOF
# Created by cvmfs_server.
# migrated from version $(mangle_version_string "2.1.6").
CVMFS_CREATOR_VERSION=2.1.7
CVMFS_REPOSITORY_NAME=$CVMFS_REPOSITORY_NAME
CVMFS_REPOSITORY_TYPE=$CVMFS_REPOSITORY_TYPE
CVMFS_USER=$CVMFS_USER
CVMFS_SPOOL_DIR=$CVMFS_SPOOL_DIR
CVMFS_STRATUM0=$CVMFS_STRATUM0
CVMFS_UPSTREAM_STORAGE=$new_upstream
EOF
  fi

  # reload repository information
  load_repo_config $name
}


migrate_2_1_7() {
  local name=$1
  local destination_version="2.1.15"

  # get repository information
  load_repo_config $name

  echo "Migrating repository '$name' from CernVM-FS $CVMFS_CREATOR_VERSION to $(mangle_version_string $destination_version)"

  if [ ! -f ${CVMFS_SPOOL_DIR}/client.local ]; then
    echo "--> creating client.local"
    sudo -H -u $CVMFS_USER sh -c "touch ${CVMFS_SPOOL_DIR}/client.local" || die "fail!"
  fi

  local server_conf="/etc/cvmfs/repositories.d/${name}/server.conf"
  if ! cat $server_conf | grep -q CVMFS_UNION_FS_TYPE; then
    echo "--> setting AUFS as used overlay file system"
    echo "CVMFS_UNION_FS_TYPE=aufs" >> $server_conf
  fi

  if ! grep client.local /etc/fstab | grep -q ${CVMFS_REPOSITORY_NAME}; then
    echo "--> adjusting /etc/fstab"
    sed -i -e "s|cvmfs2#${CVMFS_REPOSITORY_NAME} ${CVMFS_SPOOL_DIR}/rdonly fuse allow_other,config=/etc/cvmfs/repositories.d/${CVMFS_REPOSITORY_NAME}/client.conf,cvmfs_suid 0 0 # added by CernVM-FS for ${CVMFS_REPOSITORY_NAME}|cvmfs2#${CVMFS_REPOSITORY_NAME} ${CVMFS_SPOOL_DIR}/rdonly fuse allow_other,config=/etc/cvmfs/repositories.d/${CVMFS_REPOSITORY_NAME}/client.conf:${CVMFS_SPOOL_DIR}/client.local,cvmfs_suid 0 0 # added by CernVM-FS for ${CVMFS_REPOSITORY_NAME}|" /etc/fstab
    if ! grep client.local /etc/fstab | grep -q ${CVMFS_REPOSITORY_NAME}; then
      die "fail!"
    fi
  fi

  echo "--> analyzing file catalogs for additional statistics counters"
  local temp_dir="${CVMFS_SPOOL_DIR}/tmp"
  local new_manifest="${temp_dir}/new_manifest"

  cvmfs_swissknife migrate \
    -v "2.1.7" \
    -r ${CVMFS_STRATUM0} \
    -n $name \
    -u ${CVMFS_UPSTREAM_STORAGE} \
    -t $temp_dir \
    -o $new_manifest \
    -k /etc/cvmfs/keys/$name.pub \
    -z /etc/cvmfs/repositories.d/${name}/trusted_certs \
    -s || die "fail! (migrating catalogs)"
  chown ${CVMFS_USER} $new_manifest

  # sign new (migrated) repository revision
  echo -n "Signing newly imported Repository... "
  create_whitelist $name ${CVMFS_USER} ${CVMFS_UPSTREAM_STORAGE} $temp_dir > /dev/null
  sudo -H -u ${CVMFS_USER} sh -c "cvmfs_swissknife sign \
    -c /etc/cvmfs/keys/$name.crt \
    -k /etc/cvmfs/keys/$name.key \
    -n $name \
    -m $new_manifest \
    -t $temp_dir \
    -r ${CVMFS_UPSTREAM_STORAGE}" > /dev/null || die "fail! (cannot sign repo)"
  echo "done"

  echo "--> updating server.conf"
  sed -i -e "s/^CVMFS_CREATOR_VERSION=.*/CVMFS_CREATOR_VERSION=$destination_version/" /etc/cvmfs/repositories.d/$name/server.conf

  # reload (updated) repository information
  load_repo_config $name

  # update repository information
  echo "--> remounting (migrated) repository"
  local remote_hash
  remote_hash=$(cvmfs_swissknife info -r $CVMFS_STRATUM0 -c)

  cvmfs_suid_helper rw_umount $name     > /dev/null 2>&1 || die "fail! (unmounting /cvmfs/$name)"
  cvmfs_suid_helper rdonly_umount $name > /dev/null 2>&1 || die "fail! (unmounting ${CVMFS_SPOOL_DIR}/rdonly)"
  set_ro_root_hash $name $remote_hash
  cvmfs_suid_helper rdonly_mount $name  > /dev/null 2>&1 || die "fail! (mounting ${CVMFS_SPOOL_DIR}/$name)"
  cvmfs_suid_helper rw_mount $name      > /dev/null 2>&1 || die "fail! (mounting /cvmfs/$name)"
}


migrate() {
  local names
  local retcode=0

  # get repository names
  check_parameter_count_for_multiple_repositories $#
  names=$(get_or_guess_multiple_repository_names $@)
  check_multiple_repository_existence "$names"

  # sanity checks
  is_root || die "Only root can migrate repositories"

  for name in $names; do

    check_repository_existence $name || { echo "The repository $name does not exist"; retcode=1; continue; }

    # get repository information
    load_repo_config $name

    # more sanity checks
    check_repository_compatibility "nokill" && { echo "Repository '$name' is already up-to-date."; continue; }
    health_check $name

    # do the migrations...
    if [ $(repository_creator_version) = "2.1.6" ]; then
      migrate_2_1_6 $name
    fi

    if [ $(repository_creator_version) = "2.1.7" -o  \
         $(repository_creator_version) = "2.1.8" -o  \
         $(repository_creator_version) = "2.1.9" -o  \
         $(repository_creator_version) = "2.1.10" -o \
         $(repository_creator_version) = "2.1.11" -o \
         $(repository_creator_version) = "2.1.12" -o \
         $(repository_creator_version) = "2.1.13" -o \
         $(repository_creator_version) = "2.1.14" ];
    then
      migrate_2_1_7 $name
    fi

  done

  return $retcode
}


################################################################################


skeleton() {
  local skeleton_dir
  local skeleton_user

  # get optional parameters
  OPTIND=1
  while getopts "o:" option
  do
    case $option in
      o)
        skeleton_user=$OPTARG
        ;;
      ?)
        shift $(($OPTIND-2))
        usage "Command skeleton: Unrecognized option: $1"
      ;;
    esac
  done

  # get skeleton destination directory
  shift $(($OPTIND-1))

  # get skeleton destination directory
  if [ $# -eq 0 ]; then
    usage "Command skeleton: Please provide a skeleton destination directory"
  fi
  if [ $# -gt 1 ]; then
    usage "Command skeleton: Too many arguments"
  fi
  skeleton_dir=$1

  # ask for the skeleton dir owern
  if [ x$skeleton_user = "x" ]; then
    read -p "Owner of $skeleton_dir [$(whoami)]: " skeleton_user
    # default value
    [ x"$skeleton_user" = x ] && skeleton_user=$(whoami)
  fi

  # sanity checks
  check_user $skeleton_user || die "No user $skeleton_user"

  # do it!
  create_repository_skeleton $skeleton_dir $skeleton_user
}


################################################################################
#                                                                              #
#                                Entry Point                                   #
#                                                                              #
################################################################################

# check that there are no traces of CernVM-FS 2.0.x which might interfere
foreclose_legacy_cvmfs

# check if there is at least a selected sub-command
if [ $# -lt 1 ]; then
  usage
fi

# check if the given sub-command is known and, if so, call it
subcommand=$1
shift
if is_subcommand $subcommand; then
  # parse the command line arguments (keep quotation marks)
  args=""
  while [ $# -gt 0 ]; do
    if echo $1 | grep -q "\s"; then
      args="$args \"$1\""
    else
      args="$args $1"
    fi
    shift 1
  done

  # replace a dash (-) by an underscore (_) and call the requested sub-command
  eval "$(echo $subcommand | sed 's/-/_/g') $args"
else
  usage "Unrecognized command: $subcommand"
fi
