#!/bin/bash -efu

# This file is part of hsh-svace.
#
# Copyright (C) 2024  Egor Ignatov <egori@altlinux.org>
#
# hsh-svace is free software: you can redistribute it and/or modify it
# under the  terms of the GNU  General Public License as  published by
# the Free  Software Foundation, either  version 3 of the  License, or
# (at your option) any later version.
#
# hsh-svace 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 hsh-svace. If not, see <https://www.gnu.org/licenses/>.

show_help()
{
    cat <<EOF
Usage: $PROG [options] [<path-to-workdir>] <package>
  or:  $PROG [options] --workdir=DIR <package>

Options:
    --workdir=DIR              path to workdir to use (default ~/hasher);
    --outdir=DIR               directory for results (default .);
    --build-only               skip svace analysis, just build;
    --apt-config=FILE          path to custom apt.conf file;
    -r, --rebuild              use existing hasher;
    -v, --verbose              enable verbose output (default);
    -q, --quiet                try to be more quiet;
    -h, --help                 show this text and exit.

EOF
}

show_usage()
{
    [ -z "${1:-}" ] || echo "$1" >&2
    show_help >&2
    exit 1
}

PROG=hsh-svace
TEMP=$(getopt -n $PROG -o "r,h,v,q" -l "rebuild,build-only,apt-config:,workdir:,outdir:,help,verbose,quiet" -- "$@") \
    || show_usage
eval set -- "$TEMP"

rc=0
selfdir="$(dirname $(realpath $0))"
verbose=-v
quiet=
analyze=1
rebuild=
workdir_from_opt=
workdir=$HOME/hasher
outdir="$PWD"

while :; do
    case "$1" in
        --) shift; break
            ;;
        --workdir) shift; workdir="$1"
                   workdir_from_opt=1
                   ;;
        --outdir) shift; outdir="$1"
                  ;;
        -v|--verbose) verbose=-v
                      quiet=
                      ;;
        -q|--quiet) verbose=
                    quiet=-q
                    ;;
        -r|--rebuild) rebuild=1
                      ;;
        --build-only) analyze=
                      ;;
        --apt-config) shift; apt_config="$1"
                      ;;
        -h|--help)
            show_help
            exit 0
            ;;
        *) show_usage "Unrecognized option: $1"
           ;;
    esac
    shift
done

if [ -z "$workdir_from_opt" ]; then
    if [ -d "${1-}" ]; then
        # At least one argument.
        [ "$#" -ge 1 ] || show_usage 'Insufficient arguments.'
        workdir="$1"
        shift
    fi
fi

[ -d "$outdir" ] || show_usage 'Outdir does not exist or not a directory'
outdir="$(realpath $outdir)"

[ "$#" -ge 1 ] || show_usage 'Insufficient arguments.'
pkgtar="$1"

# init hasher
[ -n "${rebuild:-}" ] ||
    hsh $verbose \
        --initroot-only \
        --without-stuff \
        ${apt_config:+--apt-config "$apt_config"} \
        --workdir "$workdir"

install_deps_log="$(mktemp -t hsh-rebuild.log.XXXXXXXXXX)"
trap "rm -f $install_deps_log" EXIT

verbose_stderr=/dev/stderr
[ "${verbose:-}" = "-v" ] || verbose_stderr="/dev/null"

# install deps
hsh-rebuild -v \
            --install-only \
            --workdir "$workdir" \
            "$pkgtar" 2>&1 | \
    tee "$install_deps_log" 1>&2 >$verbose_stderr

# Hack to avoid recalculating mountpoints:
# Take mountpoints from hsh-rebuild log
# NOTE(egori): hsh-rebuild must be run in verbose mode
build_mountpoints="$(sed -n 's/hsh-rebuild: calculated mount points: //p' \
     $install_deps_log | tail -n1)"

# run build
hsh-run $verbose \
        --mountpoints="$build_mountpoints,/proc,/opt" \
        --execute="$selfdir/hsh-svace-build.sh" \
        "$workdir" -- $quiet

# run analyze
if [ -n "${analyze:-}" ]; then
    hsh-run $verbose --rooter --workdir "$workdir" -- sh -c 'mkdir -p /var/hasplm'
    share_network=1 hsh-run $verbose \
                    --mountpoints=/proc,/opt,/var/hasplm \
                    --execute="$selfdir/hsh-svace-analyze.sh" \
                    "$workdir" -- $quiet || \
        {
            rc="$?"
            echo "WARNING: 'svace analyze' failed!" >&2
            echo "Make sure that you have set up a hasher for analysis." >&2
            echo "The output archive contains only the results of 'svace build'" >&2
        }
fi

[ ! -f "$outdir/hsh-svace-results.tar" ] || \
    mv "$outdir/hsh-svace-results.tar" "$outdir/hsh-svace-results.tar.bak"

mv -f "$workdir/chroot/.out/hsh-svace-results.tar" \
   "$outdir/hsh-svace-results.tar"

exit "$rc"
