# Copyright (c) 2024, HCUOpt CORPORATION.  All rights reserved.

ARG BASEIMAGE
FROM ${BASEIMAGE}

ENV DEBIAN_FRONTEND=noninteractive

# ARG REPO_MIRROR=http://mirrors.aliyun.com

# RUN set -ex \
#     && rm -f /etc/apt/apt.conf.d/docker-clean \
#     && sed -i "s@http://.*.ubuntu.com@${REPO_MIRROR}@g" /etc/apt/sources.list

RUN apt-get update && apt-get install -y --no-install-recommends \
        wget \
        ca-certificates \
        git \
        build-essential \
        dh-make \
        fakeroot \
        devscripts \
        lsb-release && \
    rm -rf /var/lib/apt/lists/*

ARG GOLANG_VERSION=0.0.0
RUN set -eux; \
    \
    arch="$(uname -m)"; \
    case "${arch##*-}" in \
        x86_64 | amd64) ARCH='amd64' ;; \
        ppc64el | ppc64le) ARCH='ppc64le' ;; \
        aarch64 | arm64) ARCH='arm64' ;; \
        *) echo "unsupported architecture" ; exit 1 ;; \
    esac; \
    wget -nv -O - https://golang.google.cn/dl/go${GOLANG_VERSION}.linux-${ARCH}.tar.gz \
    | tar -C /usr/local -xz

ENV GOPATH /go
ENV PATH $GOPATH/bin:/usr/local/go/bin:$PATH

# packaging
ARG PKG_NAME
ARG PKG_VERS
ARG PKG_REV

ENV DEBFULLNAME "HCUOpt. CORPORATION"
ENV REVISION "$PKG_VERS-$PKG_REV"
ENV SECTION ""

# output directory
ENV DIST_DIR=/tmp/dtk-container-toolkit-$PKG_VERS
RUN mkdir -p $DIST_DIR /dist

# dtk-container-toolkit
WORKDIR $GOPATH/src/dtk-container-toolkit
COPY . .

ARG GIT_COMMIT
ENV GIT_COMMIT ${GIT_COMMIT}
RUN make PREFIX=${DIST_DIR} cmds

WORKDIR $DIST_DIR
COPY packaging/debian ./debian

RUN dch --create --package="${PKG_NAME}" \
        --newversion "${REVISION}" \
            "See ${GOPATH}/src/dtk-container-toolkit/CHANGELOG.md for the changelog" && \
    dch -r "" && \
    if [ "$REVISION" != "$(dpkg-parsechangelog --show-field=Version)" ]; then exit 1; fi

CMD export DISTRIB="$(lsb_release -cs)" && \
    debuild -eDISTRIB -eSECTION -eVERSION="${REVISION}" \
    --dpkg-buildpackage-hook='sh debian/prepare' -i -us -uc -b && \
    mv /tmp/*.deb /dist
