#!/bin/sh

# ebs (ebs build system): build xpt packages from ebs.formula

set -eu

umask 022
TZ=UTC
LC_ALL=C
export TZ LC_ALL

if command -v fakeroot >/dev/null 2>&1; then
    FAKEROOT="fakeroot"
else
    FAKEROOT=
fi

command -v bsdtar >/dev/null 2>&1 || {
    echo "! bsdtar not found" >&2
    exit 1
}

command -v zstd >/dev/null 2>&1 || {
    echo "! zstd not found" >&2
    exit 1
}

download() {
    if command -v rswc >/dev/null 2>&1; then
        rswc -T 60 -o "$2" "$1" || {
            echo "! rswc failed" >&2
            return 1
        }
    elif command -v curl >/dev/null 2>&1; then
        curl -fsSL -o "$2" "$1" --progress-bar || {
            echo "! curl failed" >&2
            return 1
        }
    elif command -v wget >/dev/null 2>&1; then
        wget -qO "$2" "$1" || {
            echo "! wget failed" >&2
            return 1
        }
    else
        echo "! no URL transfer program found (tried rswc, curl, wget)" >&2
        return 1
    fi
}

if [ "${1:-}" = "" ]; then
    echo "usage: ebs <command> [arguments]"
    exit 1
fi

print_ebs_help() {
    printf "%s\n" 'the ebs build system'
    printf "%s\n\n" 'usage: ebs <command> [arguments]'
    printf "%s\n\n" 'build .xpt packages from ebs formulae'
    printf "%s\n" 'commands:'
    printf " %-10s %s\n" 'build' 'build from an ebs formula'
    printf " %-10s %s\n" 'help' 'show this message'
    printf "\n%s\n" 'view ebs(1) for more information on the available commands,'
    printf "%s\n" 'and ebs(5) for more information on the formula format.'
}

createTreefile() {
    if [ ! -d "$1" ]; then
        echo "directory $1 does not exist" >&2
        return 1
    fi

    dir="$1"
    tmpd=""

    rm -f "$dir/xpt.tree"
    if [ -f "$dir/xpt.manifest" ]; then
        tmpd=$(mktemp)
        mv "$dir/xpt.manifest" "$tmpd"
    fi
    tree=$(cd "$dir" && find . \( -type f -o -type l \) | sed 's|^\./||' | LC_ALL=C sort)
    echo "$tree" >"$dir/xpt.tree"
    if [ -n "$tmpd" ] && [ -f "$tmpd" ]; then
        mv "$tmpd" "$dir/xpt.manifest"
    fi
    echo "successfully created a treefile for $dir"
}

extract_source() {
    archive="$1"
    builddir="$2"

    mkdir -p "$builddir"

    case "${pkgsrcformat:-archive}" in
    archive)
        case "$archive" in
        *.tar.gz | *.tgz)
            decomp="gzip"
            ;;
        *.tar.xz)
            decomp="xz"
            ;;
        *.tar.bz2)
            decomp="bzip2"
            ;;
        *.tar.zst)
            decomp="zstd"
            ;;
        *.tar)
            tar -xf "$archive" -C "$builddir"
            return
            ;;
        *.zip)
            command -v unzip >/dev/null 2>&1 || {
                echo "! unzip not found" >&2
                exit 1
            }
            unzip "$archive" -d "$builddir"
            return
            ;;
        *)
            echo "! unsupported archive format: $archive" >&2
            exit 1
            ;;
        esac
        command -v tar >/dev/null 2>&1 || {
            echo "! tar not found" >&2
            exit 1
        }
        command -v "${decomp}" >/dev/null 2>&1 || {
            echo "! ${decomp} not found" >&2
            exit 1
        }
        (cd "$builddir" && "$decomp" -dc "$archive" | tar -xf -) || {
            echo "! failed to extract $archive" >&2
            exit 1
        }
        ;;
    *)
        cp "$archive" "$builddir/$(basename $archive)"
        return
        ;;
    esac
}

