#!/usr/bin/env bash

# Bash Scripting for AVpres
# Seventh Session: find missing files in a folder, course script
# 2022-02-15

# initialise constants
SCRIPT_NAME="$(basename "${0}")"
RED='\033[1;31m'
BLUE='\033[1;34m'
NC='\033[0m'

# initialise variables
unset input_folder
unset output_file


# if no input is provided, then display a minimal help message and exit with 1
if (( "${#}" == 0 )); then
    cat << EOF
Help:
  ${SCRIPT_NAME} -h
EOF
    exit 1
fi


# display an error message and exit with 1
prompt_error() {
    echo -e "${RED}Error: ${1:-unknown error.\a}${NC}"
    exit 1
}


# display a help message and exit with 0
prompt_help() {
    cat << EOF

Syntax:
  ${SCRIPT_NAME} -i <input_folder> [-o <output_file>]
  ${SCRIPT_NAME} -h

Parameters:
  -i  path and name of the input folder
  -o  path, name and extension of the output file
      (default is <input_folder>_missing.txt)
  -h  display this help

EOF
    exit 0
}


# verify input (and normalise path if needed)
verify_input() {
    local in_folder="${1}"

    if [[ ! "${in_folder}" ]]; then
        prompt_error "No input folder passed."
    elif [[ ! -d "${in_folder}" ]]; then
        prompt_error "'${in_folder}' is not a folder."
    elif [[ "${in_folder%/*}" == "${in_folder}" ]]; then
        input_folder="${PWD}/${in_folder}"
    fi

    if [[ ! $(ls -A "${in_folder}") || $(ls -A "${in_folder}") == '.DS_Store' ]]; then
        prompt_error "Error: '${in_folder}' is empty."
    fi

    return 0
}


# verify output file
verify_output() {
    local out_file="${1}"

    if ! : > "${out_file}" &> /dev/null; then
        prompt_error "Cannot create an output file '${out_file}'."
    fi

    return 0
}


# check files in folder
check_files() {
    local in_folder="${1}"
    local out_file="${2}"
    local first_file
    local first_number
    local last_file
    local last_number
    local filename_regex
    local tmp

    echo -e "${BLUE}Please wait while verifying...${NC}"

    # find the first number
    first_file=$(ls "${in_folder}" | sort | head -n 1)
    first_number=$(echo "${first_file}" | grep -oE '_[0-9]+\.' | grep -oE '[0-9]+')
    if [[ ! "${first_number}" ]]; then
        first_number=$(echo "${first_file}" | grep -oE '[0-9]+')
    fi
    if [[ ! "${first_number}" =~ ^[0-9]+$ ]]; then
        rm "${out_file}"
        prompt_error "'${first_file}' is not a valid first file."
    fi

    # find the last number
    last_file=$(ls "${in_folder}" | sort | tail -n 1)
    last_number=$(echo "${last_file}" | grep -oE '_[0-9]+\.' | grep -oE '[0-9]+')
    if [[ ! "${last_number}" ]]; then
        last_number=$(echo "${last_file}" | grep -oE '[0-9]+')
    fi
    if [[ ! "${last_number}" =~ ^[0-9]+$ ]]; then
        rm "${out_file}"
        prompt_error "'${last_file}' is not a valid last file."
    fi

    # verify that first number is lower or equal than last number
    if [[ "${first_number}" > "${last_number}" ]]; then
        rm "${out_file}"
        prompt_error "The numbering of '${in_folder}' is not valid."
    fi

    # generate regex
    if [[ "${first_number}" == $(basename "${first_file%.*}") ]]; then
        filename_regex="${in_folder}/%0${#first_number}d.${first_file##*.}"
    else
        filename_regex="${in_folder}/${first_file%_*}_%0${#first_number}d.${first_file##*.}"
    fi

    # verify that all files of the interval exist
    for ((f=((10#${first_number})); f<=((10#${last_number})); f++)); do
        tmp=$(printf "${filename_regex}" "$f")
        if [[ ! -e "${tmp}" ]]; then
            basename "${tmp}" >> "${out_file}"
        fi
    done

    # report results
    if [[ ! -s "${out_file}" ]]; then
        rm "${out_file}"
        echo -e "${BLUE}All files are present in '$(basename "${in_folder}")'.${NC}"
    else
        echo -e "${RED}The following files of the intervall from '${first_number}' to '${last_number}' are missing:${NC}"
        cat "${out_file}" | sed 's/^/  /'
    fi
    if [[ -f "${out_file}" ]]; then
        exit 1
    else
        exit 0
    fi
}


# parse and process provided input
(( $# == 0 )) && print_prompt
while getopts ":i:o:h" opt; do
    case "${opt}" in
        i) if [[ "${OPTARG:0:1}" == '-' ]]; then
              prompt_error "The option '-i' requires an argument."
           else
              input_folder="${OPTARG}"
           fi ;;
        o) if [[ "${OPTARG:0:1}" == '-' ]]; then
              prompt_error "The option '-o' requires an argument."
           else
              output_file="${OPTARG}"
           fi ;;
        h) prompt_help ;;
        :) prompt_error "The option '-${OPTARG}' requires an argument." ;;
        *) prompt_error "The option '-${OPTARG}' is not valid." ;;
    esac
done


# check if provided input is valid
verify_input "${input_folder}"
if [[ ! "${output_file}" ]]; then
    output_file="${input_folder}_missing.txt"
fi
verify_output "${output_file}"

# check files in folder
check_files "${input_folder}" "${output_file}"
