#!/bin/bash
# aur-sync - download and build AUR packages automatically
[[ -v AUR_DEBUG ]] && set -o xtrace
set -o errexit
argv0=sync
XDG_CACHE_HOME=${XDG_CACHE_HOME:-$HOME/.cache}
XDG_CONFIG_HOME=${XDG_CONFIG_HOME:-$HOME/.config}
XDG_DATA_HOME=${XDG_DATA_HOME:-$HOME/.local/share}
XDG_RUNTIME_DIR=${XDG_RUNTIME_DIR:-/run/user/$UID}
AURDEST=${AURDEST:-$XDG_CACHE_HOME/aurutils/$argv0}
AUR_SYNC_USE_NINJA=${AUR_SYNC_USE_NINJA:-0}
PS4='+(${BASH_SOURCE}:${LINENO}): ${FUNCNAME[0]:+${FUNCNAME[0]}(): }'

# default arguments
build_args=(--clean --syncdeps) depends_args=() repo_args=() view_args=() filter_args=() fetch_args=()

# default options
build=1 chkver_depth=2 download=1 view=1 provides=1 graph=1 keep_going=1

# default options (disabled)
rotate=0 update=0 repo_targets=0

lib32() {
    awk -v arch="$(uname -m)" '{
        if(arch == "i686") {
            gsub(/^lib32-/,"")
            gsub(/^gcc-multilib$/,"")
        }
        print
    }' "$@"
}

# argv[1]: $1 pkgname $2 depends $3 pkgbase
# note: edges are not checked for duplicates
select_pkgbase() {
    awk 'NR == FNR {
        map[$1] = $3
        next
    }
    $2 in map {
        printf("%s\t%s\n", $3, map[$2])
    }' "$@"
}

# argv[1]: $1 pkgname (possibly empty, #910)
# argv[2]: $1 pkgname $2 pkgver
select_ignores() {
    awk 'ARGV[1] == FILENAME {
        map[$1] = 1
        next
    }
    !($1 in map) {
        print
    }' "$@"
}

select_ignores_pkgspec() {
    awk -F'/' -v needle="$1" '{
        if (NF == 2 && $1 == needle) {
            print $2
        } else if (NF == 1) {
            print $1
        }
    }' "${@:2}"
}

# argv[1]: $1 pkgname $2 depends[<>=]
tr_ver() {
    awk '{
        sub(/[<>=].*/, "", $2)
        print
    }' "$@"
}

complement() {
    # empty set should not return 1
    grep -Fxvf "$@" || return $(( $? - 1 ))
}

trap_exit() {
    if [[ ! -v AUR_DEBUG ]]; then
        rm -rf -- "$tmp"
    else
        printf >&2 'AUR_DEBUG: %s: temporary files at %s\n' "$argv0" "$tmp"
    fi
}

usage() {
    plain >&2 'usage: %s [-d repo] [--root path] [-cdfoSu] pkgname...' "$argv0"
    exit 1
}

source /usr/share/makepkg/util/message.sh
source /usr/share/makepkg/util/parseopts.sh

if [[ ! -v NO_COLOR ]] && [[ ! -v AUR_DEBUG ]]; then
    [[ -t 2 ]] && colorize
fi

# 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

opt_short='d:D:k:U:AcfLnorRSTuv'
opt_long=('bind:' 'bind-rw:' 'database:' 'directory:' 'ignore:' 'root:'
          'makepkg-conf:' 'pacman-conf:' 'chroot' 'continue' 'force'
          'ignore-arch' 'log' 'no-confirm' 'no-ver' 'no-graph' 'no-ver-argv'
          'no-view' 'no-provides' 'no-build' 'rmdeps' 'sign' 'temp' 'upgrades'
          'pkgver' 'rebuild' 'rebuild-tree' 'rebuild-all' 'ignore-file:'
          'remove' 'provides-from:' 'new' 'prevent-downgrade' 'verify'
          'makepkg-args:' 'format:' 'no-check' 'keep-going:' 'user:'
          'rebase' 'reset' 'ff')
