#!/usr/bin/sh

# Probe system for multilib information.
# Copyright (C) 2016 Red Hat, Inc.
# Written by Pavel Raiskup <praiskup@redhat.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

progname=$(basename "$0")
opt_verbose=:
opt_arch=$(uname -i)

multilib_arches="
    i386  x86_64
    ppc   ppc64
    s390  s390x
    sparc sparc64
"

verbose ()
{
    $opt_verbose && echo >&2 "INFO: $progname: $*"
}

die ()
{
    echo >&2 " # $*"
    print_help 1
}

error ()
{
    error_occurred=:
    echo >&2 " ! $*"
}

is_multilib ()
{
    _m_result=false
    for _m_arch in $multilib_arches
    do
        if test "$_m_arch" = "$1"; then
            _m_result=:
            break
        fi
    done
    $_m_result
}

fix_arch ()
{
    eval "_arch=\$$1"
    case $_arch in
        # See rhbz#1242873 for more info.
        ppc64p7)
            eval "$1=ppc64"
            ;;
    esac
}

error_occurred=false

# vi: ft=sh

opt_multilib_capable=false

print_help ()
{
    _h_exit=false
    test -n "$1" && _h_exit=:

    cat <<EOF
Usage: $progname [OPTIONS]

Probe system for interesting multilib information.

--multilib-capable   could package built on this box play some role on multilib
                capable system?  Prints 'true' or 'false'.
--arch          override arch detection (mostly for testing purposes)
EOF
    $_h_exit && exit "$1"
}

while test $# -gt 0
do
    _opt=$1 ; shift
    case $_opt in
        --arch)
            _raw_opt=$(echo "$_opt" | sed -e 's/^--//' -e 's/-/_/g')
            eval "opt_$_raw_opt=\$1"
            shift || die "$_opt requires argument"
            ;;
        --multilib-capable)
            _raw_opt=$(echo "$_opt" | sed -e 's/^--//' -e 's/-/_/g')
            eval "opt_$_raw_opt=:"
            ;;
        --help)
            print_help 0
            ;;
        *)
            error "unexpected '$_opt' program argument"
            ;;
    esac
done
$error_occurred && print_help 1
fix_arch opt_arch

$opt_multilib_capable && {
    if is_multilib "$opt_arch"; then
        echo true
    else
        echo false
    fi
    exit 0
}

print_help 1
