#!/bin/sh
BASENAME="$(basename $0)"

version="Roxygen 0.1"

usage="Usage: R CMD roxygen [OPTIONS] SOURCE [TARGET]

Uses roxygenize() to process package in SOURCE, optionally placing
processed files in TARGET.

With -d (Destructive), roxygen operates in place; otherwise, TARGET
defaults to \`SOURCE.roxygen'.

With -u (Unlink), roxygen deletes TARGET before processing files.

WARNING: Be careful using -u (Unlink) when SOURCE and TARGET are
the same or with -d (Destructive).

Options:
  -d  (Destructive) operate in place on SOURCE
  -u       (Unlink) clean TARGET first
  -s  (Rd2) enable parsing of S4 tags

  -h         (Help) print short help message and exit
  -v      (Version) print roxygen version info and exit

Report bugs to <roxygen-devel@lists.r-forge.r-project.org>."

while getopts dushv OPT; do
    case $OPT in
        d|+d)
            destructive="TRUE"
            ;;
        u|+u)
            unlink="TRUE"
            ;;
        s|+s)
            rd2="TRUE"
            ;;
        h|+h)
            echo "${usage}"
            exit 0
            ;;
        v|+v)
            echo ${version}
            exit 0
            ;;
        *)
            echo "${usage}"
            exit 2
    esac
done
shift `expr $OPTIND - 1`
OPTIND=1

if [ ${#} -eq 0 ]; then
    echo "${usage}" >&2
    exit 1
fi

warning () {
    echo ${BASENAME}: "WARNING!" ${1} >&2
}

source="${1}"

if test ${#} -eq 1
then target="NULL"
else
    if test "${destructive}" = "TRUE"
    then warning "Both -d (Destructive) and TARGET specified; using TARGET."
        destructive="FALSE"
    fi
    target="${2}"
fi

if test "${destructive}" = "TRUE"
then
    if test "${unlink}" = "TRUE"
    then warning "Specified -d (Destructive) and -u (Unlink); unsetting -u."
        unlink="FALSE"
    fi
    target="${source}"
fi

if test "${source}" -ef "${target}" -o "${destructive}" = "TRUE"
then
    if test "${unlink}" = "TRUE"
    then warning "SOURCE and TARGET are identical; unsetting -u (Unlink)."
        unlink="FALSE"
    fi
    copy="FALSE"
fi

source="'${source}'"
if test "${target}" != "NULL"
then target="'${target}'"
fi

: ${unlink:="FALSE"}
: ${copy:="TRUE"}
: ${rd2:="FALSE"}

debug () {
    echo source: "${source}"\; target: "${target}"\; copy: "${copy}"\; unlink: "${unlink}"\; rd2: "${rd2}"
}


R_EXE="${R_HOME}/bin/R"
echo "library(roxygen)
      roxygenize(package.dir=${source},
                 roxygen.dir=${target},
                 copy.package=${copy},
                 unlink.target=${unlink},
                 use.Rd2=${rd2})" | \
    "${R_EXE}" --no-restore --slave
