#!/bin/bash
# Copyright 2014 Hewlett-Packard Development Company, L.P.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

# Script to setup pip manifest file location environment variables from a
# given directory tree

set -eu
set -o pipefail
SCRIPT_NAME=$(basename $0)
SCRIPT_HOME=$(cd $(dirname $0); pwd)

function show_options {
    echo
    echo "Usage: $SCRIPT_NAME file|directory ..[file|directory]"
    echo
    echo "    This script takes a list of manifest files and or directory"
    echo "    trees and sets the matching DIB_PIP_MANIFEST_<name> environment"
    echo "    variable to the full path of any matching manifest"
    echo "    dib-pip-manifest* files found"
    echo
    echo "    To source the export commands produced by running this script"
    echo "    and set the variables for the current shell,"
    echo "    you can run the script as follows:"
    echo
    echo "        source <( $SCRIPT_NAME /path/to/pip-manifests )"
    echo
    echo "Options:"
    echo "    -h, --help                     -- print this help."
    echo
    echo "Echo the appropriate environment variables to use a pip manifest"
    echo "for input into image building with the pip-manifest element."
    echo
    echo "e.g. $SCRIPT_NAME ~/myTripleo/seed-manifests"
    echo
    exit $1
}

TEMP=`getopt -o h -l help -n $SCRIPT_NAME -- "$@"`
if [ $? != 0 ]; then
    echo "Terminating..." >&2;
    exit 1;
fi

# Note the quotes around `$TEMP': they are essential!
eval set -- "$TEMP"

while true ; do
    case "$1" in
        -h|--help) show_options 0 >&2;;
        --) shift ; break ;;
        *) echo "Error: unsupported option $1." ; exit 1 ;;
    esac
done

if (( $# <= 0 )); then
    echo "One or more pip manifest directory or file name required" >&2;
    show_options 1 >&2
fi

for target in $*; do
    for ent in $(find ${target} -type f -name dib-pip-manifest\* ); do
        echo DIB_PIP_MANIFEST_${ent##*dib-pip-manifest-}=${ent};
    done
done 2>/dev/null | sort -t = -k1 -u



