#!/usr/bin/env bash
# reindex 1.6.6
# Generates table of scripts

output_file="index.md"

echo "## Scripts" > "$output_file"
printf "Useful shell scripts.\n\nTo use a script, download it locally by clicking on its respective link below. You can then run the script from its download location or move it to a directory in your system's PATH for easier access. To view the source code of these scripts directly, go to [Github](https://github.com/kquo/bits/tree/main/scripts).\n\n" >> "$output_file"

echo "| Script Name | Version    | Comment               |" >> "$output_file"
echo "|-------------|------------|-----------------------|" >> "$output_file"

for script in *; do
    [[ -f "$script" ]] || continue

    l1=$(sed -n '1p' "$script")
    l2=$(sed -n '2p' "$script")
    l3=$(sed -n '3p' "$script")

    script_name=$(basename "$script")
    version="-"
    comment="-"

    # Shell scripts
    if [[ "$l1" == "#!/"* && "$l2" == "# "* ]]; then
        version=$(echo "$l2" | awk '{print $NF}')
        comment=$(echo "$l3" | sed 's/^# //')

    # Go scripts: "// name version"
    elif [[ "$l1" == "//"* && "$l2" == "//"* ]]; then
        # The first part of the cleaned line is the script name, and the last part is the version
        version=$(echo "$l2" | awk '{print $NF}')
        comment=$(echo "$l3" | sed 's|^// *||') # Comment from the first line

    else
        continue
    fi

    script_link="[$script_name]($script)"

    printf "| %-11s | %-10s | %-21s |\n" \
        "$script_link" "$version" "$comment" >> "$output_file"
done

printf "\n( REMINDER: Don't edit this \`index.md\` file directly -- run the \`reindex\` script instead. )\n\n" >> "$output_file"

echo "Generated $output_file with script details."
