#!/bin/sh

# Source variables
. /etc/diaspora/diaspora-common.conf

echo "Download diaspora tarball version ${diaspora_version} from github.com..."

# Downloading a branch and tag is supported
if test ${diaspora_release_type} = "branch"
then
    export diaspora_archive="diaspora-release-${diaspora_version}"
else
    export diaspora_archive="diaspora-${diaspora_version}"
fi

mkdir -p ${diaspora_cache}

# Skip download if already present
if ! test -f ${diaspora_cache}/diaspora-${diaspora_version}.tar.gz
then 
    if test ${diaspora_release_type} = "branch"
    then
	wget -O ${diaspora_cache}/diaspora-${diaspora_version}.tar.gz ${github_archive_url}/release/${diaspora_version}.tar.gz
    else
        wget -O ${diaspora_cache}/diaspora-${diaspora_version}.tar.gz ${github_archive_url}/v${diaspora_version}.tar.gz
    fi
fi

echo "Checking integrity of download..."
sha256sum -c ${diaspora_sha256sums}

echo "Extracting files..."
tar -C ${diaspora_cache} -zxvf ${diaspora_cache}/diaspora-${diaspora_version}.tar.gz >/dev/null
    
echo "Copying files to ${diaspora_home}..."
    
echo "diaspora archive to copy: ${diaspora_archive}"

# Exclude user generated or files or directories
rsync -a ${diaspora_cache}/${diaspora_archive}/* ${diaspora_home} --exclude tmp --exclude log --exclude db/schema.rb --exclude app/assets --exclude public --exclude config/oidc_key.pem
cp -r  ${diaspora_cache}/${diaspora_archive}/app/assets/* ${diaspora_user_home}/app-assets
cp -r  ${diaspora_cache}/${diaspora_archive}/public/* ${diaspora_user_home}/public
chown -R ${diaspora_user}: ${diaspora_user_home}/public
chown -R ${diaspora_user}: ${diaspora_user_home}/app-assets

echo "Copying source tarball to ${diaspora_user_home}/public..."
cp -f ${diaspora_cache}/diaspora-${diaspora_version}.tar.gz ${diaspora_user_home}/public/source.tar.gz
