#!/bin/bash
# aur-build - build packages to a local repository
[[ -v AUR_DEBUG ]] && set -o xtrace
set -o errexit
shopt -s extglob
argv0=build
machine=$(uname -m)
startdir=$PWD
PS4='+(${BASH_SOURCE}:${LINENO}): ${FUNCNAME[0]:+${FUNCNAME[0]}(): }'

# Avoid CDPATH screwing with cd (#1047)
unset -v CDPATH

# default options
chroot=0 no_sync=0 overwrite=0 sign_pkg=0 run_pkgver=0 truncate=1

# default arguments (empty)
chroot_args=() pacconf_args=() repo_args=() repo_add_args=() pkglist_args=()
makepkg_args=() makechrootpkg_makepkg_args=() makepkg_common_args=() read_args=()

# default arguments
gpg_args=(--detach-sign --no-armor --batch)
makechrootpkg_args=(-cu) # -c to clean working copy, -u to sync local repository builds

args_csv() {
    # shellcheck disable=SC2155
    local str=$(printf '%s,' "$@")
    printf '%s' "${str%,}"
}

diag_moved_packages() {
    # Print diagnostic on non-moved packages (#794)
    cat <<EOF >&2
Note:
    aur-build encountered an error before moving packages to the local repository.
    This may happen when signing built packages with gpg (aur build --sign),
    or with certain makepkg errors.

    The following files were preserved:
EOF
    #shellcheck disable=SC2030
    realpath -z -- "$@" | while read -rd ''; do
        printf '%8s%s\n' ' ' "$REPLY"
    done
}

diag_pacman_conf() {
    cat <<EOF >&2
Error:
    aur-build could not find a pacman.conf(5) file for container usage. Before
    using --chroot, make sure this file is created and valid. See OPTIONS in
    aur-build(1) for configuration details.

    The following file paths were checked:
EOF
    #shellcheck disable=SC2030
    realpath -z -- "$@" | while read -rd ''; do
        printf '%8s%s\n' ' ' "$REPLY"
    done
}

get_local_upgrades() {
    local repo=$1

    LANG=C pacman -Sup --print-format '%r/%n' | while IFS=/ read -ra line; do
        case ${line[0]} in
            "$repo")
                printf '%s\n' "$repo/${line[1]}" ;;
            ::\ *)  # XXX: pacman prints diagnostics to standard output
                printf >&2 '%s\n' "${line[*]}" ;;
        esac
    done
    return "${PIPESTATUS[0]}"
}

