#!/bin/bash # $HeadURL$ $LastChangedRevision$ set -e PROGNAME=$(basename $0) # Load support functions . $(pcms-config PCMS_SHARE_PREFIX)/scripts/support.sh main() { # Defaults for options VERBOSELEVEL=2 # Process options while [ $# -ge 1 ]; do case $1 in -d) VERBOSELEVEL=$2; shift ;; --debug=*) VERBOSELEVEL=${1#*=} ;; -v|--verbose) VERBOSELEVEL=3 ;; --) shift; break ;; -*) error "main: $1: bad option" ;; *) break ;; esac shift done # Process arguments [ $# = 1 ] || usage eval set -- $(encode --decode "$1") [ $# -eq 3 ] || usage SYMLINK="$1" TARGET="$2" MKDIR_FLAG="$3" debug 10 "main: SYMLINK=$SYMLINK, TARGET=$TARGET, MKDIR_FLAG=$MKDIR_FLAG" # Sanity checks and derivations [[ $MKDIR_FLAG =~ ^(true|false)$ ]] || error "$MKDIR_FLAG: invalid value for MKDIR_FLAG" [[ $SYMLINK =~ ^/ ]] || error "$SYMLINK: not absolute" ! [[ $TARGET =~ ^/ ]] || error "$SYMLINK: not relative" # Symlink if [ ! -h $SYMLINK -a ! -e $SYMLINK ]; then ln -s $TARGET $SYMLINK elif { [ ! -h $SYMLINK -a -e $SYMLINK ]; }; then error "$SYMLINK: exists but is not a symlink (hint: fix this manually)" elif { [ -h $SYMLINK ] && [ $(readlink $SYMLINK) != $TARGET ]; }; then warning "$SYMLINK: exists and is a symlink but points to $(readlink $SYMLINK) instead of $TARGET; removing ..." rm -f $SYMLINK ln -s $TARGET $SYMLINK fi # Mkdir if $MKDIR_FLAG; then ABSOLUTE_TARGET=$(realpath -m $SYMLINK) if [ ! -h $ABSOLUTE_TARGET -a ! -e $ABSOLUTE_TARGET ]; then mkdir -p $ABSOLUTE_TARGET elif [ -h $ABSOLUTE_TARGET -o \( -e $ABSOLUTE_TARGET -a ! -d $ABSOLUTE_TARGET \) ]; then error "$ABSOLUTE_TARGET: exists but is not a directory (hint: fix this manually)" fi else # It'd be nice to do this "if link's targer doesn't exist then error" test before we even create the # symlink, but $ABSOLUTE_TARGET depends on the realpath command and I suspect that that won't work # in the above call unless $SYMLINK actually exists. But perhaps it would e..g: # # lagane# realpath /etc/a # where /etc/a does not exist! # /etc/a # lagane# # # Nonetheless, for the time being, we do it this way: undo the just created symlink # and return an error. if [ ! -e $ABSOLUTE_TARGET ]; then rm -f $SYMLINK error "$ABSOLUTE_TARGET: does not exist and you didn't request me to create it (as a directory); symlink has been removed" fi fi } usage() { echo "Usage: $PROGNAME @@" >&2; exit 1; } main "$@"