#!/usr/bin/env bash

set -eo pipefail

check_macos_package() {
    local binary="${1}"
    local package="${2}"

    if ! command -v "${binary}" >/dev/null 2>&1; then
        echo
        echo -e "\\033[31;1m"
        echo "Seems that you're using Mac OS. In case of troubles with packaging ensure"
        echo "that ${package} is installed. You can do this e.g. with 'brew install ${package}'"
        echo -e "\\033[0m"
        echo
    fi
}

base_input_part="out/helper-images/prebuilt-"
base_output_part="/usr/lib/gitlab-runner/helper-images/prebuilt-"

prebuilt_images_list=$(cat <<-END
            ${base_input_part}alpine-arm.tar.xz=${base_output_part}alpine-arm.tar.xz \
            ${base_input_part}alpine-arm64.tar.xz=${base_output_part}alpine-arm64.tar.xz \
            ${base_input_part}alpine-s390x.tar.xz=${base_output_part}alpine-s390x.tar.xz \
            ${base_input_part}alpine-x86_64-pwsh.tar.xz=${base_output_part}alpine-x86_64-pwsh.tar.xz \
            ${base_input_part}alpine-x86_64.tar.xz=${base_output_part}alpine-x86_64.tar.xz \
            ${base_input_part}ubuntu-arm.tar.xz=${base_output_part}ubuntu-arm.tar.xz \
            ${base_input_part}ubuntu-arm64.tar.xz=${base_output_part}ubuntu-arm64.tar.xz \
            ${base_input_part}ubuntu-ppc64le.tar.xz=${base_output_part}ubuntu-ppc64le.tar.xz \
            ${base_input_part}ubuntu-s390x.tar.xz=${base_output_part}ubuntu-s390x.tar.xz \
            ${base_input_part}ubuntu-x86_64-pwsh.tar.xz=${base_output_part}ubuntu-x86_64-pwsh.tar.xz \
            ${base_input_part}ubuntu-x86_64.tar.xz=${base_output_part}ubuntu-x86_64.tar.xz
END
        )

prebuilt_images_list_fips=$(cat <<-END
        ${base_input_part}ubi-fips-x86_64.tar.xz=${base_output_part}ubi-fips-x86_64.tar.xz
END
    )

create_package() {
    local packageType=${1}
    local prebuilt_images_list=${2}
    local package_postfix=${3}
    shift
    shift
    shift

    local customOptions
    read -r -a customOptions <<< "${@}"

    if [ -z "${PACKAGE_ARCH}" ]; then
      echo "PACKAGE_ARCH not specified, aborting."
      exit 1
    fi

    local uname_s
    uname_s=$(uname -s)

    if [[ "${uname_s}" == "Darwin" ]]; then
        check_macos_package "gtar" "gnu-tar"
        check_macos_package "rpmbuild" "rpm"
    fi

    mkdir -p "out/${packageType}/"

    fpm \
        --package "out/${packageType}/${PACKAGE_NAME}_${PACKAGE_ARCH}${package_postfix}.${packageType}" \
        --force \
        --input-type dir \
        --output-type "${packageType}" \
        \
        --name "${PACKAGE_NAME}${package_postfix}" \
        --description "GitLab Runner" \
        --version "${VERSION}" \
        --url https://gitlab.com/gitlab-org/gitlab-runner \
        --maintainer "GitLab Inc. <support@gitlab.com>" \
        --license "MIT" \
        --vendor "GitLab Inc." \
        --architecture "${PACKAGE_ARCH}" \
        \
        --conflicts "${PACKAGE_NAME}-beta" \
        --conflicts "${PACKAGE_NAME}-fips" \
        --conflicts gitlab-ci-multi-runner \
        --conflicts gitlab-ci-multi-runner-beta \
        --provides gitlab-ci-multi-runner \
        --replaces gitlab-ci-multi-runner \
        \
        --depends git \
        --depends curl \
        --depends tar \
        \
        "${customOptions[@]}" \
        \
        --after-install "packaging/scripts/postinst.${packageType}" \
        --before-remove "packaging/scripts/prerm.${packageType}" \
        \
        packaging/root/=/ \
        "${RUNNER_BINARY}=/usr/bin/gitlab-runner" \
        ${prebuilt_images_list}
}

create_deb() {
    local options=()
    options+=("--depends ca-certificates")
    options+=("--category admin")
    options+=("--deb-priority optional")
    options+=("--deb-compression bzip2")
    options+=("--deb-suggests docker-engine")

    create_package deb "${prebuilt_images_list}" "" "${options[@]}"

    if [ -n "${GPG_KEYID}" ]; then
        dpkg-sig \
            -g "--no-tty --digest-algo 'sha512' --passphrase '${GPG_PASSPHRASE}' --pinentry-mode=loopback" \
            -k "${GPG_KEYID}" \
            --sign builder \
            "out/deb/${PACKAGE_NAME}_${PACKAGE_ARCH}.deb"
    fi
}

create_rpm() {
    local options=()
    options+=("--rpm-compression bzip2")
    options+=("--rpm-os linux")
    options+=("--rpm-digest sha256")

    create_package rpm "${prebuilt_images_list}" "" "${options[@]}"
    sign_rpm "${PACKAGE_NAME}_${PACKAGE_ARCH}.rpm"
}

create_rpm_fips() {
    local options=()
    options+=("--rpm-compression bzip2")
    options+=("--rpm-os linux")
    options+=("--depends openssl")
    options+=("--rpm-digest sha256")

    create_package rpm "${prebuilt_images_list_fips}" "-fips" "${options[@]}"
    sign_rpm "${PACKAGE_NAME}_${PACKAGE_ARCH}-fips.rpm"
}

sign_rpm() {
  local package_name=${1}

  if [ -n "${GPG_KEYID}" ] ; then
          echo "yes" | setsid rpm \
              --define "_gpg_name ${GPG_KEYID}" \
              --define "_signature gpg" \
              --define "__gpg_check_password_cmd /bin/true" \
              --define "__gpg_sign_cmd $(command -v gpg) --batch --no-armor --digest-algo 'sha512' --passphrase '${GPG_PASSPHRASE}' --pinentry-mode=loopback --no-secmem-warning -u '%{_gpg_name}' --sign --detach-sign --output %{__signature_filename} %{__plaintext_filename}" \
              --addsign "out/rpm/${package_name}"
      fi
}

case "${1}" in
    deb)
        create_deb
        ;;
    rpm)
        create_rpm
        ;;
    rpm-fips)
        create_rpm_fips
        ;;
    *)
        echo "Usage: ${0} (deb|rpm)"
        ;;
esac
