#!/bin/sh

set -eu

target_dir=

while [ $# -gt 0 ]; do
    case $1 in
        -h|--help)
            shift
            echo "Usage: $0 [OPTION]... [CHANGES_FILE]..."
            echo
            echo 'Do things to files listed in .changes file. If CHANGES_FILE is'
            echo 'omitted, it will be deduced from debian/changelog.'
            echo
            echo "Options:"
            echo "    -h, --help                   print help and exit"
            echo "    -c, --copy DIR               copy files to DIR"
            echo "    -l, --link DIR               link files to DIR"
            echo "    -m, --move DIR               move files to DIR"
            echo "    -r, --remove                 remove files"
            echo
            exit 0
            ;;
        -c|--copy)
            shift
            target_dir=$1
            shift
            cmd="cp -v -a -t ${target_dir}"
            ;;
        -l|--link)
            shift
            target_dir=$1
            shift
            cmd="cp -v -a -l -t ${target_dir}"
            ;;
        -m|--move)
            shift
            target_dir=$1
            shift
            cmd="mv -v -t ${target_dir}"
            ;;
        -r|--remove)
            shift
            cmd="rm -f"
            ;;
        --)
            shift
            break
            ;;
        -*)
            echo "error: invalid argument '$1'" >&2
            exit 1
            ;;
        *)
            break
            ;;
    esac
done

if [ $# -eq 0 ]; then
    pkg_name=$(dpkg-parsechangelog -SSource)
    pkg_version=$(dpkg-parsechangelog -SVersion | sed -r -n 's/^([0-9]+:)?(.+)$/\2/p')
    pkg_arch=$(dpkg-architecture -qDEB_BUILD_ARCH)
    set -- "../${pkg_name}_${pkg_version}_${pkg_arch}.changes"
fi

while [ $# -gt 0 ]; do
    changes_file=$1
    shift
    source_dir=$(dirname "${changes_file}")

    if [ -n "${target_dir}" ]; then
        mkdir -p "${target_dir}"
    fi

    awk -v"source_dir=${source_dir}" \
        'NR == 1, /^Files:$/ { next } /^ / { printf "%s/%s%c", source_dir, $5, 0 }' \
        "${changes_file}" | xargs -0 ${cmd}

    ${cmd} "${changes_file}"
done
