#!/bin/bash

#
# Copyright (c) 2023 SUSE
# Written by Olaf Kirch
#
# 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
#
################################################################

function assert_boolean {

  case "$2" in
  true|false)
    return 0;;
  *)
    echo "Option $1 takes 'true' or 'false', nothing else" >&2
    exit 1;;
  esac
}

function generate_obsinfo {

  file="$1"

  version=$(jq '.Labels["org.opencontainers.image.version"]' < $file|tr -d '"')
  mtime=$(jq '.Labels["org.opencontainers.image.created"]' < $file|tr -d '"')
  reference=$(jq '.Labels["org.opensuse.reference"]' < $file|tr -d '"')

  unversioned="${reference/:*}"
  name="${unversioned##*/}"
  # Split the version string into version and release
  release="${version##*-}"
  version="${version/-*}"

  echo "name: $name"
  echo "version: $version"
  echo "release: $release"
  echo "mtime: $mtime"
}

# defaults
protocol=docker
registry=registry.opensuse.org
name=
download_image=false
tlsverify=true

while test $# -gt 0; do
  case $1 in
    *-protocol)
      protocol="$2"
      shift
    ;;
    *-registry)
      registry="$2"
      shift
    ;;
    *-name)
      name="$2"
      shift
    ;;
    *-download-image)
      assert_boolean "$@"
      download_image="$2"
      shift
    ;;
    *-tlsverify)
      assert_boolean "$@"
      tlsverify="$2"
      shift
    ;;
    *-outdir)
      outdir="$2"
      shift
    ;;
    *)
      echo "Unknown parameter $1." >&2
      exit 1
    ;;
  esac
  shift
done

if [ -z "$outdir" ]; then
  echo "ERROR: You need to specify an output directory using the --outdir option!" >&2
  exit 1
fi

if [ -z "$name" ]; then
  echo "ERROR: You need to specify an image name using the --name option!" >&2
  exit 1
fi

remotespec="$protocol://$registry/$name"
localspec=$(echo "$name" | tr / -)

skopeo inspect --tls-verify=$tlsverify "$remotespec" >"$outdir/$localspec.json" || exit 1

generate_obsinfo "$outdir/$localspec.json" >"$outdir/$localspec.obsinfo"

if $download_image; then
  rm -f "$localspec.tar"
  skopeo copy --src-tls-verify=$tlsverify "$remotespec" "docker-archive:$localspec.tar" || exit 1
fi

exit 0