build_formula() {
    pkgdir=
    buildroot=
    sourcedir=

    cleanup() {
        [ -z "$pkgdir" ] || rm -rf "$pkgdir"
        [ -z "$buildroot" ] || rm -rf "$buildroot"
        [ -z "$sourcedir" ] || rm -rf "$sourcedir"
    }

    if [ -z "${EBS_SKIP_CLEANUP:-}" ]; then
        trap cleanup EXIT
    fi

    formula_script=${1:-ebs.formula}
    output_file=${2:-ebs.auto}

    SOURCE_DATE_EPOCH=${SOURCE_DATE_EPOCH:-0}
    export SOURCE_DATE_EPOCH

    initdir="$(pwd)"

    case "$formula_script" in
    /*) formula_path="$formula_script" ;;
    *) formula_path="$initdir/$formula_script" ;;
    esac

    if ! [ -f "${formula_path:-}" ]; then
        echo "! formula $formula_path does not exist" >&2
        exit 1
    fi

    formuladir="$(cd "$(dirname "$formula_path")" && pwd)"
    filesdir="$formuladir/files"
    export formuladir filesdir

    . "$formula_path"
    [ -n "${ebsver:-}" ] || {
        echo "! ebsver not set in $formula_script" >&2
        exit 1
    }

    case "$ebsver" in
    1) ;;
    *)
        echo "! incompatible ebs formula version" >&2
        exit 1
        ;;
    esac

    echo "> validating formula"

    type build >/dev/null 2>&1 || {
        echo "! function 'build()' not found" >&2
        exit 1
    }

    type package >/dev/null 2>&1 || {
        echo "! function 'package()' not found" >&2
        exit 1
    }

    [ -n "${pkgname:-}" ] || {
        echo "! attribute 'pkgname=' not set in $formula_script" >&2
        exit 1
    }

    [ -n "${pkgver:-}" ] || {
        echo "! attribute 'pkgver=' not set in $formula_script" >&2
        exit 1
    }

    [ -n "${pkgmaintainer:-}" ] || {
        echo "! attribute 'pkgmaintainer=' not set in $formula_script " >&2
        exit 1
    }

    [ -n "${pkgdesc:-}" ] || {
        echo "! attribute 'pkgdesc=' not set in $formula_script" >&2
        exit 1
    }

    pkgdir=$(mktemp -d)
    if ! [ -d "${pkgdir:-}" ]; then
        echo "! $pkgdir does not exist" >&2
        exit 1
    fi

    buildroot="${EBS_RESUME:-$(mktemp -d)}"

    if [ -z "${EBS_RESUME:-}" ] || [ -n "${EBS_FORCE_DOWNLOAD:-}" ]; then
        if [ -n "${pkgsrc:-}" ]; then
            [ -n "${pkgchecksum:-}" ] || {
                echo "! attribute 'pkgchecksum=' not set in $formula_script" >&2
                exit 1
            }
            echo "> downloading $pkgsrc"

            sourcedir="$(mktemp -d)"
            srcfile="$sourcedir/$(basename "${pkgsrc%%\?*}")"
            download "$pkgsrc" "$srcfile" || exit 1

            echo "> verifying source"

            algo="${pkgchecksum%%:*}"
            sum="${pkgchecksum#*:}"
            case "$algo" in
            md5) cmd=md5sum ;;
            sha1) cmd=sha1sum ;;
            sha224) cmd=sha224sum ;;
            sha256) cmd=sha256sum ;;
            sha384) cmd=sha384sum ;;
            sha512) cmd=sha512sum ;;
            *)
                echo "! unknown checksum algorithm: $algo" >&2
                exit 1
                ;;
            esac

            command -v "$cmd" >/dev/null 2>&1 || {
                echo "! '$cmd' not found" >&2
                exit 1
            }

            printf '%s  %s\n' "$sum" "$srcfile" | "$cmd" -c - || {
                echo "! checksum mismatch" >&2
                exit 1
            }

            echo "> extracting source"
            extract_source "$srcfile" "$buildroot"
        fi
    fi

    cd "$buildroot"

    set -- ./*
    if [ "$#" -eq 1 ] && [ -d "$1" ]; then
        cd "$1"
    fi

    if type prepare >/dev/null 2>&1; then
        echo "> preparing the package 'prepare()'"
        prepare || {
            echo "! failed preparing the package" >&2
            exit 1
        }
    fi

    echo "> building $pkgname@$pkgver 'build()'"
    build || {
        echo "! failed building the package" >&2
        exit 1
    }

    if [ "${EBS_SKIP_CHECK:-false}" = "false" ]; then
        if type check >/dev/null 2>&1; then
            echo "> running checks 'check()'"
            check || {
                echo "! check() failed" >&2
                exit 1
            }
        fi
    fi

    echo "> packaging $pkgname 'package()'"
    package "$FAKEROOT" || {
        echo "! error packaging the package" >&2
        exit 1
    }

    if [ "${EBS_NO_CLEAN_LIBTOOL:-0}" -ne 1 ]; then
        find "$pkgdir" -name '*.la' -exec rm -f {} +
    fi

    createTreefile "$pkgdir"

    echo "> compressing the package"

    if [ -z "${2:-}" ]; then
        output_file="$pkgname-$pkgver.xpt"
    fi

    case "$output_file" in
    /*) output_path=$output_file ;;
    *) output_path="$initdir/$output_file" ;;
    esac

    cat <<EOF >"$pkgdir/xpt.manifest"
// generated by ebs
build_epoch=${SOURCE_DATE_EPOCH:-0}

name=$pkgname
version=$pkgver
arch=${pkgarch:-$(uname -m)}
desc=$pkgdesc
maintainer=$pkgmaintainer
depends=${pkgdeps:-}
provides=${pkgprovides:-}
triggers=${pkgtriggers:-}
EOF

    [ "${pkglicense:-""}" != "" ] && echo "license=${pkglicense}" >>"$pkgdir/xpt.manifest"
    [ "${pkghomepage:-""}" != "" ] && echo "homepage=${pkghomepage}" >>"$pkgdir/xpt.manifest"

    chmod 755 "$pkgdir"

    if ! bsdtar --mtime "@$SOURCE_DATE_EPOCH" --uid 0 --gid 0 --numeric-owner -cf - -C "$pkgdir" . | zstd -T0 -f -o "$output_path"; then
        echo "! failed to create archive" >&2
        exit 1
    fi

    echo "> $output_path is ready."
}

case "${1:-}" in
help)
    print_ebs_help
    exit 0
    ;;

build)
    build_formula "${2:-./ebs.formula}" "${3:-}"
    ;;

*)
    echo "! invalid option: '$1'" >&2
    exit 1
    ;;
esac
