#!/bin/bash -e


if [ "$1" = "configure" ]; then
    # Copy the files that don't exist yet to the app-install folder and record
    # which ones are copied
    find /usr/share/app-install-ORIGIN/desktop -type f | \
    while read path; do
        file=`basename $path`
        if [ ! -e /usr/share/app-install/desktop/$file ]; then
            ln -s $path /usr/share/app-install/desktop/$file
            echo /usr/share/app-install/desktop/$file >> /usr/share/app-install-ORIGIN/list
        fi
    done
    find /usr/share/app-install-ORIGIN/icons -type f | \
    while read path; do
        file=`basename $path`
        if [ ! -e /usr/share/app-install/icons/$file ]; then
            ln -s $path /usr/share/app-install/icons/$file
            echo /usr/share/app-install/icons/$file >> /usr/share/app-install-ORIGIN/list
        fi
    done
    
    # Update the app-install cache
    if [ -x "`which update-app-install 2>/dev/null`" ]; then
        update-app-install
    fi
    
    # Add our key
    if [ -e /usr/share/app-install/channels/ORIGIN.key ]; then
        (apt-key list | grep -q "pub.*/GPGKEY") || apt-key add /usr/share/app-install/channels/ORIGIN.key
    fi
    
    # Fix the sources.list
    mirrors=(MIRRORS)
    rand=$(python -c "import random; print random.randint(0,${#mirrors[*]})")
    mirror=${mirrors[$rand]}
    sed -e "s!MIRROR!$mirror!" -i /etc/apt/sources.list.d/ORIGIN.list
    sed -e "s!MIRROR!$mirror!" -i /usr/share/app-install/channels/ORIGIN.list
    
    # Record the current lsb_release version so we can signal for updates if
    # someone upgrades their os
    lsb_release -sr > /usr/share/app-install-ORIGIN/version
fi