opt_hidden=('dump-options' 'allan' 'ignorearch' 'ignorefile:' 'noconfirm'
            'nover' 'nograph' 'nover-argv' 'noview' 'noprovides' 'nobuild'
            'rebuildall' 'rebuildtree' 'rm-deps' 'gpg-sign' 'margs:' 'nocheck'
            'no-checkdepends' 'nocheckdepends' 'optdepends' 'repo:')

if ! parseopts "$opt_short" "${opt_long[@]}" "${opt_hidden[@]}" -- "$@"; then
    usage
fi
set -- "${OPTRET[@]}"

unset pkg pkg_i repo repo_p ignore_file
while true; do
    case "$1" in
        # sync options
        --allan)
            rotate=1 ;;
        --continue)
            download=0 ;;
        --format)
            shift; view_args+=(--format "$1") ;;
        --ignore)
            shift; IFS=, read -a pkg -r <<< "$1"
            pkg_i+=("${pkg[@]}") ;;
        --ignorefile|--ignore-file)
            shift; ignore_file=$1 ;;
        -k|--keep-going)
            shift; keep_going=$1 ;;
        -o|--nobuild|--no-build)
            build=0 ;;
        --optdepends)
            depends_args+=(--optdepends) ;;
        --nocheck|--no-check|--nocheckdepends|--no-checkdepends)
            depends_args+=(--no-checkdepends)
            build_args+=(--no-check) ;;
        --nograph|--no-graph)
            graph=0 ;;
        --nover|--no-ver)
            chkver_depth=0 ;;
        --nover-argv|--no-ver-argv)
            chkver_depth=1 ;;
        --noview|--no-view)
            view=0 ;;
        --noprovides|--no-provides)
            provides=0 ;;
        --provides-from)
            shift; IFS=, read -a repo -r <<< "$1"
            repo_p+=("${repo[@]}")
            provides=1 ;;
        --rebuild)
            build_args+=(-f); chkver_depth=1 ;;
        --rebuildtree|--rebuild-tree)
            build_args+=(-f); chkver_depth=0 ;;
        --rebuildall|--rebuild-all)
            build_args+=(-f); chkver_depth=0; repo_targets=1 ;;
        -u|--upgrades)
            update=1 ;;
        # database options
        -d|--database|--repo)
            shift; repo_args+=(-d "$1") ;;
        --root)
            shift; repo_args+=(-r "$1") ;;
        # fetch options
        --ff)
            fetch_args+=(--ff) ;;
        --rebase)
            fetch_args+=(--rebase) ;;
        --reset)
            fetch_args+=(--reset) ;;
        # build options
        -c|--chroot)
            build_args+=(--chroot) ;;
        -f|--force)
            build_args+=(--force) ;;
        --makepkg-args|--margs)
            shift; build_args+=(--margs "$1") ;;
        --makepkg-conf)
            shift; build_args+=(--makepkg-conf "$1") ;;
        --pacman-conf)
            shift; build_args+=(--pacman-conf "$1")
            repo_args+=(--config "$1")
            filter_args+=(--config "$1") ;;
        --pkgver)
            build_args+=(--pkgver) ;;
        -S|--sign|--gpg-sign)
            build_args+=(--sign) ;;
        -U|--user)
            shift; build_args+=(--user "$1") ;;
        # build options (devtools)
        -D|--directory)
            shift; build_args+=(--directory "$1") ;;
        --bind)
            shift; build_args+=(--bind "$1") ;;
        --bind-rw)
            shift; build_args+=(--bind-rw "$1") ;;
        -T|--temp)
            build_args+=(-T) ;;
        # build options (makepkg)
        -A|--ignorearch|--ignore-arch)
            build_args+=(--ignorearch) ;;
        -L|--log)
            build_args+=(--log) ;;
        -n|--noconfirm|--no-confirm)
            build_args+=(--noconfirm) ;;
        -r|--rmdeps|--rm-deps)
            build_args+=(--rmdeps) ;;
        # build options (repo-add)
        -R|--remove)
            build_args+=(--remove) ;;
        -v|--verify)
            build_args+=(--verify) ;;
        --prevent-downgrade)
            build_args+=(--prevent-downgrade) ;;
        --new)
            build_args+=(--new) ;;
        # other options
        --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

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

