#!/bin/bash

#
# perltidy rules can be found in ../.perltidyrc
#
usage() {
    cat << EOF
Usage:
 tidy [-c|--check] [-f|--force] [-o|--only-changed]

Options:
 -h, -?, --help       display this help
 -c, --check          Only check for style check differences
 -f, --force          Force check even if tidy version mismatches
 -o --only-changed    Only tidy files with uncommitted changes in git. This can
                      speed up execution a lot.

perltidy rules can be found in .perltidyrc
EOF
    exit
}

cleanup() {
    find . -name '*.tdy' -delete
}

set -eo pipefail

check=
only_changed=false
opts=$(getopt -o hcfo --long help,check,force,only-changed -n 'parse-options' -- "$@") || usage
eval set -- "$opts"
while true; do
  case "$1" in
    -h | --help ) usage; shift ;;
    -c | --check ) check=true; shift ;;
    -f | --force ) force=true; shift ;;
    -o | --only-changed ) only_changed=true; shift ;;
    -- ) shift; break ;;
    * ) break ;;
  esac
done

trap cleanup EXIT

if ! command -v perltidy > /dev/null 2>&1; then
    echo "No perltidy found, install it first!"
    exit 1
fi

# cpan file is in top directory
dir="$(dirname "$0")/.."
perltidy_version_expected=$(sed -n "s/^.*Tidy[^0-9]*\([0-9]*\)['];$/\1/p" "$dir"/cpanfile)
if [ -z "${perltidy_version_expected}" ]; then
    # No cpanfile in the linked repo, use the one from os-autoinst instead
    dir="$(dirname "$(readlink -f "$0")")/.."
    perltidy_version_expected=$(sed -n "s/^.*Tidy[^0-9]*\([0-9]*\)['];$/\1/p" "$dir"/cpanfile)
fi
perltidy_version_found=$(perltidy -version | sed -n '1s/^.*perltidy, v\([0-9]*\)\s*$/\1/p')
if [ "$perltidy_version_found" != "$perltidy_version_expected" ]; then
    echo -n "Wrong version of perltidy. Found '$perltidy_version_found', expected '$perltidy_version_expected'."
    if [[ "$force" = "true" ]]; then
        echo "Found '--force', continuing"
    else
        echo "Consider '--force' but results might not be consistent."
        exit 1
    fi
fi

find-files() {
    local files=()
    [[ -d script ]] && files+=(script/*)
    # shellcheck disable=SC2207
    files=($(file --mime-type -- * "${files[@]}" | (grep text/x-perl || true) | awk -F':' '{ print $1 }'))
    files+=('**.p[ml]' '**.t')
    if $only_changed; then
        git status --porcelain "${files[@]}" | awk '{ print $2 }'
    else
        git ls-files "${files[@]}"
    fi
}

# go to caller directory
cd "$(dirname "$0")/.."

# just to make sure we are at the right location
test -e tools/tidy || exit 1

cleanup

find-files | xargs perltidy --pro=.../.perltidyrc

find . -name "*.tdy" | while read -r file
do
    if diff -u "${file%.tdy}" "$file"; then
        continue
    fi
    if [[ -n "$check" ]]; then
        echo "RUN tools/tidy script before checkin"
        exit 1
    else
        mv -v "$file" "${file%.tdy}"
    fi
done
