# Tiny Cloud - Main Phase Functions
# vim:set ts=4 et ft=sh:

: "${LIBDIR:=$PREFIX/lib}"
. "$LIBDIR"/tiny-cloud/init-common

# ensure existence of output directories
[ ! -d "$TINY_CLOUD_LOGS" ] && mkdir -p "$TINY_CLOUD_LOGS"
[ ! -d "$TINY_CLOUD_VAR" ] && mkdir -p "$TINY_CLOUD_VAR"

set_hostname() {
    skip_action set_hostname && return

    local fqdn=$(imds @hostname)
    local host="${fqdn%%\.*}"

    echo "$host" > /etc/hostname
    hostname -F /etc/hostname
    echo -e "127.0.1.1\t$fqdn $host" >> /etc/hosts
}

set_ssh_keys() {
    skip_action set_ssh_keys && return

    local user="$CLOUD_USER"
    local pwent=$(getent passwd "$user")
    local group=$(echo "$pwent" | cut -d: -f4)
    local ssh_dir="$(echo "$pwent" | cut -d: -f6)/.ssh"
    local keys_file="$ssh_dir/authorized_keys"

    if [ ! -d "$ssh_dir" ]; then
        mkdir -p "$ssh_dir"
        chmod 700 "$ssh_dir"
    fi

    touch "$keys_file"
    chmod 600 "$keys_file"
    chown -R "$user:$group" "$ssh_dir"
    imds @ssh-keys > "$keys_file"
}

match_header() {
    local bytes=$(echo -en "$1")
    [ "$bytes" = "$(dd bs=1 count=${#bytes} if="$2" 2>/dev/null)" ]
}

save_userdata() {
    skip_action save_userdata && return

    local userdata="$TINY_CLOUD_VAR/user-data"
    local tmpfile=$(mktemp "$userdata.XXXXXX")
    local cmd

    imds -e @userdata > "$tmpfile"
    cmd="cat"
    if ! skip_action decompress_userdata; then
        if match_header '\037\213\010' "$tmpfile"; then
            cmd="gzip -dc"
        elif match_header 'BZh' "$tmpfile"; then
            cmd="bzip2 -dc"
        elif match_header '\3757zXZ\000' "$tmpfile"; then
            cmd="unxz -c"
        elif match_header '\135\0\0\0' "$tmpfile"; then
            cmd="lzma -dc"
        elif match_header '\211\114\132' "$tmpfile"; then
            cmd="lzop -dc"
        elif match_header '\002!L\030' "$tmpfile"; then
            cmd="lz4 -dc"
        elif match_header '(\265/\375' "$tmpfile"; then
            cmd="zstd -dc"
        fi
    fi
    $cmd "$tmpfile" > "$userdata"
    rm "$tmpfile"
}