trap_exit() {
    if [[ ! -v AUR_DEBUG ]]; then
        rm -rf -- "$tmp"

        # Only remove package directory if all files were moved (#593)
        if ! rm -df -- "$var_tmp"; then
            diag_moved_packages "$var_tmp"/*
        fi
    else
        printf >&2 'AUR_DEBUG: %s: temporary files at %s\n' "$argv0" "$tmp"
        printf >&2 'AUR_DEBUG: %s: temporary files at %s\n' "$argv0" "$var_tmp"
    fi
}

usage() {
    printf >&2 'usage: %s [-acfNS] [-d repo] [--root path] [--margs makepkg_arg...]\n' "$argv0"
    exit 1
}

# mollyguard for makepkg
if (( UID == 0 )) && ! [[ -v AUR_ASROOT ]]; then
    warning 'aur-%s is not meant to be run as root.' "$argv0"
    warning 'To proceed anyway, set the %s variable.' 'AUR_ASROOT'
    exit 1
fi

## option parsing
opt_short='a:d:D:U:AcCfnrsvzLNRST'
opt_long=('arg-file:' 'chroot' 'database:' 'force' 'root:' 'sign' 'gpg-sign'
          'verify' 'directory:' 'no-sync' 'pacman-conf:' 'remove' 'pkgver'
          'rmdeps' 'no-confirm' 'no-check' 'ignore-arch' 'log' 'new'
          'makepkg-conf:' 'bind:' 'bind-rw:' 'prevent-downgrade' 'temp'
          'syncdeps' 'clean' 'namcap' 'checkpkg' 'makepkg-args:' 'user:'
          'margs:' 'buildscript:' 'null')
opt_hidden=('dump-options' 'ignorearch' 'noconfirm' 'nocheck' 'nosync' 'repo:'
            'results:' 'results-append:')

if opts=$(getopt -o "$opt_short" -l "$(args_csv "${opt_long[@]}" "${opt_hidden[@]}")" -n "$argv0" -- "$@"); then
    eval set -- "$opts"
else
    usage
fi

unset db_name db_path db_root makepkg_conf pacman_conf results_file pkgrel_incr queue
while true; do
    case "$1" in
        # build options
        -a|--arg-file)
            shift; queue=$1 ;;
        -f|--force)
            overwrite=1 ;;
        -c|--chroot)
            chroot=1 ;;
        -d|--database|--repo)
            shift; db_name=$1
            repo_args+=(--repo "$1") ;;
        --buildscript)
            shift; makepkg_common_args+=(-p "$1")
            pkglist_args+=(-p "$1") ;;
        --nosync|--no-sync)
            no_sync=1 ;;
        --makepkg-conf)
            shift; makepkg_conf=$1 ;;
        --pacman-conf)
            shift; pacman_conf=$1 ;;
        --pkgver)
            run_pkgver=1; makepkg_args+=(--noextract)
            makechrootpkg_makepkg_args+=(--holdver) ;;
        --root)
            shift; db_root=$1
            repo_args+=(--root "$1") ;;
        -S|--sign|--gpg-sign)
            sign_pkg=1; repo_add_args+=(-s) ;;
        # chroot options
        -D|--directory)
            shift; chroot_args+=(-D "$1") ;;
        --bind)
            shift; makechrootpkg_args+=(-D "$1") ;;
        --bind-rw)
            shift; makechrootpkg_args+=(-d"$1") ;;
        -N|--namcap)
            makechrootpkg_args+=(-n) ;;
        --checkpkg)
            makechrootpkg_args+=(-C) ;;
        -T|--temp)
            makechrootpkg_args+=(-T) ;;
        -U|--user)
            shift; makechrootpkg_args+=(-U "$1") ;;
        # makepkg options (common)
        -A|--ignorearch|--ignore-arch)
            makepkg_common_args+=(--ignorearch)
            makechrootpkg_makepkg_args+=(--ignorearch) ;;
        -n|--noconfirm|--no-confirm)
            makepkg_common_args+=(--noconfirm) ;;
        -r|--rmdeps)
            makepkg_common_args+=(--rmdeps) ;;
        -s|--syncdeps)
            makepkg_common_args+=(--syncdeps) ;;
        # makepkg options (build)
        -C|--clean)
            makepkg_args+=(--clean) ;;
        -L|--log)
            makepkg_args+=(--log) ;;
        --nocheck|--no-check)
            makepkg_args+=(--nocheck)
            makechrootpkg_makepkg_args+=(--nocheck) ;;
        --makepkg-args|--margs)
            shift; IFS=, read -a arg -r <<< "$1"
            makepkg_args+=("${arg[@]}")
            makechrootpkg_makepkg_args+=("${arg[@]}") ;;
        # repo-add options
        -v|--verify)
            repo_add_args+=(-v) ;;
        -R|--remove)
            repo_add_args+=(-R) ;;
        --new)
            repo_add_args+=(-n) ;;
        --prevent-downgrade)
            repo_add_args+=(-p) ;;
        # other options
        --results)
            shift; results_file=$1 ;;
        --results-append)
            shift; results_file=$1; truncate=0 ;;
        -z|--null)
            read_args+=(-d $'\0') ;;
        --dump-options)
            printf -- '--%s\n' "${opt_long[@]}" ${AUR_DEBUG+"${opt_hidden[@]}"}
            printf -- '%s' "${opt_short}" | sed 's/.:\?/-&\n/g'
            exit ;;
        --) shift; break ;;
    esac
    shift
done

# Assign environment variables
: "${db_ext=$AUR_DBEXT}" "${db_root=$AUR_DBROOT}" "${db_repo=$AUR_REPO}"

# shellcheck disable=SC2174
mkdir -pm 0700 -- "${TMPDIR:-/tmp}/aurutils-$UID"
tmp=$(mktemp -d --tmpdir "aurutils-$UID/$argv0.XXXXXXXX")

# shellcheck disable=SC2174
mkdir -pm 0700 -- "${TMPDIR:-/var/tmp}/aurutils-$UID"
var_tmp=$(mktemp -d --tmpdir="${TMPDIR:-/var/tmp/}" "aurutils-$UID/$argv0.XXXXXXXX")

trap 'trap_exit' EXIT
trap 'exit' INT

# XXX: default paths can be set through the Makefile
if (( chroot )); then
    # The pacman configuration in the chroot may contain a local repository that
    # is not configured on the host. Therefore, $db_name is only used for the
    # default paths below when specified on the command-line or through `AUR_REPO`.
    if [[ $db_name ]]; then
        default_pacman_paths=("/etc/aurutils/pacman-$db_name.conf"
            "/etc/aurutils/pacman-$machine.conf")
        default_makepkg_paths=("/etc/aurutils/makepkg-$db_name.conf"
            "/etc/aurutils/makepkg-$machine.conf")
    else
        default_pacman_paths=("/etc/aurutils/pacman-$machine.conf")
        default_makepkg_paths=("/etc/aurutils/makepkg-$machine.conf")
    fi

    # Change the default /usr/share/devtools/pacman-extra.conf in aur-chroot to
    # /etc/aurutils/pacman-<repo>.conf or /etc/aurutils/pacman-<uname>.conf in
    # aur-build, and pass it on to aur-chroot (#824, #846)
    for def in "${default_pacman_paths[@]}"; do
        if [[ -f $def ]] && [[ ! -v pacman_conf ]]; then
            pacman_conf=$def
            break
        fi
    done

    # The same as above but for /etc/aurutils/makepkg-<repo>.conf or
    # /etc/aurutils/makepkg-<uname>.conf. If the file is not found, fallback to
    # makepkg.conf files in /usr/share/devtools.
    for def in "${default_makepkg_paths[@]}"; do
        if [[ -f $def ]] && [[ ! -v makepkg_conf ]]; then
            makepkg_conf=$def
            break
        fi
    done

    # No pacman configuration is available for the container, or it points to a
    # non-existing file. Print a matching diagnostic and exit.
    if [[ ! -v pacman_conf ]]; then
        diag_pacman_conf "${default_pacman_paths[@]}"
        exit 2

    elif [[ ! -f $pacman_conf ]]; then
        diag_pacman_conf "$pacman_conf"
        exit 2
    fi
    chroot_args+=(--pacman-conf "$pacman_conf")

    # The default path is /usr/share/devtools/makepkg-<uname.conf>, which is
    # copied to <container path>/etc/makepkg.conf by arch-nspawn.
    if [[ -v makepkg_conf ]]; then
        chroot_args+=(--makepkg-conf "$makepkg_conf")
    else
        # When `makechrootpkg` calls `makepkg` inside the container, it uses the devtools
        # `makepkg.conf` for most variables including PKGEXT. (`makepkg --packagelist`)
        makepkg_conf=$(aur chroot --path "${chroot_args[@]}")/etc/makepkg.conf
        unset PKGEXT
    fi

    # Propagate makepkg/makechrootpkg arguments to aur-chroot
    if (( ${#makechrootpkg_args[@]} )); then
        chroot_args+=(--cargs "$(args_csv "${makechrootpkg_args[@]}")")
    fi
    if (( ${#makechrootpkg_makepkg_args[@]} )); then
        chroot_args+=(--margs "$(args_csv "${makechrootpkg_makepkg_args[@]}")")
    fi
fi

# Propagate makepkg and pacman configuration to other tools. This must be done
# BEFORE retrieving the local repository name/root. It should be done AFTER
# retrieving the container configuration, as it may contain (local) repositories
# not enabled on the host.
if [[ -v pacman_conf ]]; then
    pacconf_args+=(--config "$pacman_conf")
fi

if [[ -v makepkg_conf ]]; then
    makepkg_common_args+=(--config "$makepkg_conf")
    pkglist_args+=(--config "$makepkg_conf")
fi

# Automatically choose the local repository based on the pacman configuration.
if [[ $db_name ]] && [[ $db_root ]]; then
    db_path=$db_root/$db_name.${db_ext:-db}
    db_path=$(realpath -- "$db_path")
else
    { IFS=: read -r _ db_name
      IFS=: read -r _ db_root
      IFS=: read -r _ db_path # canonicalized
    } < <(aur repo --status "${repo_args[@]}" "${pacconf_args[@]}")
    wait "$!"
fi
db_root=$(realpath -- "$db_root")

# Check that a valid database extension was retrieved (#700, #1038)
if [[ -z $AUR_DBEXT ]] && [[ $db_path =~ \.db$ ]]; then
    printf >&2 '%s: %s does not have a valid database archive extension\n' "$argv0" "$db_path"
    # TODO: this usually happens on file systems not supporting symbolic links
    # (SMB/CIFS). Add a diagnostic to point towards AUR_DBEXT in this case
    exit 2
fi

# File permission checks
if [[ ! -f $db_path ]]; then
    printf >&2 '%s: %s: not a regular file\n' "$argv0" "$db_path"
    exit 2
elif [[ ! -w $db_path ]]; then
    printf >&2 '%s: %s: permission denied\n' "$argv0" "$db_path"
    exit 13
elif [[ -v pacman_conf ]] && [[ ! -r $pacman_conf ]]; then
    printf >&2 '%s: %s: permission denied\n' "$argv0" "$pacman_conf"
    exit 13
elif [[ -v makepkg_conf ]] && [[ ! -r $makepkg_conf ]]; then
    printf >&2 '%s: %s: permission denied\n' "$argv0" "$makepkg_conf"
    exit 13
fi

# Write successfully built packages to file (#437, #980)
if [[ -v results_file ]]; then
    results_file=$(realpath -- "$results_file")
    (( truncate )) && true | tee "$results_file"
fi

if (( chroot )); then
    # Update pacman and makepkg configuration for the chroot build
    # queue. A full system upgrade is run on the /root container to
    # avoid lenghty upgrades for makechrootpkg -u.
    aur chroot --create --update "${chroot_args[@]}"
fi

if [[ -v queue ]]; then
    exec {fd}< "$queue"
else
    exec {fd}< <(echo "$startdir")
fi

# Early consistency check for signed database
if (( ! sign_pkg )); then
    db_sigs=("$db_root/$db_name".sig "$db_root/$db_name".files.sig)

    if [[ -f ${db_sigs[0]} ]]; then
        printf >&2 '%s: database signature found, but signing is disabled\n' "$argv0"

        printf '%q\n' >&2 "${db_sigs[@]}"
        exit 1
    fi

elif [[ -v GPGKEY ]]; then
    #shellcheck disable=SC2086
    ${AUR_GPG:-gpg} --list-keys "$GPGKEY"
    gpg_args+=(-u "$GPGKEY")
fi

while IFS= read "${read_args[@]}" -ru "$fd" path; do
    cd -- "$startdir"
    [[ $path ]] && cd -- "$path"

    # Allow running repo-add(8) on existing packages (#839)
    create_package=1
    pkglist=()

    # Run pkgver function before --packagelist (#500)
    if (( run_pkgver )); then
        #shellcheck disable=SC2086
        ${AUR_MAKEPKG:-makepkg} -od "${makepkg_common_args[@]}" >&2
    fi

    # Retrieve list of potential package paths. This is used to (optionally)
    # check if package paths are already available in the local repository
    # before builds. If so, the build is skipped and the path is passed to
    # repo-add (create_package=0). If no paths are available, the package is
    # assumed to not exist and the build proceeds as usual (create_package=1).
    if (( ! overwrite )); then
        exists=()
        #shellcheck disable=SC2086
        while read -r pkgpath; do
            [[ -f $pkgpath ]] && exists+=("$pkgpath")
        done < <(PKGDEST="$db_root" ${AUR_BUILD_PKGLIST:-aur build--pkglist} "${pkglist_args[@]}")

        if ! wait "$!"; then
            printf >&2 '%s: warning: failed to retrieve package list\n' "$argv0"
        fi

        if (( ${#exists[@]} )); then
            printf >&2 '%s: warning: skipping existing package (use -f to overwrite)\n' "$argv0"
            create_package=0

            printf '%q\n' >&2 "${exists[@]}"
            pkglist=("${exists[@]}")
        fi

        if (( ${#exists[@]} )) && [[ -v results_file ]]; then
            printf "exist:file://%s\n" "${exists[@]}" | tee -a "$results_file" >/dev/null
        fi
    fi

    if (( create_package )); then
        if (( chroot )); then
            PKGDEST="$var_tmp" aur chroot --build "${chroot_args[@]}"
        else
            #shellcheck disable=SC2086
            PKGDEST="$var_tmp" LOGDEST="${LOGDEST:-$PWD}" \
                ${AUR_MAKEPKG:-makepkg} "${makepkg_common_args[@]}" "${makepkg_args[@]}"
        fi

        cd -- "$var_tmp"
        pkglist=(!(*.sig)) # discard makepkg --sign from package list (#410)
    else
        cd -- "$var_tmp"
        # pkglist has paths to $db_root/<pkg>
    fi

    # Sign any packages without signatures, even if the packages are existing.
    siglist=()

    for p in "${pkglist[@]}"; do
        # Package basename (equals $p if create_package=1)
        p_base=${p##*/}

        # Signature from makepkg --sign
        if [[ -f $p_base.sig ]]; then
            siglist+=("$p_base".sig)

        # Skipped package build with signature
        elif [[ -f $db_root/$p_base.sig ]] && [[ ! -f $p_base ]]; then
            printf >&2 '%s: existing signature file %q\n' "$argv0" "$db_root/$p_base.sig"

        # No candidate signature, generate one
        elif (( sign_pkg )); then
            #shellcheck disable=SC2086
            ${AUR_GPG:-gpg} "${gpg_args[@]}" --output "$p_base".sig "$p"

            printf >&2 '%s: created signature file %q\n' "$argv0" "$p_base".sig
            siglist+=("$p_base".sig)
        fi
    done

    if (( create_package )); then
        mv -f "${siglist[@]}" "${pkglist[@]}" "$db_root"

        if [[ -v results_file ]]; then
            printf "build:file://$db_root/%s\n" "${pkglist[@]}" | tee -a "$results_file" >/dev/null
        fi

    elif (( ${#siglist[@]} )); then
        mv -f "${siglist[@]}" "$db_root"
    fi

    # Update database
    #shellcheck disable=SC2086
    env -C "$db_root" LANG=C ${AUR_REPO_ADD:-repo-add} "${repo_add_args[@]}" "$db_path" "${pkglist[@]}"

    if (( chroot )) || (( no_sync )); then
        continue
    else
        #shellcheck disable=SC2086
        ${AUR_PACMAN_AUTH:-sudo} pacsync "$db_name"
        #shellcheck disable=SC2086
        ${AUR_PACMAN_AUTH:-sudo} pacsync "$db_name" --dbext=.files

        # Retrieve upgrade targets in local repository. May error in case of
        # conflicts or dependency errors.
        mapfile -t targets < <(get_local_upgrades "$db_name")
        wait "$!"

        if (( ${#targets[@]} )); then
            printf >&2 "%s: upgrading packages in repository '%s'\n" "$argv0" "$db_name"
            #shellcheck disable=SC2086
            printf '%s\n' "${targets[@]}" | ${AUR_PACMAN_AUTH:-sudo} pacman -S --noconfirm -
        fi
    fi
done

exec {fd}<&-

# vim: set et sw=4 sts=4 ft=sh:
