#!/bin/bash

#set -x

CURL_CONFIGS="--silent --show-error --fail --insecure --location -b cookies.txt -c cookies.txt"
#CURL_CONFIGS="--insecure --location -b cookies.txt -c cookies.txt"
CURL_CONFIGS2="--show-error --fail --insecure --location -b cookies.txt -c cookies.txt"

DOWNLOAD_FILE=https://support.criticallink.com/redmine/attachments/download/8271/MitySOM-335X_Dev_SD_512MB_NAND.zip
USER=user
PASS=pass

cleanup()
{
    rm -f cookies.txt
}

# Initial cleanup
cleanup

# Fetch CSRF authenticity token
CSRF1=$(curl $CURL_CONFIGS https://support.criticallink.com/redmine/login | grep "name=\"authenticity_token" | sed 's/.*value="\(.*\)".*/\1/')

if [[ $? -ne 0  ]]
then
    echo "Error getting csrf token"
    echo $CSRF1
    cleanup
    exit 1
fi

#echo $CSRF1

# Login
HTML=$(curl $CURL_CONFIGS -d "login=Login&username=${USER}&password=${PASS}&authenticity_token=${CSRF1}" https://support.criticallink.com/redmine/login)
 
#echo $HTML

if [[ $? -ne 0  ]]
then
    echo "Error logging in"
    cleanup
    exit 1
fi

# Download file
curl $CURL_CONFIGS2 $DOWNLOAD_FILE --remote-name

if [[ $? -ne 0  ]]
then
    echo "Error downloading backup file" | tee -a ${LOGFILE}
    cleanup
    exit 1
fi

cleanup
