#!/bin/zsh
#
# Copyright (C) 2023-2024 Dyne.org Foundation
#
# Designed, written and maintained by Denis Roio <jaromil@dyne.org>
#
# This source code is free software; you can redistribute it and/or
# modify it under the terms of the GNU Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This source code is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	Please refer
# to the GNU Public License for more details.
#
# You should have received a copy of the GNU Public License along with
# this source code; if not, , see <https://www.gnu.org/licenses/>.

source /etc/dyne/snapshot.conf

function mm() {	>&2 echo "dyne-snapshot: $*"; }

[[ -r /usr/local/bin/dyne-install ]] || {
	mm "not running on a dynebolic system"
	exit 1
}

ls /run/live/persistence | grep loop && {
   mm "a nest is in use, aborting operation"
   exit 1
}

[[ $UID = 0 ]] || {
	mm "need root to make a snapshot: su dyne"
	exit 1
}

mm "Snapshot current changes on dyne:bolic"

let MINIMUM_LEN=8
let MAXIMUM_LEN=16
set -A CHARS a b c d e f g h i j k l m n o p q r s t u v w x y z \
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z \
0 1 2 3 4 5 6 7 8 9
CNUM="${#CHARS[@]}"
MAXLEN=$(( $MINIMUM_LEN + ( $RANDOM % ( $MAXIMUM_LEN - $MINIMUM_LEN ) ) ))
RANDSTR=""
let POSCNT=0;
while [ 1 -eq 1 ]
    do
    if [ $POSCNT -ge $MAXLEN ]
        then
            break;
    fi
    let POSCNT=$POSCNT+1
    RANDSTR="${RANDSTR}${CHARS[${RANDOM}%${CNUM}]}"
done
RANDSTR="${RANDSTR}${CHARS[${RANDOM}%${CNUM}]}"

outfile="dyneIV-snapshot-`date +'%d%m%y'`-${RANDSTR}.squashfs"
mm "New: $outfile"

mm "Compressing snapshot..."
outmp=`mktemp`
tar -c /run/live/overlay/rw | tar2sqfs -r /run/live/overlay/rw -f -q -c xz ${outmp}

mm "Uploading..."

chmod a+r "${outmp}"
sktmp=`mktemp`; echo "$SK" | base64 -d > $sktmp
scp -i "${sktmp}" "${outmp}" "${SSH}:snapshots/${outfile}"
[[ $? = 0 ]] || {
	mm "SSH transfer error."
	rm -f "${sktmp}"
	exit 1
}
rm -f "${sktmp}"

URL="${HOSTNAME}/snapshots/$outfile"
mm "$URL"
echo "$URL" | qrencode -t ansi
mm "$URL"

mv "${outmp}" "${outfile}"
mm "Success!"
