#!/bin/bash
#set -x
# Copyright 2015 Red Hat, Inc.
#
# 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 upload files to a Artifact container for deployment via
# TripleO Heat Templates.
#
set -eu
set -o pipefail
SCRIPT_NAME=$(basename $0)
SCRIPT_HOME=$(cd $(dirname $0); pwd)

function show_options {
    echo "Usage: $SCRIPT_NAME"
    echo
    echo "Options:"
    echo "    -h, --help                  -- print this help."
    echo "    -f <file>                   -- File(s) to upload."
    echo "    -c <container>              -- Artifact container to use."
    echo "      Default: overcloud-artifacts"
    echo "    --environment <env>         -- Generate this heat <env>"
    echo "      Default: $HOME/.tripleo/environments/deployment-artifacts.yaml"
    echo "    --seconds <seconds>         -- Number of seconds for temp URLs."
    echo "      Default: 31536000 (one year)"
    echo
    echo "Upload a set of files to Artifact and generate a Heat environment"
    echo "file containing the required DeployArtifactURLs parameter(s) "
    echo "so that it is used with TripleO Heat Templates."
    echo
    exit $1
}

function check_file {
    local FILE=$1
    supported_files=(" RPM " "gzip compressed data")
    array_length=${#supported_files[@]}

    local test_type=`file $FILE`

    local i=0
    local matched=0

    while [ $i -ne $array_length -a $matched -eq 0 ]; do
        if [[ "$test_type" =~ ${supported_files[$i]} ]]; then
            matched=1
        fi
        i=$((i+1))
    done

    if [ $matched -eq 0 ]; then
        echo "Not a supported file type: $FILE"
        exit 1
    fi

}


TEMP=`getopt -o he:f:c:s: -l help,environment:,file:,container:,seconds: -n $SCRIPT_NAME -- "$@"`
if [ $? != 0 ]; then
    echo "Terminating..." >&2
    exit 1
fi

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

ENVIRONMENT_FILE="$HOME/.tripleo/environments/deployment-artifacts.yaml"
FILES=
CONTAINER_NAME=overcloud-artifacts
SECONDS=31536000
BINDPORT="${BINDPORT:-8080}"
BINDADDRESS=$(ip addr show dev br-ctlplane | awk -F'\\s|/' '/inet\s/ {print $6}' | head -n 1)

while true ; do
    case "$1" in
        -h|--help) show_options 0 >&2;;
        -e|--environment) ENVIRONMENT_FILE=$2 ; shift 2;;
        -f|--file) FILES+=" $2" ; shift 2;;
        -c|--container) CONTAINER_NAME=$2 ; shift 2;;
        -s|--seconds) SECONDS=$2 ; shift 2;;
        --) shift ; break;;
        *) echo "Error: unsupported option $1." ; exit 1;;
    esac
done

if [ -z "${FILES:-}" ]; then
    echo "Error: No files were specified."
    exit 1
fi

if [ -z "${CONTAINER_NAME:-}" ]; then
    echo "Error: No Artifact --container was specified."
    exit 1
fi

# Create artifact archive
sudo mkdir -p "/var/lib/tripleo/artifacts/${CONTAINER_NAME}"

for FILE in ${FILES[@]}; do
    check_file "$FILE"
    sudo mv -v "$FILE" "/var/lib/tripleo/artifacts/${CONTAINER_NAME}/"
done

if [ -n "${ENVIRONMENT_FILE:-}" ]; then
    echo "Creating heat environment file: ${ENVIRONMENT_FILE}"
    mkdir -p $(dirname "${ENVIRONMENT_FILE}")
    /bin/python3 <<EOC
import os
import yaml
key = 'DeployArtifactFILEs'
urls = [
    "/var/lib/tripleo/artifacts/${CONTAINER_NAME}/{}".format(i)
    for i in files
]
content = {'parameter_defaults': {key: []}}
content['parameter_defaults'][key].extend(urls)
with open("${ENVIRONMENT_FILE}", 'w') as f:
    yaml.dump(content, f, default_flow_style=False)
EOC
fi
