#!/bin/sh
#
# Script to setup the environment for openvpn-build/generic and openvpn-build/windows-nsis 

BUILD_DEPS="mingw-w64 man2html dos2unix nsis unzip wget curl autoconf"
OSSLSIGNCODE_DEPS="libssl-dev libcurl4-openssl-dev build-essential"
OSSLSIGNCODE_URL="http://sourceforge.net/projects/osslsigncode/files/latest/download"
OSSLSIGNCODE_PACKAGE="osslsigncode-latest.tar.gz"
OPENVPN_BUILD_URL="https://github.com/OpenVPN/openvpn-build.git"
PATCHED_DEBS_BASEURL="http://build.openvpn.net/downloads/packaging"
PATCHED_DEBS_PRECISE="mingw-w64-dev_2.0.1-101_all.deb mingw-w64-tools_2.0.1-101_amd64.deb mingw-w64_2.0.1-101_all.deb nsis-common_2.46-101_all.deb nsis-doc_2.46-101_all.deb nsis-pluginapi_2.46-101_all.deb nsis_2.46-101_amd64.deb"
PATCHED_DEBS_QUANTAL="mingw-w64-dev_2.0.3-101_all.deb mingw-w64-tools_2.0.3-101_amd64.deb mingw-w64_2.0.3-101_all.deb mingw-w64-i686-dev_2.0.3-101_all.deb mingw-w64-x86-64-dev_2.0.3-101_all.deb nsis-common_2.46-101_all.deb nsis-doc_2.46-101_all.deb nsis-pluginapi_2.46-101_all.deb nsis_2.46-101_amd64.deb"

check_if_root() {
    if ! [ `whoami` = "root" ]; then
            echo "ERROR: you must run this script as root!"
            exit 1
    fi
}

usage() {

    echo "Usage: setup-generic-buildsystem.sh <oscodename>"
    echo
    echo "Parameter <oscodename> is:"
    echo
    echo "    trusty  (Ubuntu 14.04)"
    echo "    precise (Ubuntu 12.04)"
    echo "    quantal (Ubuntu 12.10)"
    echo
    echo "Example:"
    echo
    echo "   setup-generic-buildsystem.sh trusty"
    echo
    exit 1
}

install_prequisites() {
    #apt-get update
    apt-get -y install $BUILD_DEPS $GIT_PKG $GNUEABI_PKG
}

install_osslsigncode() {
    apt-get -y install $OSSLSIGNCODE_DEPS
    curl -L $OSSLSIGNCODE_URL > $OSSLSIGNCODE_PACKAGE
    tar -zxf $OSSLSIGNCODE_PACKAGE
    cd osslsigncode-*
    ./configure
    make
    make install
    cd ..
}

install_patched_debs() {

    for DEB in $PATCHED_DEBS; do
        if ! [ -r $DEB ]; then
            curl -O $PATCHED_DEBS_BASEURL/$DEB
        fi
    done
    dpkg -i $PATCHED_DEBS
}

clone_openvpn_build() {
    if ! [ -d "openvpn-build" ]; then
        git clone $OPENVPN_BUILD_URL
    fi
}

OSCODENAME=$1

if [ "$OSCODENAME" = "trusty" ]; then
    PATCHED_DEBS=""
    GIT_PKG="git"
    GNUEABI_PKG="gcc-4.7-arm-linux-gnueabi"
elif [ "$OSCODENAME" = "precise" ]; then
    PATCHED_DEBS=$PATCHED_DEBS_PRECISE
    GIT_PKG="git-core"
    GNUEABI_PKG="gcc-4.6-arm-linux-gnueabi"
elif [ "$OSCODENAME" = "quantal" ]; then
    PATCHED_DEBS=$PATCHED_DEBS_QUANTAL
    GIT_PKG="git-core"
    GNUEABI_PKG="gcc-4.6-arm-linux-gnueabi"
else
    echo "ERROR: unknown oscodename"
    echo
    usage
fi

check_if_root
install_prequisites
install_osslsigncode

if ! [ "$PATCHED_DEBS" = "" ]; then
    install_patched_debs
fi

clone_openvpn_build
