#!/bin/bash
#set -x
exec > /dev/null

action=$1
id=$2
conf_dir="/unas/run/docker/export_image/$id"
# The task conf
conf_file="$conf_dir/conf"
# The exported file name for user to download
name_file="$conf_dir/name"
# The actual exported file name
filename_origin_file="$conf_dir/name_ori"
# The path to the exported file
filepath_file="$conf_dir/filepath"

. $conf_file

if [ -d "$TARGET_DIR" ];then
    if [ "$USER" != "admin" ] && ! sudo -u $USER test -w "$TARGET_DIR" ;then
        exit 2 # Permission denied
    fi
fi

prepare_(){
    :
}

start_(){
    image_name=`echo $IMAGE | awk -F: '{print $1}'`
    image_name=`basename $image_name`
    image_tag=`echo $IMAGE | awk -F: '{print $2}'`
    filepath="$TARGET_DIR/${image_name}.tar.gz"
    docker save $IMAGE | gzip - > $filepath
    chown $USER:`groups $USER | awk '{print $3}'` $filepath
}

clear_(){
    rm -rf "$conf_dir"
}

case "$action" in
    start)
        prepare_
        start_
        ;;
    clear)
        clear_
        ;;
    *)
        ;;
esac

exit 0
