#!/bin/bash

set -e

BASE_URL=https://repo.openbytes.ie/patchman/debian/pool/main/p/patchman/

## # ### # ### # ### # ### # ### # ### # ### # ### # ### # #

exit_with_error () {
    echo "error: $1"
    exit 1
}

progress () {
    if [ "$VERBOSE" == "1" ]; then
	echo "progress: $1"
    fi
}

download_deb_file () {
    local base_filename
    local filename
    base_filename=$1
    filename="${base_filename}_${VERSION}-1_all.deb"

    progress "downloading $filename to ${TMPDIR}/${filename}"
    wget "${BASE_URL}${filename}" -O "${TMPDIR}/${filename}"
    progress "finished downloading $filename"
}

upload_deb_file () {
    local base_filename
    local filename

    base_filename=$1
    filename="${base_filename}_${VERSION}-1_all.deb"

    progress "about to upload $filename"

    GNUPGHOME=/srv/repos/stanford/keyring reprepro -b /srv/repos/stanford includedeb sid "${TMPDIR}/${filename}"
    GNUPGHOME=/srv/repos/stanford/keyring reprepro -b /srv/repos/stanford copy bullseye sid "$base_filename"
    GNUPGHOME=/srv/repos/stanford/keyring reprepro -b /srv/repos/stanford copy stable sid "$base_filename"
}

## # ### # ### # ### # ### # ### # ### # ### # ### # ### # #


# Initialize our own variables:
VERBOSE=0

PARAMS=""

# The following option parsing code taken from:
# https://medium.com/@Drew_Stokes/bash-argument-parsing-54f3b81a6a8f
while (( "$#" )); do
    case "$1" in
	-v|--verbose)
	    VERBOSE=1
	    shift
	    ;;
	-*) # unsupported flags
	    echo "Error: Unsupported flag $1" >&2
	    exit 1
	    ;;
	*) # preserve positional arguments
	    PARAMS="$PARAMS $1"
	    shift
	    ;;
    esac
done

# Grab positional arguments
eval set -- "$PARAMS"

VERSION=$1

## # ### # ### # ### # ### # ### # ### # ### # ### # ### # #

if [ -z "$VERSION" ]; then
    exit_with_error "missing required version argument"
fi

progress "version is $VERSION"

# Make a temporary directory
TMPDIR=$(mktemp -d)
progress "temp directory is '$TMPDIR'"

# Download the DEB files
download_deb_file "python3-patchman"
download_deb_file "patchman-client"

# Upload to the repo
upload_deb_file "python3-patchman"
upload_deb_file "patchman-client"

progress "cleaning up $TMPDIR"
rm -rf "$TMPDIR"

exit 0

DOCS=<<_END_OF_DOCS_

=head1 NAME

upload-patchman - Upload new patchman client packages to stanford repo

=head1 SYNOPSIS

B<upload-patchman> VERSION

=head1 DESCRIPTION

Download patchman client packages from source repo and upload to stanford
Debian repo. You MUST include the version number as the first argument.
Example:

    upload-patchman 1.2.32

=head1 AUTHOR

Adam H. Lewenberg <adamhl@stanford.edu>

=cut

_END_OF_DOCS_
