#!/bin/bash
# $Id$
# Written by slakmagik <slakmagik@gmail.com>
# Released under the WTFPL

script=${0##*/}

# USER-MODIFIABLE VARIABLES
# this needs to be where the checked out svn directory is.
repo="/tmp/sbopkg-read-only"
remote_repo="https://github.com/sbopkg/sbopkg.git"
export OUTPUT="${OUTPUT:-/tmp}"

usage() {
cat << EOF
$script: sbopkg subversion package maker usage: $script [-b] | [-i] | [-s]

-b build a package from local subversion repository
-i install the package
-s syncs the local repo to the remote one

No arguments is equivalent to -bis: $script checks out the latest revision to
the subversion repository and builds and installs a package from it.
EOF
exit
}

printe() {
    printf "$script: $@" | tr -s ' ' | fmt -sw78 >&2
    exit 1
}

if (( $# == 0 )); then
    build="yes"
    inst="yes"
    sync="yes"
else
    build="no"
    inst="no"
    sync="no"
fi

while getopts :bis opt; do
    case $opt in
        b) build="yes" ;;
        i) inst="yes" ;;
        s) sync="yes" ;;
        *) usage ;;
    esac
done

# Make sure we are root.
if (( $(id -u) != 0 )); then
    printe "$script must be run by the root user."
fi

if [[ $sync == yes ]]; then
    if [[ -w $repo ]] || [[ ! -e $repo && -w ${repo%/*} ]]; then
        git checkout $remote_repo $repo || printe "checkout failed"
    else
        printe "$repo is not writable.\nChange your privileges or the \
            value of the \"repo\" variable.\n"
    fi
fi

# this allows for a version mismatch if someone builds a package, doesn't
# install it, then syncs their repo to a newer version, then does install the
# old package. But, as the doctor said to the guy who complained that it hurt
# when he did that, don't DO that.
if [[ $build == yes || $inst == yes ]]; then
    git_script="$repo/src/usr/sbin/sbopkg"
    if [ -r $git_script ]; then
        export VERSION=git$(gitversion $repo)
    else
        printe "unable to find $git_script.\nPlease check your repository."
    fi

    if [[ $OUTPUT =~ "$repo/(sbopkg-$VERSION|root-tools)" ]]; then
        printe "the OUTPUT variable is set to a path that will be \
            removed.\nPlease alter the value of the variable.\n"
    fi

    output_pkg=$OUTPUT/sbopkg-$VERSION-noarch-1_cng.tgz
    if [[ $build == yes ]]; then
        cd $repo
        if [ -d sbopkg-$VERSION ] || [ -d root-tools ]; then
            printe "director(y|ies) exist(s)"
        fi
        cp -r src sbopkg-$VERSION
        cp -r tools root-tools
        tar --exclude='*.svn*' --exclude='*.rej' \
            --exclude='*~' --exclude='tags' \
            -czvf $repo/root-tools/sbopkg-$VERSION.tar.gz sbopkg-$VERSION
        cd $repo/root-tools
        sh sbopkg.SlackBuild
        cd $repo
        rm -rf root-tools
        rm -rf sbopkg-$VERSION
    fi
    if [[ $inst == yes ]]; then
        if [ -r $output_pkg ]; then
            upgradepkg --install-new --reinstall $output_pkg
        else
            printe "$output_pkg not found."
        fi
    fi
fi
