

# License GNU GPLv3
# Copyright (C) 2019 step
# Part of checksum script

# Usage:
# awk -F"|" -v TMPS="$TMPS" -v COPY_CMD="$COPY_CMD" -v SEP="$COLUMN_SEP" \
# -v CCOL="$COPY_COLUMNS" \
# "$TMPS".rsel

# This script copies selected rows to the clipboard falling
# back to printing all rows when COPY_CMD is null.

# Get copy-column set update, if any
1 == NR {
	if(0 < (getline ccol < (TMPS".ccol"))) {
		close(TMPS".ccol")
		gsub("/", ",", ccol)
		CCOL = ccol
	}
}

# Save all input rows in array R separating checked from unchecked.
# Input fields: # checkbox(0|1), CHECKSUM, NAME, HASH, SERIAL, PATH

{ any = any || $1 }

COPY_CMD {
	sep = rec = ""
	for(i = 1; i <= NF; i++) {
		if(index(","CCOL",", ","i",")) {
			rec = rec sep $i
			sep = SEP
		}
	}
	R[++nR,$1] = rec
	next
}

# Fallback
{ R[++nR,$1] = $0; next }

# If no row (!any) was selected then output all rows (I know, it`s weird
# but it`s also convenient) otherwise output just the selected rows.
# The following substitutions hold: if !any i,0 = i,any, if any i,1 = i,any
END {
	if(COPY_CMD) {
		for(i = 1; i <= nR; i++) {
			if((i,any) in R) {
				print R[i,any] | COPY_CMD
			}
		}
	} else {
		for(i = 1; i <= nR; i++) {
			print R[i,any]
		}
	}
	close(COPY_CMD)
}
