#!/bin/sh

VM=openbsd.codevoid.de

restore() {
    [ -z "${ID}" ] && exit 2
    hcloud server rebuild \
        --image ${ID} ${VM}
    sleep 2
    hcloud server poweron ${VM}
}
delete() {
    [ -z "${ID}" ] && exit 2
    printf "Selected:\n%s - %s" "${ID}" "${DESCR}"
    printf "Are you sure [y/N]? "
    read -r _sure
    case $_sure in
        [yY]) hcloud image delete "${ID}"; ;;
    esac
}

save() {
    printf "Description: "
    read -r _desc
    hcloud server create-image ${VM} \
        --type snapshot \
        --description "${_desc}"
    sleep 2
    hcloud server poweron ${VM}
}

list() {
    hcloud image list \
        -o columns=id,description \
        -o noheader \
        -t snapshot
}

console() {
    hcloud server request-console ${VM}
}

get_info() {
    SEL=$(list | fzf)
    [ -z "${SEL}" ] && exit 2
    ID="$(echo "$SEL" | cut -d" " -f1)"
    DESCR="$(echo "$SEL" | cut -d" " -f2- | sed 's/^ *//')"
}

# MAIN PROGRAM
ACTION="$(printf "quit\nturn vm off\nturn vm on\nget console\ndelete snapshot\ncreate snapshot\nrestore vm" | fzf --header="Action for ${VM}")"

case $ACTION in
    delete*)  get_info && delete; ;;
    restore*) get_info && restore; ;;
    create*)  save; ;;
    *console) console; ;;
    turn*on)  hcloud server poweron ${VM}; exit 0; ;;
    turn*off) hcloud server poweroff ${VM}; exit 0; ;;
esac

