#!/bin/bash

version=0.11
program=${0##*/}
progdir=${0%/*}
if [ "$progdir" = "$program" ]; then progdir="."; fi
if [ "$progdir" = "." ]; then progdir="$PWD"; fi
parent=$(dirname "$progdir")
if [ "$parent" = "." ]; then parent="$PWD"; fi
if [[ $(uname) =~ CYGWIN.* ]]; then parent=$(echo "$parent" | sed -e 's/^\/cygdrive\/\(.\)/\1:/'); fi


function usage() {
    cat <<EOF
NAME
	$program - Make a tarball of the MySQL database files and upload it

SYNOPSIS
	$program [OPTIONS]

DESCRIPTION
	This script creates a compressed tarball from the MySQL database files
	on disk, and uploads it to the ietf datatracker developer area on
	www.ietf.org.

	It is intended to be used with the docker datatracker environment, after
	you have set up the database with docker/setupdb, started the docker
	image with docker/run, and updated the database with docker/updatedb.

	To use it, exit from the docker container, to make sure that mysqldb
	isn't running and all the files consistent and available for copy.  Then
	run docker/$program outside the docker container.  You need to have ssh
	access to www.ietf.org in order for the scp command to succeed.

OPTIONS
EOF
    grep -E '^\s+-[a-zA-Z])' "$0" | sed -E -e 's/\)[^#]+#/ /'
    cat <<EOF

AUTHOR
	Written by:
		Henrik Levkowetz, <henrik@levkowetz.com>
		Lars Eggert, <lars@eggert.org>

COPYRIGHT
	Copyright (c) 2016 IETF Trust and the persons identified as authors of
	the code. All rights reserved. Redistribution and use in source and
	binary forms, with or without modification, is permitted pursuant to,
	and subject to the license terms contained in, the Revised BSD
	License set forth in Section 4.c of the IETF Trust’s Legal Provisions
	Relating to IETF Documents(https://trustee.ietf.org/license-info).

EOF
}


function die() {
    echo -e "\n$program: error: $*" >&2
    exit 1
}


function version() {
	echo -e "$program $version"
}


trap 'echo "$program($LINENO): Command failed with error code $? ([$$] $0 $*)"; exit 1' ERR

# Option parsing
shortopts=hV
args=$(getopt -o$shortopts $*)
if [ $? != 0 ] ; then die "Terminating..." >&2 ; exit 1 ; fi
set -- $args

while true ; do
    case "$1" in
    	-h)    usage; exit;;		# Show this help, then exit
    	-V)    version; exit;;		# Show program version, then exit
    	--)    shift; break;;
    	*) die "Internal error, inconsistent option specification: '$1'";;
    esac
    shift
done

# The program itself
if [ -e "/.dockerenv" -o -n "$(grep -s '/docker/' /proc/self/cgroup)" ]; then
   die "It looks as if you're running inside docker -- please quit docker first."
fi

workdir=$(realpath $progdir/../data/mysql/..)
echo "Working directory: $workdir"
cd $workdir
echo "Building tarfile ..."
tar cjf ietf_utf8.bin.tar.bz2 mysql
echo "Copying tarfile to ietfa.amsl.com ..."
scp ietf_utf8.bin.tar.bz2 ietfa.amsl.com:/a/www/www6s/lib/dt/sprint/