#! /bin/sh
#
#

PREFIX="/sw"
USER="sw"
GROUP="sw"

TMPDIR="/var/tmp/openpkg-now"

SERVER="ftp.openpkg.org"

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

if [ ".$UID" = "." ]; then
    echo "Please run this script as root user" 1>&2 
    exit 1
fi

echo "Preparing environment"
export TMPDIR

umask 002

case "`uname -s`" in
    Linux)
        PATH="/usr/bin:/usr/sbin:/bin:/sbin"
        OS="linux"
        export PATH OS
        ;;
    SunOS)
        PATH="/usr/bin:/usr/sbin:/usr/ccs/bin:/sbin"
        OS="solaris"
        export PATH OS
        ;;
    *)
        ;;
esac

if [ -e "$TMPDIR" ]; then
    rm -rf $TMPDIR 2> /dev/null || true
fi
mkdir -p $TMPDIR/log
cd $TMPDIR

echo "Fetching OpenPKG bootstrap package"
ftp -n -i $SERVER << EOF
user ftp seeyou@openpkg.org
bin
cd current/SRC/
mget openpkg-*.src.sh
bye
EOF

echo "Building OpenPKG bootstrap package"
sh ./openpkg-*src.sh \
    --prefix="$PREFIX" \
    --user="$USER" \
    --group="$GROUP" > $TMPDIR/log/openpkg.log 2>&1

echo "Installing OpenPKG bootstrap package"
sh ./openpkg-*$OS*.sh >> $TMPDIR/log/openpkg.log 2>&1

PKGS="make gcc zlib gzip sed gawk bison flex bzip2 tar libiconv pcre grep \
    bash fileutils findutils shellutils textutils file ntp perl whois \
    openssl openssh db bind8 rsync"

for p in $PKGS; do
    echo "Fetching OpenPKG $p package"
    case $p in
        *)
            su - $USER -c "$PREFIX/bin/rpm -U \
                ftp://$SERVER/current/SRC/$p-[0-9]*.src.rpm" \
                > $TMPDIR/log/$p.log 2>&1
            ;;
    esac

    echo "Building OpenPKG $p package"
    case $p in
        *)
            su - $USER -c "$PREFIX/bin/rpm -bb \
                $PREFIX/RPM/SRC/$p/$p.spec" \
                >> $TMPDIR/log/$p.log 2>&1
            ;;
    esac

    echo "Installing OpenPKG $p package"
    case $p in
        *)
            $PREFIX/bin/rpm -U $PREFIX/RPM/PKG/$p-[0-9]*.rpm \
            >> $TMPDIR/log/$p.log 2>&1
            ;;
    esac

    echo "Configuring OpenPKG $p package"
    case $p in
        ntp)
            { egrep -v "^server" $PREFIX/etc/ntp/ntp.conf ; \
              echo "server ntp1.de.cw.net" ; \
              echo "server ntp2.de.cw.net" ; \
            } > $TMPDIR/ntp.conf
            mv $TMPDIR/ntp.conf $PREFIX/etc/ntp/ntp.conf
            chown $USER:$GROUP $PREFIX/etc/ntp/ntp.conf
            chmod 644 $PREFIX/etc/ntp/ntp.conf
            echo "ntp_daemon=\"no\"" >> $PREFIX/etc/rc.conf
            ( cd /
              $PREFIX/etc/rc.d/rc.ntp start
            )
            ;;
        findutils)
            ( cd /
              $PREFIX/etc/rc.d/rc.findutils daily
            )
            ;;
        bind)
            echo "bind_enable=\"no\"" >> $PREFIX/etc/rc.conf
            ;;
        rsync)
            echo "rsync_enable=\"no\"" >> $PREFIX/etc/rc.conf
            ;;
        *)
            ;;
    esac
done

