#!/bin/sh
# Copyright 2018 Davide Alberani <da@mimante.net>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
# s3-reduce.sh: create smaller versions of .tsv.gz files

set -eu

COUNT="100"
START_DIR="$(pwd)"
MODE="head"

usage() {
    cat <<'EOF'
Usage: s3-reduce [options] [directory]

Create reduced versions of .tsv.gz files in the partials/ directory.

Options:
  -l, --lines N      Keep N lines from the head and N lines from the tail.
  -p, --percent P    Keep P percent (1-100) of lines, split between head and tail.
  -t, --titles FILE  Also keep the titles listed in FILE and what they refer to.
  -e, --episodes N   With --titles, keep N episodes of each listed series
                     (default: 10).
  -h, --help         Show this help and exit.

Default behavior (no options): keep the first 100 lines.
The first line is always preserved.

Rows selected by position are unrelated to each other: a kept title usually
has none of its cast, ratings or episodes among the kept rows.  --titles adds
complete records.  FILE lists one IMDb title id (tt0133093) per line; blank
lines and text after # are ignored.  For each listed title the output also
contains its ratings, alternative titles, crew and principals, the people
they name, the titles those people are known for, the series of a listed
episode and the first N episodes of a listed series.  It needs all seven
dataset files and can be combined with the other options.
EOF
}

die() {
    echo "Error: $*" >&2
    exit 1
}

is_non_negative_int() {
    case "$1" in
        ''|*[!0-9]*)
            return 1
            ;;
        *)
            return 0
            ;;
    esac
}

OPTS="$(getopt -o l:p:t:e:h -l lines:,percent:,titles:,episodes:,help -- "$@")" || {
    usage >&2
    exit 2
}
eval set -- "$OPTS"

HAS_LINES=0
HAS_PERCENT=0
PERCENT=""
TITLES=""
EPISODES="10"

while true
do
    case "$1" in
        -l|--lines)
            HAS_LINES=1
            COUNT="$2"
            shift 2
            ;;
        -p|--percent)
            HAS_PERCENT=1
            PERCENT="$2"
            shift 2
            ;;
        -t|--titles)
            TITLES="$2"
            shift 2
            ;;
        -e|--episodes)
            EPISODES="$2"
            shift 2
            ;;
        -h|--help)
            usage
            exit 0
            ;;
        --)
            shift
            break
            ;;
        *)
            die "unexpected option: $1"
            ;;
    esac
done

if [ "$HAS_LINES" -eq 1 ] && [ "$HAS_PERCENT" -eq 1 ] ; then
    die "--lines and --percent cannot be used together"
fi

if [ "$HAS_LINES" -eq 1 ] ; then
    MODE="lines"
fi

if [ "$HAS_PERCENT" -eq 1 ] ; then
    MODE="percent"
fi

if ! is_non_negative_int "$COUNT" ; then
    die "--lines requires a positive integer"
fi

if [ "$COUNT" -lt 1 ] ; then
    die "--lines requires a positive integer"
fi

if [ "$MODE" = "percent" ] ; then
    if ! is_non_negative_int "$PERCENT" ; then
        die "--percent requires an integer between 1 and 100"
    fi
    if [ "$PERCENT" -lt 1 ] || [ "$PERCENT" -gt 100 ] ; then
        die "--percent must be between 1 and 100"
    fi
fi

if ! is_non_negative_int "$EPISODES" ; then
    die "--episodes requires a non-negative integer"
fi

if [ "$#" -gt 1 ] ; then
    die "too many positional arguments"
fi

if [ "$TITLES" != "" ] ; then
    [ -r "$TITLES" ] || die "cannot read the --titles file: $TITLES"
    # Resolve it before changing directory.
    TITLES="$(cd "$(dirname "$TITLES")" && pwd)/$(basename "$TITLES")"
fi

if [ "${1:-}" != "" ] ; then
    cd "$1"
fi

mkdir -p partials

WORK_DIR=""
cleanup() {
    if [ "$WORK_DIR" != "" ] ; then
        rm -rf "$WORK_DIR"
    fi
}
trap cleanup EXIT
trap 'exit 130' INT
trap 'exit 143' TERM

# Print the rows of dataset $1 whose first column is listed in file $2.
rows_by_id() {
    zcat "$1" | awk -F '\t' '
        NR == FNR { wanted[$1]; next }
        FNR > 1 && ($1 in wanted)
    ' "$2" -
}

