#! /bin/bash

set -e

state_file="/var/lib/yandex-portocontainer/state"
cur_fqdn=`hostname -f`

log() {
    echo "$*"
}

openssh_regen_keys() {
    log "Regenerate OpenSSH keys"
    #rm /etc/ssh/ssh_host_* || true
    #/var/lib/dpkg/info/openssh-server.postinst configure
}

clean() {
    log "Current FQDN: $cur_fqdn"
    
    if [ -e $state_file ]; then
        old_fqdn=`cat $state_file`
        log "Old FQDN: $old_fqdn"
        if [ $old_fqdn = $cur_fqdn ]; then
            log "Old and Current FQDN are matched"
            exit 0
        else
            log "Old and New hostname are not matched"
            force_clean
        fi
    else
        log "File $state_file not found, writing current fqdn"
        force_clean
        exit 0
    fi
}

force_clean() {
    echo $cur_fqdn > $state_file
    openssh_regen_keys
}

case "$1" in
  clean)
        clean
        exit $?
        ;;
  force-clean)
        force_clean
        exit $?
        ;;
  *)
        echo "Usage: $SCRIPTNAME {clean|force-clean}" >&2
        exit 3
        ;;
esac