# Default to showing PKGBUILD first in patch. (#399)
orderfile=$XDG_CONFIG_HOME/aurutils/$argv0/orderfile
mkdir -p "${orderfile%/*}"

if [[ ! -s $orderfile ]]; then
    printf 'PKGBUILD\n' > "$orderfile"
fi

if (( rotate )); then
    if { hash rot13 && target=$(aur pkglist | shuf -n 1); } 2>/dev/null; then
        exec bash -c "{ aur \"$argv0\" -c \"$target\" && repo-elephant | rot13; } 2>&1 | rot13"
    else
        echo '?'; exit 16 # EBUSY
    fi
fi

mkdir -p "$AURDEST"
cd "$tmp"

# Retrieve path to local repo (#448, #700)
aur repo "${repo_args[@]}" --status-file=db
{ IFS=: read -r _ db_name
  IFS=: read -r _ db_root
  IFS=: read -r _ db_path
} <db

if (( $# + update + repo_targets == 0 )); then
    error '%s: no targets specified' "$argv0"
    exit 1
fi

if [[ -w $db_path ]]; then
    msg >&2 'Using [%s] repository' "$db_name"
else
    error '%s: %s: permission denied' "$argv0" "$db_path"
    exit 13
fi

# Concatenate ignores from file and command-line arguments
: "${ignore_file=$XDG_CONFIG_HOME/aurutils/sync/ignore}"

# Restrict ignores to local repository with a single pass (#880)
{ if [[ -r $ignore_file ]] && [[ ! -d $ignore_file ]]; then
      select_ignores_pkgspec "$db_name" "$ignore_file"
  fi
  (( ${#pkg_i[@]} )) && printf '%s\n' "${pkg_i[@]}"
} | complement <(printf '%s\n' "$@") >igni

if [[ -s igni ]]; then
    printf '%s: packages ignored: ' "$argv0"
    awk -v ORS=' ' '{print} END {printf("\n")}' igni
fi >&2

# db_info: $1 pkgname $2 pkgver
( set -o pipefail
  aur repo "${repo_args[@]}" --list -d "$db_name" -r "$db_root" | select_ignores igni -
) >db_info

{ if (( $# )); then
      # append command-line arguments
      printf '%s\n' "$@"
  fi

  if (( repo_targets )); then
      # append repository packages (all)
      cut -f1 <db_info

  elif (( update )); then
      # append repository packages (updated)
      aur vercmp --quiet <db_info
  fi
} >argv

if [[ -s argv ]]; then
    # shellcheck disable=SC2094
    # depends: $1 pkgname $2 depends $3 pkgbase $4 pkgver $5 depends_type
    aur depends --table "${depends_args[@]}" - <argv >depends
else
    plain >&2 "there is nothing to do"
    exit
fi

# pkginfo: $1 pkgname $2 pkgbase $3 pkgver
cut -f2,5 --complement depends | sort -u >pkginfo

{ cat igni # ignored packages

  # Packages with equal or newer versions are taken as complement
  # for the queue. If chkver_argv is enabled, packages on the
  # command-line are excluded from this complement.
  if (( chkver_depth )); then
      # note: AUR cannot be queried by pkgbase (FS#57230)
      cut -f1,3 pkginfo | aur vercmp -p db_info -c >current

      # shellcheck disable=SC2002
      case $chkver_depth in
          1) cat current | complement argv ;;
          2) cat current ;;
      esac
  fi

  if (( provides )); then
      if (( ${#repo_p[@]} )); then
          filter_args+=("${repo_p[@]/#/--repo=}")
      else
          filter_args+=(--sync)
      fi

      # Note: this uses pacman's copy of the repo (as used by makepkg -s)
      cut -f1 pkginfo | aur repo-filter "${filter_args[@]}" | complement argv
  fi
} >filter

# $1 pkgname $2 depends $3 pkgbase, filter by $2 (depends and self)
cut -f1-3 depends | tr_ver - | select_ignores filter - | lib32 - >graph_0

# XXX a flat file is needed for aur-{graph,fetch,view}. `ninja` requires the
# build files to be present before dependency resolution (with `ninja -n`) can
# occur, and `ninja -t targets` sorts in alphabetical order. This implies
# that dependency cycles cannot be resolved before retrieving files with
# aur-fetch with `ninja` alone. `tsort` could either be used in this case (with
# a less nice diagnostic on cycles), or fetches done in an arbitrary order
# (e.g. sort -u) with checks for cycles done at build-time.
select_pkgbase graph_0 graph_0 | tee graph | tsort | tac >queue

# XXX: preserve tsort exit status
if (( PIPESTATUS[2] )); then
    error '%s: dependency cycle detected' "$argv0"
    exit 22
fi

if [[ -s queue ]]; then
    cd "$AURDEST"
else
    plain >&2 "there is nothing to do"
    exit
fi

if (( download )); then
    msg >&2 "Retrieving package files"
    aur fetch -S "${fetch_args[@]}" --discard --results "$tmp"/fetch_results - < "$tmp"/queue >&2

    # shellcheck disable=SC2034
    while IFS=: read -r mode rev_old rev path; do
        path=${path#file://} name=${path##*/}

        case $mode in
            clone)
                git -C "$path" config diff.orderFile "$orderfile" ;;
            fetch|merge|rebase|reset)
                ;;
        esac
    done < "$tmp"/fetch_results
fi

# Verify dependency tree (#20)
if (( graph )); then
    if ! { while read -r pkg; do
               [[ $pkg ]] && printf '%s\0' "$pkg/.SRCINFO"
           done
         } | xargs -0 cat -- | aur graph >/dev/null
    then
        error '%s: failed to verify dependency graph' "$argv0"
        exit 1
    fi < "$tmp"/queue
fi

# Inspect package files
if (( view )); then
    aur view -a "$tmp"/queue "${view_args[@]}"
fi

# Build dependency tree with ninja (#908)
if (( AUR_SYNC_USE_NINJA )); then
    # directory for stamp files (concurrent aur-sync processes)
    mkdir -p "$XDG_RUNTIME_DIR"/aurutils
    build_dir=$XDG_RUNTIME_DIR/aurutils/ninja-$USER-$$
    mkdir "$build_dir"

    # generate build.ninja
    # input:  $AURDEST/pkgbase/PKGBUILD
    # output: $AURDEST/$build_dir/pkgbase.stamp
    cd "$build_dir"
    sort -k1b,1 -k1 -u "$tmp"/graph | aur sync--ninja "$AURDEST" >build.ninja \
        -- aur build "${build_args[@]}" -d "$db_name" --root "$db_root"

    if (( build )) && NINJA_STATUS='[%s/%t] ' ninja -k "$keep_going"; then
        # remove ninja directory on successful build
        rm -rf "$build_dir"

    elif (( build )); then
        # print all targets in dependency order
        NINJA_STATUS='[%s/%t] ' ninja -nC /var/empty -f "$PWD"/build.ninja | \
            # [\w@\.\-\+]: valid characters for pkgname
            # alternative: [^\s]+ from rule `env -C ... > pkgbase.stamp`
            pcregrep -o1 -o3 '(\[\d+/\d+\] )(.+?)([\w@\.\-\+]+)(\.stamp)' | while read -r status pkg
        do
            if [[ -f $pkg.stamp ]]; then
                printf "${BOLD}${BLUE}%s${ALL_OFF} %s\t${BOLD}${GREEN}[OK]${ALL_OFF}\n" "$status" "$pkg"
            else
                printf "${BOLD}${BLUE}%s${ALL_OFF} %s\t${BOLD}${RED}[FAIL]${ALL_OFF}\n" "$status" "$pkg"
            fi
        done | column -t

        # preserve ninja directory
        printf '%s: build files at %s\n' "$argv0" "$(pwd -P)"
    else
        printf '%s\n' "$(pwd -P)"
    fi

elif (( build )); then
    aur build "${build_args[@]}" -a "$tmp"/queue -d "$db_name" --root "$db_root"
else
    while read -r pkg; do
        [[ $pkg ]] && printf '%s\n' "$(pwd -P)/$pkg"
    done < "$tmp"/queue
fi

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