# Work out, in $WORK_DIR, the ids of every record the listed titles need:
#   titles      listed titles, the series of listed episodes and the kept
#               episodes of listed series: copied with all their records
#   names       people named by those titles
#   references  titles plus what the people are known for: only their
#               basic data and ratings are copied
select_records() {
    for required in name.basics title.akas title.basics title.crew \
            title.episode title.principals title.ratings
    do
        [ -e "${required}.tsv.gz" ] || \
            die "--titles needs ${required}.tsv.gz in $(pwd)"
    done
    WORK_DIR="$(mktemp -d)"

    sed -e 's/#.*//' -e 's/[[:space:]]//g' "$TITLES" | grep -v '^$' | \
        sort -u > "$WORK_DIR/listed" || true
    [ -s "$WORK_DIR/listed" ] || die "no title ids found in $TITLES"
    if grep -v '^tt[0-9][0-9]*$' "$WORK_DIR/listed" > "$WORK_DIR/invalid" ; then
        die "invalid title id in $TITLES: $(head -1 "$WORK_DIR/invalid")"
    fi

    zcat title.episode.tsv.gz | awk -F '\t' -v cap="$EPISODES" '
        NR == FNR { listed[$1]; next }
        FNR == 1 { next }
        $1 in listed { print $2 }
        ($2 in listed) && kept[$2] < cap { kept[$2]++; print $1 }
    ' "$WORK_DIR/listed" - | cat - "$WORK_DIR/listed" | \
        sort -u > "$WORK_DIR/titles"

    {
        zcat title.principals.tsv.gz | awk -F '\t' '
            NR == FNR { titles[$1]; next }
            FNR > 1 && ($1 in titles) { print $3 }
        ' "$WORK_DIR/titles" -
        zcat title.crew.tsv.gz | awk -F '\t' '
            NR == FNR { titles[$1]; next }
            FNR > 1 && ($1 in titles) {
                count = split($2 "," $3, people, ",")
                for (i = 1; i <= count; i++) {
                    print people[i]
                }
            }
        ' "$WORK_DIR/titles" -
    } | grep '^nm' | sort -u > "$WORK_DIR/names" || true

    zcat name.basics.tsv.gz | awk -F '\t' '
        NR == FNR { names[$1]; next }
        FNR > 1 && ($1 in names) {
            count = split($6, known, ",")
            for (i = 1; i <= count; i++) {
                print known[i]
            }
        }
    ' "$WORK_DIR/names" - | grep '^tt' | cat - "$WORK_DIR/titles" | \
        sort -u > "$WORK_DIR/references" || true
}

# Print the complete records of dataset $1 selected by select_records.
selected_rows() {
    case "$1" in
        name.basics.tsv.gz)
            rows_by_id "$1" "$WORK_DIR/names"
            ;;
        title.basics.tsv.gz|title.ratings.tsv.gz)
            rows_by_id "$1" "$WORK_DIR/references"
            ;;
        title.*.tsv.gz)
            rows_by_id "$1" "$WORK_DIR/titles"
            ;;
    esac
}

if [ "$TITLES" != "" ] ; then
    select_records
fi

for fname in *.tsv.gz
do
    [ -e "${fname}" ] || continue

    case "$MODE" in
        head)
            zcat "${fname}" | head -"${COUNT}" | gzip -f - > "partials/${fname}"
            ;;
        lines)
            zcat "${fname}" | awk -v n="${COUNT}" '
                {
                    if (NR <= n) {
                        print
                    }
                    if (n > 0) {
                        tail[NR % n] = $0
                    }
                    total = NR
                }
                END {
                    if (n <= 0) {
                        exit
                    }
                    start = total - n + 1
                    if (start <= n + 1) {
                        start = n + 1
                    }
                    for (i = start; i <= total; i++) {
                        print tail[i % n]
                    }
                }
            ' | gzip -f - > "partials/${fname}"
            ;;
        percent)
            total_lines="$(zcat "${fname}" | wc -l)"
            keep_lines=$((total_lines * PERCENT / 100))
            if [ "$keep_lines" -lt 1 ] ; then
                keep_lines=1
            fi

            head_lines=$((keep_lines / 2))
            tail_lines=$((keep_lines - head_lines))

            if [ "$head_lines" -lt 1 ] ; then
                head_lines=1
                if [ "$keep_lines" -gt 1 ] ; then
                    tail_lines=$((keep_lines - 1))
                else
                    tail_lines=0
                fi
            fi

            if [ "$total_lines" -le "$head_lines" ] || [ "$total_lines" -le $((head_lines + tail_lines)) ] ; then
                zcat "${fname}" | gzip -f - > "partials/${fname}"
            elif [ "$tail_lines" -le 0 ] ; then
                zcat "${fname}" | head -"${head_lines}" | gzip -f - > "partials/${fname}"
            else
                {
                    zcat "${fname}" | head -"${head_lines}"
                    zcat "${fname}" | tail -"${tail_lines}"
                } | gzip -f - > "partials/${fname}"
            fi
            ;;
        *)
            die "internal error: invalid mode ${MODE}"
            ;;
    esac

    if [ "$TITLES" != "" ] ; then
        # Append the selected records that the positional cut left out.
        {
            zcat "partials/${fname}"
            selected_rows "${fname}"
        } | awk '!seen[$0]++' | gzip -f - > "$WORK_DIR/merged.gz"
        mv "$WORK_DIR/merged.gz" "partials/${fname}"
    fi
done

if [ "${1:-}" != "" ] ; then
    cd "${START_DIR}"
fi
