#!/bin/bash

BASE_URL=$1
TARGET_CHANNEL=$2
SITE_PATH=$3
RELEASE_BASE_PATH=$4

update_contents() {
    local TARGET_PATH=$1
    # Escape slashes in the variable
    echo $TARGET_PATH
    CLEAN=$(echo "$TARGET_PATH/" | sed 's/\//\\\//g')
    echo $CLEAN
    # Use the escaped variable in a sed command
    echo "find $TARGET_PATH -type f | sed -e \"s|$CLEAN||g\" > \"$TARGET_PATH/content.txt\""
    find $TARGET_PATH -type f | sed -e "s|$CLEAN||g" > "$TARGET_PATH/content.txt"
    cat "$TARGET_PATH/content.txt"
}

process_contents() {
    local base="content"
    local channel=$1
    local file="$base-$channel.txt"
    curl "$BASE_URL/$channel/$base.txt" -o "$file"
    mkdir $channel

    # Fetch files from page
    # Read each line from the file
    while IFS= read -r line; do
        # Execute your command for each line
        echo "Processing: $line"
        if [ "$line" == "" ]; then
            echo "Empty line, aborting."
            exit 0
        fi        
        # make parent dirs
        mkdir -p `dirname "$channel/$line"`
        # get file
        echo curl "$BASE_URL/$channel/$line" -o "$channel/$line"
        curl "$BASE_URL/$channel/$line" -o "$channel/$line"
    done < "$file"
    # update contents
    update_contents $channel
    mkdir -p $RELEASE_BASE_PATH/$channel
    cp -r -f $channel/* $RELEASE_BASE_PATH/$channel
}

# update contents
update_contents "$SITE_PATH"

# process opposite channel
if [ "$TARGET_CHANNEL" == "beta" ]; then
    process_contents "stable"
else
    process_contents "beta"
fi


# # Debugging
# BASE_URL="https://top.etsi.org/top-extras/updatesite"
# TARGET_CHANNEL="stable"
# SITE_PATH="updatesite/org.etsi.mts.tdl.extras.updatesite/target/repository"
# RELEASE_BASE_PATH="public/updatesite"

# update_contents "$SITE_PATH"
# process_contents "$TARGET_CHANNEL"
