#!/bin/bash

# Test if nervogrid is available. It's used during the image creation.
# and won't be accessible otherwise. If it's not accessible then this
# script uses ssu credentials to download content from dav.
source_url="dav.ng.jollamobile.com"

source_content="default"

sources=()
file_lists=()
targets=()
source_urls=()

i=0
for content in "$@"
do
    sources[$i]=$(echo "$content" | cut -d ":" -f1)
    file_lists[$i]=$(echo "$content" | cut -d ":" -f2)
    targets[$i]=$(echo "$content" | cut -d ":" -f3)
    i=$i+1
done


use_auth=0
use_noproxy=0

USERNAME=""
PASSWD=""

tmp_dir=`mktemp -d`

function rmtemp()
{
    if [ -d $tmp_dir ]; then rm -rf $tmp_dir; fi
}


function create_urls()
{
    # Test curl call this fails and if not then the source_url can be used. Otherwise
    # fallback to the other url and use SSU credentials for authentication
    curl --noproxy '*' --insecure -f "https://$source_url/democontent/default/photos/photos.list"

    if [ $? -gt 0 ]
    then
        source_url="https://dav.jollamobile.com/democontent/$source_content"
        use_auth=1
        echo "Can't reach the default host. Using ssu credentials to download demo content."
    else
        source_url="https://$source_url/democontent/$source_content"
        use_noproxy=1
    fi

    # Create source urls and target directories
    i=0
    for source in "${sources[@]}"
    do
	source_urls[$i]="$source_url/$source/"
	mkdir -p ${targets[$i]}
        i=$i+1
    done
}

function parse_config()
{
    local input="/usr/share/jolla-preload-content"

    if [ ! -d $input ]
    then
        echo "No configuration directory found. Using the default configuration"
        return
    fi

    for file in $input/*
    do
        echo "Reading file: $file"
        # read file content
        while read -r line
        do
            echo "$line"
            if [ $line != "" ]
            then
                source_content=$line
                echo "Config found from: $line"
                return
            fi
        done < "$file"
     done

    echo "No custom configuration found for content. Using default"
}

function parse_credentials()
{
    local input="/etc/ssu/ssu.ini"

    # Make sure ssu credentials are up to date
    ssu up

    if [ $? -ne 0 ]
    then
        echo "Could not update ssu credentials."
        echo "This might cause this script to fail."
        echo "run ssu register manually first."
        rmtemp
        exit $?
    fi
    section_found=0
    # Parse ssu credentials from the file
    while IFS='=' read -r f1 f2
    do
        if [ "$f1" = "[credentials-jolla]" ] && [ $section_found -eq 0 ]
        then
            section_found=1
        fi

        if [ "$f1" = "username" ]
        then
           USERNAME="$f2"
        fi
        if [ "$f1" = "password" ]
        then
           PASSWD="$f2"
        fi
        if [ $section_found -eq 1 ] && [ "$USERNAME" != "" ] && [ "$PASSWD" != "" ]
        then
           break
        fi
    done < "$input"

    if [ "$USERNAME" = "" ] || [ "$PASSWD" = "" ]
    then
       echo "Failed to parse ssu credentials."
    fi
}


# example: download "http://path/to/file.xyz" "/path/to/save/location/file.zyz"
function download()
{
    if [ $# -ne 2 ]; then
        echo "download: expected 2 parameters, instead got $#".
        rmtemp
        exit 1
    fi

    local source=$1
    local target=$2
    local args=""

    # Use authentication if required
    if [ $use_auth -eq 1 ]; then
        args="-u $USERNAME:$PASSWD --progress-bar"
    else
        args="--insecure --progress-bar"
    fi

    echo "Downloading file: $source and saving file to $target"
    curl $args -o "$target" "$source"
    if [ $? -ne 0 ]; then
        echo "Failed to download a file: $source"
        rmtemp
        exit $?
    fi
}

function download_files()
{
    if [ $# -ne 4 ]; then
        echo "download_files: expected 4 parameters, instead got $#"
        rmtemp
        exit 1
    fi

    local index=$1
    local source=$2
    local target=$3
    local index_files=$4

    # download the list of files first
    download "$source$index" "$tmp_dir/$index"

    if ! [ -e "$tmp_dir/$index" ]; then echo "File $tmp_dir/$index does not exists!"; rmtemp; exit 1; fi

    # parse the file names from the target file
    while read line
    do
        download "$source$line" "$target$line"
        if [ $index_files -eq 1 ]; then
            tracker index --index-file $target$line
        fi
    done < "$tmp_dir/$index"
    echo "Downloading files done!"
}

##############################################################
# Figure out where to download the content
parse_config

# Create urls based content location
create_urls

# Parse ssu credentials if needed.
if [ $use_auth -eq 1 ]; then
    parse_credentials
fi

i=0
for file_list in "${file_lists[@]}"
do
    echo "Downloading $file_list..."
    download_files $file_list ${source_urls[$i]} ${targets[$i]} 0
    i=$i+1
done

# Delete created temp dir
rmtemp
#########################
