#!/usr/bin/env bash

# Dependencies
deps=('curl' 'dos2unix' 'grep' 'node' 'rows' 'sqlite3')

# Config files
config_files=('categories.json' 'countries.json' 'languages.json')

# URLs
tmp_m3u_url='https://iptv-org.github.io/iptv/index.m3u'
tmp_csv_url='https://raw.githubusercontent.com/iptv-org/database/master/data/channels.csv'

# Temporary files
tmp_m3u_file='/tmp/iptv.m3u'
tmp_csv_file='/tmp/iptv.csv'
tmp_processed_csv_file='/tmp/iptv-processed.csv'
tmp_sqlite_file='/tmp/iptv.sqlite'

# Final m3u
final_m3u='channels.m3u'

function cleanup {
    [[ -f "$tmp_m3u_file" ]] && rm "$tmp_m3u_file"
    [[ -f "$tmp_csv_file" ]] && rm "$tmp_csv_file"
    [[ -f "$tmp_processed_csv_file" ]] && rm "$tmp_processed_csv_file"
    [[ -f "$tmp_sqlite_file" ]] && rm "$tmp_sqlite_file"
}

function cleanup_and_exit {
    cleanup
    exit "$1"
}

function update {
    # Ensure old temporary files don't exist
    cleanup

    if ! curl -s "$tmp_m3u_url" > "$tmp_m3u_file"; then
        printf '%s\n' "Unable to download $tmp_m3u_url"
        cleanup_and_exit 1
    fi

    if curl -s "$tmp_csv_url" > "$tmp_csv_file"; then
        # Convert to unix format
        dos2unix "$tmp_csv_file"

        # Add links to each channel
        while read -r; do
            if [[ "$REPLY" =~ ^([^,]*), ]]; then
                id="${BASH_REMATCH[1]}"

                if [[ "$id" = 'id' ]]; then
                    printf '%s\n' "${REPLY},link"
                else
                    match="$(grep -A1 'tvg-id="'"$id"'"' "$tmp_m3u_file")"

                    if (( $? == 0 )); then
                        link="$(grep -e '^http' <<< "$match")"
                        printf '%s\n' "$REPLY,$link"
                    fi
                fi
            fi
        done < "$tmp_csv_file" > "$tmp_processed_csv_file"

        # Convert to sqlite
        rows csv2sqlite "$tmp_processed_csv_file" "$tmp_sqlite_file"

        # Create the m3u
        ./scripts/iptv-generate-m3u > "$final_m3u"

        # Delete temporary files
        cleanup_and_exit 0
    else
        printf '%s\n' "Unable to download $tmp_csv_url"
        cleanup_and_exit 1
    fi
}

# Check for missing dependencies
declare -a missing_deps=()

for dep in "${deps[@]}"; do
    type -P "$dep" >/dev/null \
        || missing_deps=( "${missing_deps[@]}" "$dep" )
done

[[ -n "${missing_deps[*]}" ]] && {
    printf '%s\n' "missing dependencies ($(
        for (( x=0; x < ${#missing_deps[@]}; x++ )); do
            printf '%s' "${missing_deps[$x]}"
            (( ( x + 1 ) < ${#missing_deps[@]} )) && printf '%s' ', '
        done
    ))"

    exit 1
}

# Ensure the required config files exist
for config in "${config_files[@]}"; do
    if [[ ! -f "config/$config" ]]; then
        printf '%s\n' "The file config/$config is missing"
        exit 1
    fi
done

# Update M3U
update