#!/bin/bash

#
# Copyright (c) 2009 Adrian Schroeter, SUSE Linux Products GmbH.
# Copyright (c) 2020 SUSE LLC
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# 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 (see the file COPYING); if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
#
################################################################


# defaults
protocol="http"
host=
port=
prefer_old=
enforceipv4='enable'
sslvalidation='enable'
args=()

use_manifest=0

while test $# -gt 0; do
  case $1 in
    *-host)
      host="$2"
      shift
    ;;
    *-port)
      port="$2"
      shift
    ;;
    *-protocol)
      protocol="$2"
      shift
    ;;
    *-path)
      path="${2#/}"
      shift
    ;;
    *-filename)
      filename="${2#/}"
      shift
    ;;
    *-outdir)
      outdir="$2"
      shift
    ;;
    *-url)
      url="$2"
      shift
    ;;
    *-prefer-old)
      prefer_old="$2"
      shift
    ;;
    *-enforceipv4)
      enforceipv4="$2"
      shift
    ;;
    *-sslvalidation)
      sslvalidation="$2"
      shift
    ;;
    *-download-manifest)
      download_manifest="${2##*/}"
      shift
      path=`pwd`
      manifest_file="$path/$download_manifest"
      args+=("-i" $manifest_file)
      use_manifest=1
    ;;
    *)
      echo "Unknown parameter $1." >&2
      exit 1
    ;;
  esac
  shift
done

if [ -z "$outdir" ]; then
  echo "ERROR: no output directory is given via --outdir parameter!" >&2
  exit 1
fi

if [ -z "$url" -a $use_manifest -lt 1 ]; then
  if [ -z "$host" -o -z "$path" ]; then
    echo "ERROR: need url or host, path " >&2
    exit 1
  fi

  url="$protocol://${host}${port:+:$port}/$path"
fi

if [ "$enforceipv4" = "enable" ]; then
  args+=("-4")
fi

if [ "$sslvalidation" = "disable" ]; then
  args+=("--no-check-certificate")
fi

if [ $use_manifest -lt 1 ]; then
  if [ -z "$filename" ]; then
    filename="${url##*/}"
  fi
  if [ -z "$filename" ]; then
    echo "ERROR: can't determine file name from $url" >&2
    exit 1
  fi
  args+=(-O "${filename##*/}")
fi

if [ "$prefer_old" = "enable" -a -e ".old/_service:download_url:$filename" ]; then
  ln ".old/_service:download_url:$filename" "$outdir/$filename"
  exit 0
fi

cd "$outdir"
if [ -n "$url" ];then
  args+=('--')
  args+=($url)
fi
set -- /usr/bin/wget "${args[@]}"
exec "$@"
